@unbrained/pm-cli 2026.10.11 → 2026.10.13

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 (740) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +45 -0
  3. package/dist/cli/after-command-context-usage.d.ts +8 -8
  4. package/dist/cli/bundle-integrity.d.ts +23 -23
  5. package/dist/cli/commander-usage.d.ts +31 -31
  6. package/dist/cli/commander-usage.js +3 -3
  7. package/dist/cli/error-guidance.d.ts +158 -161
  8. package/dist/cli/error-guidance.js +2 -2
  9. package/dist/cli/extension-command-help.d.ts +68 -68
  10. package/dist/cli/extension-command-options.d.ts +20 -20
  11. package/dist/cli/extension-recovery.d.ts +20 -20
  12. package/dist/cli/help-content.d.ts +16 -16
  13. package/dist/cli/help-content.js +2 -2
  14. package/dist/cli/help-json-payload.d.ts +40 -40
  15. package/dist/cli/help-json-payload.js +1 -1
  16. package/dist/cli/invocation-profile.d.ts +8 -8
  17. package/dist/cli/main.d.ts +166 -165
  18. package/dist/cli/main.js +4 -4
  19. package/dist/cli/migration-gates.d.ts +20 -20
  20. package/dist/cli/register-list-query.d.ts +4 -4
  21. package/dist/cli/register-mutation-options.d.ts +2 -2
  22. package/dist/cli/register-operations.d.ts +68 -63
  23. package/dist/cli/register-operations.js +1 -1
  24. package/dist/cli/register-setup.d.ts +1 -1
  25. package/dist/cli/register-structured-mutation.d.ts +3 -3
  26. package/dist/cli/register-structured-mutation.js +1 -1
  27. package/dist/cli/runtime/activation.d.ts +3 -3
  28. package/dist/cli/runtime/invocation-options.js +1 -1
  29. package/dist/cli/runtime/selection.d.ts +6 -6
  30. package/dist/cli/runtime-compatibility-boundary.d.ts +12 -12
  31. package/dist/cli-bundle/bundle-manifest.json +1 -1
  32. package/dist/cli-bundle/chunks/{chunk-K2UTE75T.js → chunk-AM2XOZKE.js} +2 -2
  33. package/dist/cli-bundle/chunks/{chunk-S445XEYT.js → chunk-APWPC4ZZ.js} +2 -2
  34. package/dist/cli-bundle/chunks/chunk-DJDRHJBP.js +234 -0
  35. package/dist/cli-bundle/chunks/{chunk-RUT3CCAG.js → chunk-DUK5DHI6.js} +2 -2
  36. package/dist/cli-bundle/chunks/chunk-HXHFKXLV.js +2 -0
  37. package/dist/cli-bundle/chunks/chunk-IFPJDJUM.js +20 -0
  38. package/dist/cli-bundle/chunks/{chunk-OBLO45UM.js → chunk-LBDWFWPK.js} +2 -2
  39. package/dist/cli-bundle/chunks/{chunk-ZWRLAOA4.js → chunk-N5EXRYCZ.js} +2 -2
  40. package/dist/cli-bundle/chunks/chunk-PSNS537F.js +30 -0
  41. package/dist/cli-bundle/chunks/{chunk-2JYTSTQP.js → chunk-RL45OYTL.js} +2 -2
  42. package/dist/cli-bundle/chunks/{chunk-ESRACL6K.js → chunk-UBTYYZIE.js} +49 -49
  43. package/dist/cli-bundle/chunks/chunk-WYZGZV2M.js +2 -0
  44. package/dist/cli-bundle/chunks/{chunk-SSY4OSJR.js → chunk-YH6H3UVE.js} +10 -10
  45. package/dist/cli-bundle/chunks/{register-list-query-T6BOR67M.js → register-list-query-BJ742QOR.js} +2 -2
  46. package/dist/cli-bundle/chunks/{register-mutation-6NXR7SAJ.js → register-mutation-GGGBRIH2.js} +3 -3
  47. package/dist/cli-bundle/chunks/register-operations-E6HXYHNM.js +2 -0
  48. package/dist/cli-bundle/chunks/{register-setup-MAYFPKBX.js → register-setup-4ZVTVEPY.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-EIOQNLBQ.js → chunk-3LQEBXU5.js} +12 -12
  50. package/dist/cli-bundle/focused-chunks/{chunk-PLTTMQAW.js → chunk-6BTUISKV.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/chunk-73UNAJHD.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/{chunk-WAOXID5J.js → chunk-DVK7VKZL.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-SIEGIPNT.js → chunk-F5J3ATMV.js} +16 -16
  54. package/dist/cli-bundle/focused-chunks/chunk-IIKFTJVC.js +2 -0
  55. package/dist/cli-bundle/focused-chunks/chunk-IOTNG6CN.js +2 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-AU6VJGTY.js → chunk-KGFRQ34R.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/chunk-NNW5BS5L.js +3 -0
  58. package/dist/cli-bundle/focused-chunks/{chunk-KNJR2WUO.js → chunk-QMNAY25P.js} +62 -62
  59. package/dist/cli-bundle/focused-chunks/{chunk-W5AE7GKZ.js → chunk-R23T7GFZ.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/chunk-RAA7SVRA.js +8 -0
  61. package/dist/cli-bundle/focused-chunks/{chunk-52UJEHEV.js → chunk-RU6GCFN3.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{chunk-JGFSSR3G.js → chunk-S6ITXQ5T.js} +5 -5
  63. package/dist/cli-bundle/focused-chunks/{chunk-DMSADMEU.js → chunk-SOB7X4FJ.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/chunk-UPJA45K7.js +26 -0
  65. package/dist/cli-bundle/main.js +22 -22
  66. package/dist/cli-bundle/sdk-authoring.js +1 -1
  67. package/dist/cli-bundle/sdk-contracts.js +2 -2
  68. package/dist/cli-bundle/sdk-core.js +31 -31
  69. package/dist/cli-bundle/sdk-governance.js +1 -1
  70. package/dist/cli-bundle/sdk-graph.js +1 -1
  71. package/dist/cli-bundle/sdk-merge.js +51 -51
  72. package/dist/cli-bundle/sdk-query.js +1 -1
  73. package/dist/cli-bundle/sdk-runtime.js +1 -1
  74. package/dist/cli-bundle/sdk-testing.js +1 -1
  75. package/dist/cli-bundle/sdk.js +8 -8
  76. package/dist/cli.d.ts +4 -4
  77. package/dist/core/checkpoint/checkpoint-gc.d.ts +32 -32
  78. package/dist/core/checkpoint/mutation-checkpoint.d.ts +34 -34
  79. package/dist/core/config/nested-settings.d.ts +26 -26
  80. package/dist/core/config/positional-value.d.ts +16 -16
  81. package/dist/core/diagnostics/remediation.d.ts +6 -6
  82. package/dist/core/diagnostics/remediation.js +1 -1
  83. package/dist/core/extensions/activation-summary-markdown.d.ts +6 -6
  84. package/dist/core/extensions/activation-summary.d.ts +54 -54
  85. package/dist/core/extensions/activation-transaction.d.ts +7 -7
  86. package/dist/core/extensions/capability-usage.d.ts +26 -26
  87. package/dist/core/extensions/command-hook-context.d.ts +26 -26
  88. package/dist/core/extensions/contribution-inventory.d.ts +21 -21
  89. package/dist/core/extensions/extension-candidate.d.ts +14 -14
  90. package/dist/core/extensions/extension-capability-aliases.d.ts +2 -2
  91. package/dist/core/extensions/extension-policy.d.ts +80 -80
  92. package/dist/core/extensions/extension-types.d.ts +1294 -1285
  93. package/dist/core/extensions/extension-types.js +1 -1
  94. package/dist/core/extensions/flag-definition-validation.d.ts +4 -4
  95. package/dist/core/extensions/item-fields.d.ts +3 -2
  96. package/dist/core/extensions/item-fields.js +1 -1
  97. package/dist/core/extensions/loader.d.ts +36 -36
  98. package/dist/core/extensions/loader.js +1 -1
  99. package/dist/core/extensions/manifest-schema.d.ts +16 -16
  100. package/dist/core/extensions/module-graph-snapshot.d.ts +8 -8
  101. package/dist/core/extensions/read-output-contract.d.ts +5 -0
  102. package/dist/core/extensions/read-output-contract.js +2 -0
  103. package/dist/core/extensions/registration-values.d.ts +1 -1
  104. package/dist/core/extensions/reserved-host-flags.d.ts +6 -6
  105. package/dist/core/extensions/version-compat.d.ts +10 -10
  106. package/dist/core/fs/fs-utils.d.ts +1 -1
  107. package/dist/core/fs/host-environment-errors.d.ts +14 -14
  108. package/dist/core/governance/content-fields.d.ts +31 -31
  109. package/dist/core/governance/issue-codes.d.ts +27 -27
  110. package/dist/core/governance/metadata-coverage.d.ts +91 -91
  111. package/dist/core/history/drift-scan.d.ts +26 -26
  112. package/dist/core/history/event-classification.d.ts +1 -1
  113. package/dist/core/history/event-classification.js +1 -1
  114. package/dist/core/history/event-index.d.ts +41 -41
  115. package/dist/core/history/history-compact-bulk.d.ts +22 -22
  116. package/dist/core/history/history-diff.d.ts +22 -22
  117. package/dist/core/history/history-rewrite.d.ts +66 -66
  118. package/dist/core/history/history-storage-stats.d.ts +31 -31
  119. package/dist/core/history/history-stream-policy.d.ts +12 -12
  120. package/dist/core/history/history.d.ts +22 -22
  121. package/dist/core/history/identity.d.ts +6 -6
  122. package/dist/core/history/operation-contract.d.ts +9 -9
  123. package/dist/core/history/projection.d.ts +15 -15
  124. package/dist/core/history/read.d.ts +4 -4
  125. package/dist/core/history/replay.d.ts +51 -49
  126. package/dist/core/history/replay.js +1 -1
  127. package/dist/core/history/workspace-history.d.ts +101 -101
  128. package/dist/core/io/bulk-ids-input.d.ts +4 -4
  129. package/dist/core/item/actionability.d.ts +40 -40
  130. package/dist/core/item/id.d.ts +3 -3
  131. package/dist/core/item/item-format-version.d.ts +8 -8
  132. package/dist/core/item/item-format.d.ts +37 -35
  133. package/dist/core/item/item-format.js +2 -2
  134. package/dist/core/item/item-type-definition.d.ts +2 -2
  135. package/dist/core/item/parent-reference-policy.d.ts +1 -1
  136. package/dist/core/item/parse.d.ts +12 -12
  137. package/dist/core/item/sprint-release-format.d.ts +2 -2
  138. package/dist/core/item/status-filter.d.ts +4 -4
  139. package/dist/core/item/toon-decode.d.ts +9 -9
  140. package/dist/core/item/type-registry.d.ts +40 -40
  141. package/dist/core/lock/lock-gc.d.ts +50 -50
  142. package/dist/core/lock/lock.d.ts +37 -37
  143. package/dist/core/output/mutation-projection.d.ts +6 -6
  144. package/dist/core/output/output-control.d.ts +4 -4
  145. package/dist/core/output/output.d.ts +40 -40
  146. package/dist/core/output/query-summary.d.ts +5 -5
  147. package/dist/core/packages/manifest.d.ts +50 -50
  148. package/dist/core/policy/workflow-policy-schema.d.ts +306 -306
  149. package/dist/core/policy/workflow-policy-store.d.ts +7 -7
  150. package/dist/core/policy/workflow-policy.d.ts +81 -81
  151. package/dist/core/profile/profile-describe.d.ts +40 -40
  152. package/dist/core/profile/profile-lint.d.ts +20 -20
  153. package/dist/core/profile/profile-plan.d.ts +84 -84
  154. package/dist/core/profile/profile-presets.d.ts +52 -52
  155. package/dist/core/reproducibility/context.d.ts +6 -6
  156. package/dist/core/schema/fields-file.d.ts +54 -54
  157. package/dist/core/schema/item-types-file.d.ts +36 -36
  158. package/dist/core/schema/runtime-field-values.d.ts +2 -2
  159. package/dist/core/schema/runtime-schema.d.ts +86 -86
  160. package/dist/core/schema/status-defs-file.d.ts +36 -36
  161. package/dist/core/schema/type-inference.d.ts +14 -14
  162. package/dist/core/schema/type-workflows.d.ts +22 -22
  163. package/dist/core/search/background-refresh.d.ts +9 -9
  164. package/dist/core/search/bm25.d.ts +19 -19
  165. package/dist/core/search/cache.d.ts +35 -35
  166. package/dist/core/search/corpus.d.ts +12 -12
  167. package/dist/core/search/embedding-batches.d.ts +48 -48
  168. package/dist/core/search/eval.d.ts +49 -49
  169. package/dist/core/search/http-client.d.ts +38 -38
  170. package/dist/core/search/providers.d.ts +41 -41
  171. package/dist/core/search/relevance.d.ts +20 -20
  172. package/dist/core/search/semantic-defaults.d.ts +8 -8
  173. package/dist/core/search/staleness.d.ts +4 -4
  174. package/dist/core/search/vector-stores.d.ts +78 -78
  175. package/dist/core/search/vectorization-metadata.d.ts +6 -6
  176. package/dist/core/sentry/helpers.d.ts +15 -15
  177. package/dist/core/sentry/instrument.d.ts +40 -40
  178. package/dist/core/session/session-state.d.ts +32 -32
  179. package/dist/core/shared/agent-session-context.d.ts +14 -14
  180. package/dist/core/shared/author.d.ts +128 -128
  181. package/dist/core/shared/command-types.d.ts +40 -40
  182. package/dist/core/shared/conflict-markers.d.ts +6 -6
  183. package/dist/core/shared/constants.d.ts +13 -13
  184. package/dist/core/shared/errors.d.ts +194 -183
  185. package/dist/core/shared/errors.js +1 -1
  186. package/dist/core/shared/secret-rules.d.ts +97 -97
  187. package/dist/core/shared/serial-queue.d.ts +8 -8
  188. package/dist/core/shared/split-comma-list.d.ts +6 -6
  189. package/dist/core/shared/time.d.ts +23 -23
  190. package/dist/core/store/item-format-migration.d.ts +10 -10
  191. package/dist/core/store/item-metadata-cache.d.ts +38 -38
  192. package/dist/core/store/item-metadata-query-index.d.ts +79 -79
  193. package/dist/core/store/item-metadata-read-work.d.ts +6 -6
  194. package/dist/core/store/item-store.d.ts +110 -110
  195. package/dist/core/store/paths.d.ts +2 -2
  196. package/dist/core/store/settings-read-cache.d.ts +12 -12
  197. package/dist/core/store/settings-validator.d.ts +165 -165
  198. package/dist/core/store/settings.d.ts +59 -59
  199. package/dist/core/telemetry/observability.d.ts +17 -17
  200. package/dist/core/telemetry/policy.d.ts +3 -3
  201. package/dist/core/telemetry/runtime.d.ts +242 -242
  202. package/dist/core/telemetry/runtime.js +2 -2
  203. package/dist/core/test/background-runs.d.ts +186 -185
  204. package/dist/core/test/background-runs.js +2 -2
  205. package/dist/core/test/item-test-run-tracking.d.ts +6 -6
  206. package/dist/core/test/run-selectors.d.ts +18 -18
  207. package/dist/core/validate/fix-planning.d.ts +50 -50
  208. package/dist/core/validate/missing-by-type.d.ts +4 -4
  209. package/dist/core/validate/missing-link-owners.d.ts +30 -30
  210. package/dist/core/validate/stale-file-classification.d.ts +8 -8
  211. package/dist/mcp/http-server.d.ts +28 -28
  212. package/dist/mcp/legacy-adapter.d.ts +33 -33
  213. package/dist/mcp/runtime-capabilities.d.ts +16 -16
  214. package/dist/mcp/server.d.ts +50 -50
  215. package/dist/mcp/tool-definitions.d.ts +36 -36
  216. package/dist/sdk/agent/closed-domain-contracts.d.ts +18 -18
  217. package/dist/sdk/agent/command-recovery.d.ts +4 -0
  218. package/dist/sdk/agent/command-recovery.js +1 -1
  219. package/dist/sdk/agent/command-suggestions.d.ts +2 -0
  220. package/dist/sdk/agent/command-suggestions.js +1 -1
  221. package/dist/sdk/agent/identity-config.d.ts +32 -32
  222. package/dist/sdk/agent/item-addressing.d.ts +8 -8
  223. package/dist/sdk/agent/refusal-closure-census.d.ts +34 -34
  224. package/dist/sdk/agent/refusal-closure.d.ts +42 -42
  225. package/dist/sdk/agent/refusal-corpus-contracts.d.ts +46 -46
  226. package/dist/sdk/agent/refusal-reachability.d.ts +112 -112
  227. package/dist/sdk/agent/subcommand-recovery.d.ts +25 -25
  228. package/dist/sdk/agent/task-transcript-contracts.d.ts +30 -30
  229. package/dist/sdk/agent/tracker-preflight-contracts.d.ts +38 -38
  230. package/dist/sdk/agent-capability-contracts.d.ts +37 -37
  231. package/dist/sdk/annotations.d.ts +106 -106
  232. package/dist/sdk/author-attribution.d.ts +76 -76
  233. package/dist/sdk/authoring.d.ts +1 -1
  234. package/dist/sdk/authoring.js +1 -1
  235. package/dist/sdk/cli-bootstrap.d.ts +70 -70
  236. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +63 -63
  237. package/dist/sdk/cli-contracts/command-aliases.d.ts +14 -14
  238. package/dist/sdk/cli-contracts/command-exit-contracts.d.ts +70 -70
  239. package/dist/sdk/cli-contracts/commander-types.d.ts +17 -17
  240. package/dist/sdk/cli-contracts/completeness.d.ts +26 -26
  241. package/dist/sdk/cli-contracts/enum-contracts.d.ts +5 -5
  242. package/dist/sdk/cli-contracts/flag-contracts.d.ts +32 -32
  243. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  244. package/dist/sdk/cli-contracts/flag-lexicon-contracts.d.ts +42 -42
  245. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  246. package/dist/sdk/cli-contracts/grammar-contracts.d.ts +84 -84
  247. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  248. package/dist/sdk/cli-contracts/registration-helpers.d.ts +37 -40
  249. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  250. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +290 -294
  251. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  252. package/dist/sdk/cli-contracts/schemas/assurance-definition.d.ts +793 -793
  253. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +391 -391
  254. package/dist/sdk/cli-contracts/tool-parameter-tables.d.ts +6 -6
  255. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  256. package/dist/sdk/cli-contracts/tool-schema.d.ts +55 -55
  257. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  258. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +24 -24
  259. package/dist/sdk/comments.d.ts +44 -44
  260. package/dist/sdk/compile-cache.d.ts +4 -4
  261. package/dist/sdk/completion/shared.d.ts +22 -22
  262. package/dist/sdk/compose.d.ts +156 -156
  263. package/dist/sdk/config.d.ts +123 -123
  264. package/dist/sdk/context/semantic-session-attribution.d.ts +14 -14
  265. package/dist/sdk/context/usage-ledger.d.ts +20 -20
  266. package/dist/sdk/context-intent-contracts.d.ts +50 -50
  267. package/dist/sdk/context-intent-contracts.js +1 -1
  268. package/dist/sdk/context-intent-runtime.d.ts +8 -8
  269. package/dist/sdk/context-packing.d.ts +78 -78
  270. package/dist/sdk/context-relevance.d.ts +189 -180
  271. package/dist/sdk/context-relevance.js +1 -1
  272. package/dist/sdk/context-signal-store.d.ts +84 -84
  273. package/dist/sdk/context-usage.d.ts +92 -92
  274. package/dist/sdk/core.d.ts +1 -0
  275. package/dist/sdk/core.js +1 -1
  276. package/dist/sdk/corpus-shape.d.ts +101 -101
  277. package/dist/sdk/define.d.ts +2 -2
  278. package/dist/sdk/dependencies.d.ts +116 -116
  279. package/dist/sdk/dependency-flag-validation.d.ts +14 -12
  280. package/dist/sdk/dependency-flag-validation.js +1 -1
  281. package/dist/sdk/dependency-provenance.d.ts +30 -30
  282. package/dist/sdk/docs.d.ts +32 -32
  283. package/dist/sdk/duplicates.d.ts +21 -21
  284. package/dist/sdk/environment/agent-environment.d.ts +196 -196
  285. package/dist/sdk/environment/project-runtime-compatibility.d.ts +56 -56
  286. package/dist/sdk/environment/source-context.d.ts +6 -6
  287. package/dist/sdk/error-code-catalog.d.ts +40 -40
  288. package/dist/sdk/errors.d.ts +29 -29
  289. package/dist/sdk/eval.d.ts +45 -45
  290. package/dist/sdk/extension/author-manifest.d.ts +14 -14
  291. package/dist/sdk/extension/bundled-catalog.d.ts +7 -7
  292. package/dist/sdk/extension/describe.d.ts +36 -36
  293. package/dist/sdk/extension/doctor.d.ts +29 -29
  294. package/dist/sdk/extension/install-plan.d.ts +55 -55
  295. package/dist/sdk/extension/install-receipts.d.ts +2 -2
  296. package/dist/sdk/extension/install-runtime.d.ts +8 -8
  297. package/dist/sdk/extension/install-snapshot.d.ts +14 -14
  298. package/dist/sdk/extension/install-sources.d.ts +96 -96
  299. package/dist/sdk/extension/managed-state.d.ts +66 -66
  300. package/dist/sdk/extension/migrations.d.ts +82 -82
  301. package/dist/sdk/extension/output-ownership.d.ts +24 -24
  302. package/dist/sdk/extension/runtime-summary.d.ts +5 -5
  303. package/dist/sdk/extension/scaffold.d.ts +12 -12
  304. package/dist/sdk/extension/shared.d.ts +15 -15
  305. package/dist/sdk/extension/source-resolution.d.ts +30 -30
  306. package/dist/sdk/extension/static-inventory.d.ts +42 -42
  307. package/dist/sdk/extension/update-check.d.ts +10 -10
  308. package/dist/sdk/extension.d.ts +320 -320
  309. package/dist/sdk/files.d.ts +157 -157
  310. package/dist/sdk/flag-invocation-contracts.d.ts +44 -44
  311. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  312. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  313. package/dist/sdk/governance/artifact-ledgers.d.ts +35 -35
  314. package/dist/sdk/governance/artifact-ledgers.js +1 -1
  315. package/dist/sdk/governance/assurance-action.d.ts +68 -68
  316. package/dist/sdk/governance/assurance-action.js +1 -1
  317. package/dist/sdk/governance/assurance-mutation-error.d.ts +36 -36
  318. package/dist/sdk/governance/assurance-presets.d.ts +24 -24
  319. package/dist/sdk/governance/assurance-runtime.d.ts +14 -14
  320. package/dist/sdk/governance/assurance.d.ts +353 -353
  321. package/dist/sdk/governance/boundary-fixtures.d.ts +60 -60
  322. package/dist/sdk/governance/closure-timestamps.d.ts +9 -9
  323. package/dist/sdk/governance/coverage-assurance.d.ts +10 -10
  324. package/dist/sdk/governance/defect-recurrence-coverage.d.ts +75 -75
  325. package/dist/sdk/governance/defect-recurrence-graph.d.ts +18 -18
  326. package/dist/sdk/governance/defect-recurrence.d.ts +186 -181
  327. package/dist/sdk/governance/defect-recurrence.js +1 -1
  328. package/dist/sdk/governance/extension-host-version.d.ts +16 -16
  329. package/dist/sdk/governance/gc.d.ts +48 -48
  330. package/dist/sdk/governance/health-merge-evidence.d.ts +5 -5
  331. package/dist/sdk/governance/health.d.ts +188 -188
  332. package/dist/sdk/governance/hierarchy-validation.d.ts +13 -13
  333. package/dist/sdk/governance/linked-file-report.d.ts +26 -26
  334. package/dist/sdk/governance/merge-receipt-history.d.ts +36 -36
  335. package/dist/sdk/governance/provenance-health.d.ts +64 -64
  336. package/dist/sdk/governance/reindex.d.ts +89 -89
  337. package/dist/sdk/governance/reliability.d.ts +56 -56
  338. package/dist/sdk/governance/stale-work.d.ts +22 -22
  339. package/dist/sdk/governance/status-role-diagnostics.d.ts +12 -12
  340. package/dist/sdk/governance/storage-integrity.d.ts +54 -54
  341. package/dist/sdk/governance/tracked-runtime-cache.d.ts +10 -10
  342. package/dist/sdk/governance/upgrade.d.ts +104 -104
  343. package/dist/sdk/governance/validate-history-drift.d.ts +2 -2
  344. package/dist/sdk/governance/validate-item-reader.d.ts +6 -6
  345. package/dist/sdk/governance/validate.d.ts +191 -191
  346. package/dist/sdk/governance/workflow-completeness.d.ts +15 -15
  347. package/dist/sdk/governance/workflow-policy.d.ts +28 -28
  348. package/dist/sdk/governance/workspace-position.d.ts +46 -46
  349. package/dist/sdk/graph/adapter.d.ts +66 -66
  350. package/dist/sdk/graph/analytics.d.ts +54 -54
  351. package/dist/sdk/graph/assembly.d.ts +80 -80
  352. package/dist/sdk/graph/cache.d.ts +29 -29
  353. package/dist/sdk/graph/cardinality-integrity.d.ts +13 -0
  354. package/dist/sdk/graph/cardinality-integrity.js +2 -0
  355. package/dist/sdk/graph/centrality.d.ts +34 -34
  356. package/dist/sdk/graph/conformance.d.ts +33 -33
  357. package/dist/sdk/graph/deadline-scheduling.d.ts +58 -58
  358. package/dist/sdk/graph/durable-cache.d.ts +26 -26
  359. package/dist/sdk/graph/governance.d.ts +165 -165
  360. package/dist/sdk/graph/hierarchy-integrity.d.ts +52 -52
  361. package/dist/sdk/graph/index.d.ts +1 -0
  362. package/dist/sdk/graph/index.js +1 -1
  363. package/dist/sdk/graph/lifecycle-coverage.d.ts +17 -17
  364. package/dist/sdk/graph/mutation-advisory.d.ts +11 -11
  365. package/dist/sdk/graph/query-contracts.d.ts +10 -10
  366. package/dist/sdk/graph/remediation.d.ts +25 -25
  367. package/dist/sdk/graph/run.d.ts +392 -392
  368. package/dist/sdk/graph/scheduling.d.ts +38 -38
  369. package/dist/sdk/graph/traversal.d.ts +14 -14
  370. package/dist/sdk/guide-topics.d.ts +32 -32
  371. package/dist/sdk/guide.d.ts +62 -62
  372. package/dist/sdk/history/attestation-command.d.ts +12 -12
  373. package/dist/sdk/history/attestation-contract.d.ts +78 -78
  374. package/dist/sdk/history/attestation-scan.d.ts +6 -6
  375. package/dist/sdk/history/maintenance.d.ts +46 -46
  376. package/dist/sdk/history/salvage.d.ts +18 -18
  377. package/dist/sdk/history/subject.d.ts +9 -9
  378. package/dist/sdk/history-analytics.d.ts +84 -84
  379. package/dist/sdk/history-compact.d.ts +103 -103
  380. package/dist/sdk/history-mcp.d.ts +8 -8
  381. package/dist/sdk/history-provenance.d.ts +59 -59
  382. package/dist/sdk/history-read.d.ts +36 -36
  383. package/dist/sdk/history-redact.d.ts +78 -78
  384. package/dist/sdk/history-repair.d.ts +158 -158
  385. package/dist/sdk/history-repair.js +1 -1
  386. package/dist/sdk/improvement-ledger.d.ts +102 -102
  387. package/dist/sdk/index.d.ts +2 -0
  388. package/dist/sdk/index.js +1 -1
  389. package/dist/sdk/init-agent-guidance.d.ts +70 -70
  390. package/dist/sdk/init.d.ts +152 -152
  391. package/dist/sdk/item-children.d.ts +28 -28
  392. package/dist/sdk/item-schedule.d.ts +12 -12
  393. package/dist/sdk/item-transaction.d.ts +100 -100
  394. package/dist/sdk/learnings.d.ts +42 -42
  395. package/dist/sdk/lifecycle/append.d.ts +14 -14
  396. package/dist/sdk/lifecycle/claim.d.ts +60 -60
  397. package/dist/sdk/lifecycle/close-many.d.ts +94 -94
  398. package/dist/sdk/lifecycle/close.d.ts +27 -27
  399. package/dist/sdk/lifecycle/copy.d.ts +18 -18
  400. package/dist/sdk/lifecycle/core-field-recovery.d.ts +7 -0
  401. package/dist/sdk/lifecycle/core-field-recovery.js +2 -0
  402. package/dist/sdk/lifecycle/create.d.ts +82 -82
  403. package/dist/sdk/lifecycle/create.js +1 -1
  404. package/dist/sdk/lifecycle/delete.d.ts +28 -28
  405. package/dist/sdk/lifecycle/focus.d.ts +10 -10
  406. package/dist/sdk/lifecycle/hierarchy-mutation-lock.d.ts +10 -10
  407. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  408. package/dist/sdk/lifecycle/legacy-none-tokens.d.ts +54 -54
  409. package/dist/sdk/lifecycle/lifecycle-transitions.d.ts +4 -4
  410. package/dist/sdk/lifecycle/mcp-actions.d.ts +10 -10
  411. package/dist/sdk/lifecycle/mutation-command-options.d.ts +116 -116
  412. package/dist/sdk/lifecycle/mutation-facet-contracts.d.ts +6 -0
  413. package/dist/sdk/lifecycle/mutation-facet-contracts.js +2 -0
  414. package/dist/sdk/lifecycle/plan-mutation-receipt.d.ts +42 -42
  415. package/dist/sdk/lifecycle/plan.d.ts +217 -217
  416. package/dist/sdk/lifecycle/reopen.d.ts +29 -24
  417. package/dist/sdk/lifecycle/reopen.js +1 -1
  418. package/dist/sdk/lifecycle/repeatable-metadata-parsers.d.ts +3 -3
  419. package/dist/sdk/lifecycle/restore.d.ts +33 -33
  420. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +19 -19
  421. package/dist/sdk/lifecycle/task-composition.d.ts +4 -4
  422. package/dist/sdk/lifecycle/update-many.d.ts +79 -79
  423. package/dist/sdk/lifecycle/update.d.ts +131 -132
  424. package/dist/sdk/lifecycle/update.js +2 -2
  425. package/dist/sdk/lifecycle-completion.d.ts +22 -22
  426. package/dist/sdk/lifecycle-policy.d.ts +52 -52
  427. package/dist/sdk/linked-artifacts.d.ts +69 -69
  428. package/dist/sdk/mcp/apps.d.ts +32 -32
  429. package/dist/sdk/mcp/authorization.d.ts +76 -76
  430. package/dist/sdk/mcp/discovery.d.ts +111 -111
  431. package/dist/sdk/mcp/interactions.d.ts +61 -61
  432. package/dist/sdk/mcp/protocol.d.ts +78 -78
  433. package/dist/sdk/mcp/skills.d.ts +88 -88
  434. package/dist/sdk/mcp/subscriptions.d.ts +39 -39
  435. package/dist/sdk/mcp/tasks.d.ts +75 -75
  436. package/dist/sdk/mcp/transport.d.ts +11 -11
  437. package/dist/sdk/merge/abandoned-receipts.d.ts +6 -6
  438. package/dist/sdk/merge/driver.d.ts +60 -60
  439. package/dist/sdk/merge/install.d.ts +64 -64
  440. package/dist/sdk/merge/receipt-file-boundary.d.ts +5 -5
  441. package/dist/sdk/merge/receipt-operation.d.ts +6 -6
  442. package/dist/sdk/merge/receipt-schema.d.ts +2 -2
  443. package/dist/sdk/merge/receipts.d.ts +156 -156
  444. package/dist/sdk/merge/reconcile.d.ts +36 -36
  445. package/dist/sdk/merge/reconcile.js +1 -1
  446. package/dist/sdk/merge/three-way.d.ts +77 -76
  447. package/dist/sdk/merge/three-way.js +1 -1
  448. package/dist/sdk/mutation-events.d.ts +84 -84
  449. package/dist/sdk/mutation-guard.d.ts +106 -106
  450. package/dist/sdk/notes.d.ts +52 -52
  451. package/dist/sdk/output/table-rows.d.ts +8 -8
  452. package/dist/sdk/output-contracts.d.ts +38 -38
  453. package/dist/sdk/output-projection.d.ts +142 -142
  454. package/dist/sdk/output-token-accounting.d.ts +27 -27
  455. package/dist/sdk/output.d.ts +28 -28
  456. package/dist/sdk/package-import-adapters.d.ts +54 -54
  457. package/dist/sdk/pagination.d.ts +29 -29
  458. package/dist/sdk/profile.d.ts +123 -123
  459. package/dist/sdk/provenance.d.ts +58 -58
  460. package/dist/sdk/public-surface.json +1 -1
  461. package/dist/sdk/query/activity.d.ts +118 -118
  462. package/dist/sdk/query/aggregate.d.ts +140 -140
  463. package/dist/sdk/query/calendar.d.ts +144 -144
  464. package/dist/sdk/query/complete-list.d.ts +53 -53
  465. package/dist/sdk/query/context.d.ts +395 -395
  466. package/dist/sdk/query/duplicate-candidates.d.ts +1 -1
  467. package/dist/sdk/query/get.d.ts +77 -77
  468. package/dist/sdk/query/history.d.ts +72 -72
  469. package/dist/sdk/query/item-filter-options.d.ts +79 -79
  470. package/dist/sdk/query/list-filter-shared.d.ts +1 -1
  471. package/dist/sdk/query/list.d.ts +188 -188
  472. package/dist/sdk/query/multi-value-filters.d.ts +4 -4
  473. package/dist/sdk/query/next-ready-budget.d.ts +14 -14
  474. package/dist/sdk/query/next.d.ts +137 -137
  475. package/dist/sdk/query/projection-contracts.d.ts +8 -8
  476. package/dist/sdk/query/search/corpus.d.ts +8 -8
  477. package/dist/sdk/query/search/filters.d.ts +5 -5
  478. package/dist/sdk/query/search/input.d.ts +4 -4
  479. package/dist/sdk/query/search/response.d.ts +8 -8
  480. package/dist/sdk/query/search/semantic.d.ts +106 -106
  481. package/dist/sdk/query/search/types.d.ts +85 -85
  482. package/dist/sdk/query/search-contracts.d.ts +65 -65
  483. package/dist/sdk/query/search-pagination.d.ts +19 -19
  484. package/dist/sdk/query/search-rendering.d.ts +25 -25
  485. package/dist/sdk/query/search.d.ts +46 -46
  486. package/dist/sdk/read-output/continuation.d.ts +8 -8
  487. package/dist/sdk/read-output/continuation.js +1 -1
  488. package/dist/sdk/read-output/extension.d.ts +7 -0
  489. package/dist/sdk/read-output/extension.js +2 -0
  490. package/dist/sdk/read-output/options.d.ts +6 -4
  491. package/dist/sdk/read-output/options.js +1 -1
  492. package/dist/sdk/read-output/provenance.d.ts +8 -8
  493. package/dist/sdk/read-output-budget.d.ts +10 -10
  494. package/dist/sdk/read-output-contracts.d.ts +192 -186
  495. package/dist/sdk/read-output-contracts.js +1 -1
  496. package/dist/sdk/read-output-rows.d.ts +6 -6
  497. package/dist/sdk/read-output-session.d.ts +50 -50
  498. package/dist/sdk/relationship-analytics.d.ts +78 -78
  499. package/dist/sdk/relationship-context.d.ts +81 -81
  500. package/dist/sdk/relationship-history.d.ts +109 -109
  501. package/dist/sdk/relationship-kinds/contract.d.ts +34 -34
  502. package/dist/sdk/relationship-migration.d.ts +26 -26
  503. package/dist/sdk/relationships.d.ts +78 -78
  504. package/dist/sdk/reproducibility/process.d.ts +3 -3
  505. package/dist/sdk/runtime/context.d.ts +11 -11
  506. package/dist/sdk/runtime-action-aliases.d.ts +2 -2
  507. package/dist/sdk/runtime-extended-actions.d.ts +8 -8
  508. package/dist/sdk/runtime-input.d.ts +3 -3
  509. package/dist/sdk/runtime-public-contracts.d.ts +78 -78
  510. package/dist/sdk/runtime.d.ts +305 -305
  511. package/dist/sdk/runtime.js +1 -1
  512. package/dist/sdk/scheduling-shortcuts.d.ts +32 -32
  513. package/dist/sdk/schema-migration.d.ts +86 -86
  514. package/dist/sdk/schema.d.ts +355 -355
  515. package/dist/sdk/similarity-scoring.d.ts +10 -10
  516. package/dist/sdk/similarity.d.ts +113 -113
  517. package/dist/sdk/stats.d.ts +108 -108
  518. package/dist/sdk/structured-mutations.d.ts +16 -16
  519. package/dist/sdk/structured-mutations.js +1 -1
  520. package/dist/sdk/telemetry.d.ts +53 -53
  521. package/dist/sdk/templates.d.ts +39 -39
  522. package/dist/sdk/test/batch.d.ts +85 -85
  523. package/dist/sdk/test/batch.js +1 -1
  524. package/dist/sdk/test/command-args.d.ts +4 -0
  525. package/dist/sdk/test/command-args.js +2 -0
  526. package/dist/sdk/test/entry.d.ts +3 -0
  527. package/dist/sdk/test/entry.js +1 -1
  528. package/dist/sdk/test/execution-receipts.d.ts +3 -3
  529. package/dist/sdk/test/execution.d.ts +279 -268
  530. package/dist/sdk/test/execution.js +2 -2
  531. package/dist/sdk/test/json-path.d.ts +2 -2
  532. package/dist/sdk/test/linked-command-detection.d.ts +10 -10
  533. package/dist/sdk/test/measurements.d.ts +11 -11
  534. package/dist/sdk/test/parsers.d.ts +1 -1
  535. package/dist/sdk/test/parsers.js +1 -1
  536. package/dist/sdk/test/prerequisites.d.ts +6 -0
  537. package/dist/sdk/test/prerequisites.js +2 -0
  538. package/dist/sdk/test/runs.d.ts +52 -52
  539. package/dist/sdk/test/trust.d.ts +12 -12
  540. package/dist/sdk/test/trust.js +1 -1
  541. package/dist/sdk/test/update.d.ts +55 -0
  542. package/dist/sdk/test/update.js +2 -0
  543. package/dist/sdk/testing.d.ts +319 -319
  544. package/dist/sdk/traceability/source-traceability.d.ts +65 -65
  545. package/dist/sdk/workspace-contracts.d.ts +37 -37
  546. package/dist/sdk/workspace-memory.d.ts +60 -60
  547. package/dist/sdk/workspace-recipe.d.ts +9 -9
  548. package/dist/sdk/workspace-snapshot.d.ts +97 -97
  549. package/dist/sdk/workspace-transaction-gc.d.ts +32 -32
  550. package/dist/sdk/workspace-transaction.d.ts +47 -47
  551. package/dist/sdk/workspace.d.ts +6 -6
  552. package/dist/types.d.ts +978 -974
  553. package/dist/types.js +1 -1
  554. package/docs/BUILD_AND_RELEASE_ACCEPTANCE.md +5 -2
  555. package/docs/DEFECT_RECURRENCE.md +12 -0
  556. package/docs/EXTENSIONS.md +2 -2
  557. package/docs/LINKED_TEST_EDITS.md +79 -0
  558. package/docs/MERGE_SAFETY.md +27 -1
  559. package/docs/RECURRENCE_RECOVERY_CONTRACTS.md +17 -4
  560. package/docs/RELATIONSHIP_GRAPH.md +26 -0
  561. package/docs/RELEASING.md +25 -8
  562. package/docs/SDK.md +204 -637
  563. package/docs/SDK_CONSUMER_RECEIPTS.md +67 -0
  564. package/docs/SDK_EVIDENCE_TRACEABILITY.md +4 -0
  565. package/docs/TESTING.md +13 -0
  566. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  567. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +11 -3
  568. package/docs/performance/runner-qualification.md +36 -0
  569. package/marketplace.json +1 -1
  570. package/node_modules/@opentelemetry/core/build/esm/version.d.ts +1 -1
  571. package/node_modules/@opentelemetry/core/build/esm/version.js +1 -1
  572. package/node_modules/@opentelemetry/core/build/esnext/version.d.ts +1 -1
  573. package/node_modules/@opentelemetry/core/build/esnext/version.js +1 -1
  574. package/node_modules/@opentelemetry/core/build/src/version.d.ts +1 -1
  575. package/node_modules/@opentelemetry/core/build/src/version.js +1 -1
  576. package/node_modules/@opentelemetry/core/package.json +2 -2
  577. package/node_modules/@opentelemetry/resources/build/esm/version.d.ts +1 -1
  578. package/node_modules/@opentelemetry/resources/build/esm/version.js +1 -1
  579. package/node_modules/@opentelemetry/resources/build/esnext/version.d.ts +1 -1
  580. package/node_modules/@opentelemetry/resources/build/esnext/version.js +1 -1
  581. package/node_modules/@opentelemetry/resources/build/src/version.d.ts +1 -1
  582. package/node_modules/@opentelemetry/resources/build/src/version.js +1 -1
  583. package/node_modules/@opentelemetry/resources/package.json +3 -3
  584. package/node_modules/@opentelemetry/sdk-trace/build/esm/StackContextManager.d.ts +57 -0
  585. package/node_modules/@opentelemetry/sdk-trace/build/esm/StackContextManager.js +105 -0
  586. package/node_modules/@opentelemetry/sdk-trace/build/esm/index.d.ts +1 -0
  587. package/node_modules/@opentelemetry/sdk-trace/build/esm/index.js +1 -0
  588. package/node_modules/@opentelemetry/sdk-trace/build/esm/version.d.ts +1 -1
  589. package/node_modules/@opentelemetry/sdk-trace/build/esm/version.js +1 -1
  590. package/node_modules/@opentelemetry/sdk-trace/build/esnext/StackContextManager.d.ts +57 -0
  591. package/node_modules/@opentelemetry/sdk-trace/build/esnext/StackContextManager.js +105 -0
  592. package/node_modules/@opentelemetry/sdk-trace/build/esnext/index.d.ts +1 -0
  593. package/node_modules/@opentelemetry/sdk-trace/build/esnext/index.js +1 -0
  594. package/node_modules/@opentelemetry/sdk-trace/build/esnext/version.d.ts +1 -1
  595. package/node_modules/@opentelemetry/sdk-trace/build/esnext/version.js +1 -1
  596. package/node_modules/@opentelemetry/sdk-trace/build/src/StackContextManager.d.ts +57 -0
  597. package/node_modules/@opentelemetry/sdk-trace/build/src/StackContextManager.js +109 -0
  598. package/node_modules/@opentelemetry/sdk-trace/build/src/index.d.ts +1 -0
  599. package/node_modules/@opentelemetry/sdk-trace/build/src/index.js +3 -1
  600. package/node_modules/@opentelemetry/sdk-trace/build/src/version.d.ts +1 -1
  601. package/node_modules/@opentelemetry/sdk-trace/build/src/version.js +1 -1
  602. package/node_modules/@opentelemetry/sdk-trace/package.json +5 -5
  603. package/node_modules/@opentelemetry/sdk-trace-base/build/esm/version.d.ts +1 -1
  604. package/node_modules/@opentelemetry/sdk-trace-base/build/esm/version.js +1 -1
  605. package/node_modules/@opentelemetry/sdk-trace-base/build/esnext/version.d.ts +1 -1
  606. package/node_modules/@opentelemetry/sdk-trace-base/build/esnext/version.js +1 -1
  607. package/node_modules/@opentelemetry/sdk-trace-base/build/src/version.d.ts +1 -1
  608. package/node_modules/@opentelemetry/sdk-trace-base/build/src/version.js +1 -1
  609. package/node_modules/@opentelemetry/sdk-trace-base/package.json +7 -7
  610. package/node_modules/@sentry/core/build/cjs/browser.js +3 -0
  611. package/node_modules/@sentry/core/build/cjs/fetch.js +10 -9
  612. package/node_modules/@sentry/core/build/cjs/index.js +3 -0
  613. package/node_modules/@sentry/core/build/cjs/integrations/http/add-outgoing-request-breadcrumb.js +2 -1
  614. package/node_modules/@sentry/core/build/cjs/integrations/http/get-outgoing-span-data.js +3 -2
  615. package/node_modules/@sentry/core/build/cjs/integrations/http/server-subscription.js +7 -3
  616. package/node_modules/@sentry/core/build/cjs/integrations/requestdata.js +23 -9
  617. package/node_modules/@sentry/core/build/cjs/server.js +3 -0
  618. package/node_modules/@sentry/core/build/cjs/utils/data-collection/filterCollectedUrl.js +24 -0
  619. package/node_modules/@sentry/core/build/cjs/utils/data-collection/filterKeyValueData.js +17 -23
  620. package/node_modules/@sentry/core/build/cjs/utils/data-collection/filterQueryParams.js +8 -15
  621. package/node_modules/@sentry/core/build/cjs/utils/data-collection/filterUrlQuery.js +20 -0
  622. package/node_modules/@sentry/core/build/cjs/utils/url.js +4 -3
  623. package/node_modules/@sentry/core/build/cjs/utils/version.js +1 -1
  624. package/node_modules/@sentry/core/build/esm/browser.js +1 -0
  625. package/node_modules/@sentry/core/build/esm/fetch.js +10 -9
  626. package/node_modules/@sentry/core/build/esm/index.js +1 -0
  627. package/node_modules/@sentry/core/build/esm/integrations/http/add-outgoing-request-breadcrumb.js +2 -1
  628. package/node_modules/@sentry/core/build/esm/integrations/http/get-outgoing-span-data.js +3 -2
  629. package/node_modules/@sentry/core/build/esm/integrations/http/server-subscription.js +7 -3
  630. package/node_modules/@sentry/core/build/esm/integrations/requestdata.js +23 -9
  631. package/node_modules/@sentry/core/build/esm/package.json +1 -1
  632. package/node_modules/@sentry/core/build/esm/server.js +1 -0
  633. package/node_modules/@sentry/core/build/esm/utils/data-collection/filterCollectedUrl.js +21 -0
  634. package/node_modules/@sentry/core/build/esm/utils/data-collection/filterKeyValueData.js +18 -25
  635. package/node_modules/@sentry/core/build/esm/utils/data-collection/filterQueryParams.js +9 -16
  636. package/node_modules/@sentry/core/build/esm/utils/data-collection/filterUrlQuery.js +18 -0
  637. package/node_modules/@sentry/core/build/esm/utils/url.js +4 -3
  638. package/node_modules/@sentry/core/build/esm/utils/version.js +1 -1
  639. package/node_modules/@sentry/core/build/types/shared-exports.d.ts +1 -0
  640. package/node_modules/@sentry/core/build/types/utils/data-collection/filterCollectedUrl.d.ts +21 -0
  641. package/node_modules/@sentry/core/build/types/utils/data-collection/filterKeyValueData.d.ts +1 -0
  642. package/node_modules/@sentry/core/build/types/utils/data-collection/filterQueryParams.d.ts +2 -3
  643. package/node_modules/@sentry/core/build/types/utils/data-collection/filterUrlQuery.d.ts +13 -0
  644. package/node_modules/@sentry/core/build/types/utils/url.d.ts +4 -1
  645. package/node_modules/@sentry/core/build/types-ts3.8/shared-exports.d.ts +1 -0
  646. package/node_modules/@sentry/core/build/types-ts3.8/utils/data-collection/filterCollectedUrl.d.ts +21 -0
  647. package/node_modules/@sentry/core/build/types-ts3.8/utils/data-collection/filterKeyValueData.d.ts +1 -0
  648. package/node_modules/@sentry/core/build/types-ts3.8/utils/data-collection/filterQueryParams.d.ts +2 -3
  649. package/node_modules/@sentry/core/build/types-ts3.8/utils/data-collection/filterUrlQuery.d.ts +13 -0
  650. package/node_modules/@sentry/core/build/types-ts3.8/utils/url.d.ts +4 -1
  651. package/node_modules/@sentry/core/package.json +3 -2
  652. package/node_modules/@sentry/node/build/cjs/integrations/tracing/vercelai/instrumentation.js +3 -0
  653. package/node_modules/@sentry/node/build/esm/integrations/tracing/vercelai/instrumentation.js +3 -0
  654. package/node_modules/@sentry/node/build/esm/package.json +1 -1
  655. package/node_modules/@sentry/node/package.json +7 -6
  656. package/node_modules/@sentry/node-core/build/cjs/integrations/anr/index.js +1 -1
  657. package/node_modules/@sentry/node-core/build/cjs/integrations/http/httpServerSpansIntegration.js +6 -3
  658. package/node_modules/@sentry/node-core/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
  659. package/node_modules/@sentry/node-core/build/cjs/integrations/node-fetch/undici-instrumentation.js +2 -2
  660. package/node_modules/@sentry/node-core/build/cjs/light/client.js +7 -0
  661. package/node_modules/@sentry/node-core/build/cjs/sdk/client.js +7 -0
  662. package/node_modules/@sentry/node-core/build/cjs/utils/outgoingFetchRequest.js +1 -1
  663. package/node_modules/@sentry/node-core/build/esm/integrations/anr/index.js +1 -1
  664. package/node_modules/@sentry/node-core/build/esm/integrations/anr/worker-script.js +2 -2
  665. package/node_modules/@sentry/node-core/build/esm/integrations/http/httpServerSpansIntegration.js +7 -4
  666. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/local-variables-async.js +1 -1
  667. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/worker-script.js +1 -1
  668. package/node_modules/@sentry/node-core/build/esm/integrations/node-fetch/undici-instrumentation.js +3 -3
  669. package/node_modules/@sentry/node-core/build/esm/light/client.js +8 -1
  670. package/node_modules/@sentry/node-core/build/esm/package.json +1 -1
  671. package/node_modules/@sentry/node-core/build/esm/sdk/client.js +8 -1
  672. package/node_modules/@sentry/node-core/build/esm/utils/outgoingFetchRequest.js +2 -2
  673. package/node_modules/@sentry/node-core/build/types/light/client.d.ts +1 -0
  674. package/node_modules/@sentry/node-core/build/types/sdk/client.d.ts +1 -0
  675. package/node_modules/@sentry/node-core/build/types-ts3.8/light/client.d.ts +1 -0
  676. package/node_modules/@sentry/node-core/build/types-ts3.8/sdk/client.d.ts +1 -0
  677. package/node_modules/@sentry/node-core/package.json +5 -4
  678. package/node_modules/@sentry/opentelemetry/build/cjs/{asyncContextStrategy-BJ5buq_A.js → asyncContextStrategy-BR-l9zjD.js} +8 -6
  679. package/node_modules/@sentry/opentelemetry/build/cjs/index.browser.js +1 -1
  680. package/node_modules/@sentry/opentelemetry/build/cjs/index.js +1 -1
  681. package/node_modules/@sentry/opentelemetry/build/esm/{asyncContextStrategy-Bx5F5tCX.js → asyncContextStrategy-BQfM_LMv.js} +9 -7
  682. package/node_modules/@sentry/opentelemetry/build/esm/index.browser.js +1 -1
  683. package/node_modules/@sentry/opentelemetry/build/esm/index.js +2 -2
  684. package/node_modules/@sentry/opentelemetry/build/esm/package.json +1 -1
  685. package/node_modules/@sentry/opentelemetry/package.json +4 -3
  686. package/node_modules/@sentry/server-utils/build/cjs/tracing-channel.js +1 -0
  687. package/node_modules/@sentry/server-utils/build/esm/package.json +1 -1
  688. package/node_modules/@sentry/server-utils/build/esm/tracing-channel.js +1 -0
  689. package/node_modules/@sentry/server-utils/build/types/tracing-channel.d.ts +3 -1
  690. package/node_modules/@sentry/server-utils/build/types-ts3.8/tracing-channel.d.ts +3 -1
  691. package/node_modules/@sentry/server-utils/package.json +4 -3
  692. package/node_modules/cjs-module-lexer/README.md +8 -3
  693. package/node_modules/cjs-module-lexer/dist/lexer.js +1 -1
  694. package/node_modules/cjs-module-lexer/dist/lexer.mjs +2 -2
  695. package/node_modules/cjs-module-lexer/lexer.js +48 -9
  696. package/node_modules/cjs-module-lexer/package.json +3 -2
  697. package/node_modules/es-module-lexer/dist/lexer.asm.js +2 -2
  698. package/node_modules/es-module-lexer/dist/lexer.cjs +1 -1
  699. package/node_modules/es-module-lexer/dist/lexer.js +2 -2
  700. package/node_modules/es-module-lexer/dist/lexer.minimal.asm.js +2 -2
  701. package/node_modules/es-module-lexer/dist/lexer.minimal.cjs +1 -1
  702. package/node_modules/es-module-lexer/dist/lexer.minimal.js +2 -2
  703. package/node_modules/es-module-lexer/package.json +1 -1
  704. package/node_modules/import-in-the-middle/CHANGELOG.md +7 -0
  705. package/node_modules/import-in-the-middle/lib/get-esm-exports.mjs +7 -0
  706. package/node_modules/import-in-the-middle/package.json +1 -1
  707. package/package.json +2 -2
  708. package/packages/pm-beads/extensions/beads/runtime.ts +2 -2
  709. package/packages/pm-beads/package.json +1 -1
  710. package/packages/pm-calendar/package.json +1 -1
  711. package/packages/pm-command-kit/package.json +1 -1
  712. package/packages/pm-digital-twin/package.json +1 -1
  713. package/packages/pm-governance-audit/package.json +1 -1
  714. package/packages/pm-guide-shell/package.json +1 -1
  715. package/packages/pm-kanban/package.json +1 -1
  716. package/packages/pm-lifecycle-hooks/package.json +1 -1
  717. package/packages/pm-linked-test-adapters/package.json +1 -1
  718. package/packages/pm-search-advanced/package.json +1 -1
  719. package/packages/pm-templates/package.json +1 -1
  720. package/packages/pm-todos/package.json +1 -1
  721. package/packages/pm-vcs/package.json +1 -1
  722. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  723. package/plugins/pm-claude/package.json +1 -1
  724. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  725. package/plugins/pm-codex/package.json +1 -1
  726. package/plugins/pm-codex/plugin.json +1 -1
  727. package/runtime-dependencies.json +1 -1
  728. package/scripts/finalize-build.mjs +37 -0
  729. package/dist/cli-bundle/chunks/chunk-BXSXT5Z6.js +0 -2
  730. package/dist/cli-bundle/chunks/chunk-KNW3RSLS.js +0 -30
  731. package/dist/cli-bundle/chunks/chunk-MEWBSWE3.js +0 -2
  732. package/dist/cli-bundle/chunks/chunk-RBPOO46D.js +0 -20
  733. package/dist/cli-bundle/chunks/chunk-YMLF6QT7.js +0 -234
  734. package/dist/cli-bundle/chunks/register-operations-PDOBQZUJ.js +0 -2
  735. package/dist/cli-bundle/focused-chunks/chunk-2CJWTLQG.js +0 -2
  736. package/dist/cli-bundle/focused-chunks/chunk-B3YW6H2I.js +0 -26
  737. package/dist/cli-bundle/focused-chunks/chunk-GVGFUD52.js +0 -8
  738. package/dist/cli-bundle/focused-chunks/chunk-MJQ253F3.js +0 -2
  739. package/dist/cli-bundle/focused-chunks/chunk-PBCYGO7X.js +0 -3
  740. package/dist/cli-bundle/focused-chunks/chunk-WOEZJUA2.js +0 -2
@@ -1,37 +1,37 @@
1
- import{n as vp,o as Ko,p as Ap,q as Tp,r as As,s as Bo,t as Cp,u as Ts,v as Vo,y as tu,z as nu}from"./focused-chunks/chunk-DMSADMEU.js";import{a as au,f as su,h as en,m as cu,o as mr,r as ei,s as lu,t as du,x as mu}from"./focused-chunks/chunk-MJQ253F3.js";import{$ as Gn,$a as a_,A as Sr,Ab as w_,B as wf,Bb as v_,C as Ci,Cb as b_,D as vf,Db as k_,E as bf,Eb as S_,Fb as Tr,Ga as Xf,Gb as mc,Hb as pc,Ia as Zf,Ib as Mi,J as kf,Ja as Ni,Jb as uc,K as Sf,Ka as Rk,Kb as E_,L as Ef,La as e_,Lb as fc,M as Af,Ma as t_,Mb as Di,N as Tf,Na as dc,Nb as Kn,O as Cf,Ob as _c,P as If,Pb as hc,Q as Rf,Qb as A_,R as Of,Rb as T_,S as xf,Sb as C_,T as Pf,Tb as zn,U as Nf,Ub as gc,V as Lf,Vb as I_,W as $f,X as Ff,Y as Mf,Ya as r_,Yb as Ui,Z as Df,Za as o_,_ as Uf,_a as i_,aa as Gf,ab as s_,ba as jf,bb as c_,ca as qf,cb as l_,da as Dt,db as nn,dc as R_,ea as v,eb as d_,ec as O_,fa as Kf,fb as m_,fc as x_,g as df,ga as zf,gb as Li,h as mf,ha as Me,hb as p_,ia as Hf,ib as u_,ja as ac,jb as f_,jc as P_,ka as Bf,kb as __,kc as q_,la as sc,lb as h_,ma as Er,mb as $i,na as Ii,nb as Ut,oa as jn,ob as g_,pa as Vf,pb as Fi,qa as Ri,ra as ye,sa as cc,sb as Ar,ta as he,ua as Wf,va as Yf,wa as Oi,xa as Jf,y as yf,ya as xi,z as rc,zb as y_}from"./focused-chunks/chunk-KNJR2WUO.js";import{e as gp,g as yp,h as wp,k as bp,q as Ep}from"./focused-chunks/chunk-W5AE7GKZ.js";import{b as ru,c as Zo,e as ou,f as iu,g as mk}from"./focused-chunks/chunk-WAOXID5J.js";import{R as js,V as eu,a as cm,b as lm,c as dm,d as mm,f as pm}from"./focused-chunks/chunk-2CJWTLQG.js";import{a as _f,b as hf,c as Gi}from"./focused-chunks/chunk-GVGFUD52.js";import{K as n_,b as gf}from"./focused-chunks/chunk-52UJEHEV.js";import{A as M_,Aa as bc,B as D_,Fa as kc,Ha as U_,Wa as Rr,Ya as G_,Za as j_,a as pf,b as Ik,c as uf,d as Ti,g as oc,i as ic,k as lc,l as Cr,m as Ok,n as yc,o as wc,p as ji,q as xk,r as Pk,ta as vc,w as N_,x as L_,y as $_,ya as Ir,z as F_}from"./focused-chunks/chunk-EIOQNLBQ.js";import{$a as wr,A as fe,B as $n,C as _i,D as hi,G as gi,H as yi,I as Bu,Ia as Un,J as wi,Ja as rf,K as vi,Ka as tc,L as Fn,La as of,M as Zs,N as bi,O as Vu,Oa as nc,P as Wu,Pa as af,Q as gr,Xa as Si,_a as cf,a as ju,b as ai,c as si,cb as lf,d as ci,e as li,i as di,j as Pt,k as Nn,kb as ht,l as mi,m as Ln,mb as kr,n as pi,nb as tn,o as me,p as ui,pb as ff,q as Xs,qb as Pi,r as Ye,s as Qs,sa as nf,t as qu,u as Ie,vb as qn,w as ft,x as Ku,y as fi,z as Nt}from"./focused-chunks/chunk-JGFSSR3G.js";import{c as fp,f as _p,g as hp,i as qo,j as Rt,k as Ip,l as Rp,m as Op}from"./focused-chunks/chunk-PLTTMQAW.js";import{a as uu,b as fu,c as _u}from"./focused-chunks/chunk-AU6VJGTY.js";import{$ as Gm,A as yo,Aa as ap,B as vm,Ba as sp,C as bm,Ca as Io,D as km,Da as cp,E as wo,Ea as lp,F as Sm,Fa as dp,G as Em,Ga as Ro,H as Am,Ha as Oo,I as Tm,Ia as xo,J as vo,Ja as Po,K as bo,Ka as lr,L as Cm,La as mp,M as ko,Ma as No,Na as dr,O as Im,Oa as Lo,P as sr,Pa as $o,Q as Rm,Qa as Fo,R as Om,Ra as Mo,S as xm,Sa as pp,T as Pm,Ta as Ct,U as Nm,Ua as Do,V as Lm,Va as Uo,W as $m,Wa as Go,X as Fm,Xa as jo,Y as Mm,Z as Dm,_ as Um,_a as up,aa as jm,ab as It,ba as qm,bb as N,ca as Km,d as ks,da as cr,e as um,ea as zm,fa as Hm,ga as So,h as fo,ha as Eo,i as Ss,ia as Bm,j as Xt,ja as Vm,ka as Wm,l as fm,la as Ym,ma as Jm,na as Xm,oa as Qm,pa as Zm,q as Es,ra as ep,s as _o,sa as tp,t as ho,ta as np,u as go,ua as rp,v as _m,va as op,w as hm,wa as ip,x as gm,xa as Ao,y as ym,ya as To,z as wm,za as Co}from"./focused-chunks/chunk-WOEZJUA2.js";import{$ as Au,$a as Hu,A as Tk,Aa as _r,Ab as I,B as Ck,Bb as z,C as Pn,Cb as ae,D as C,Db as Qu,Fb as _e,Gb as Zu,H as ut,Ha as $u,Hb as ki,Ib as _t,Ja as Ws,Jb as ef,Kb as se,L as yu,Lb as tf,M as oi,Ma as Fu,N as wu,Na as ii,O as vu,Oa as We,P as bu,Pb as sf,Q as ku,Qa as Mu,R as Su,Ra as Du,T as ee,Ta as Uu,U as qs,Ua as Ys,V as re,Va as Js,Vb as vr,Wa as Gu,Wb as br,X as Ks,Xa as A,Xb as Ei,Y as Eu,Ya as Fe,Yb as Mt,Z as Ve,Za as Ce,_ as rt,_a as zu,a as ti,aa as Tu,ab as Lt,b as pk,bc as Ai,c as uk,ca as Cu,cb as ze,d as fk,da as Iu,db as hr,e as _k,ea as zs,eb as Mn,fb as Yu,gb as Dn,ha as Hs,hb as ec,ib as Ju,ja as Ru,k as ni,ka as Ou,l as hu,la as xu,m as gu,ma as Pu,n as xn,na as Nu,o as pr,ob as yr,p as hk,q as gk,r as yk,ra as $e,s as wk,sa as xt,sc as Qf,t as vk,u as bk,ua as Bs,v as kk,va as ur,vb as $t,w as Sk,wa as fr,x as Ek,xa as Vs,xb as Ft,y as ri,ya as ot,z as Ak,za as Lu,zb as Xu}from"./focused-chunks/chunk-SIEGIPNT.js";import{b as Tt,c as co,d as lo,g as mt,i as zo,j as pt,k as Ot,l as kp,n as $,o as Ho,p as nt,r as Sp}from"./focused-chunks/chunk-PBCYGO7X.js";import{e as pu}from"./focused-chunks/chunk-YLVHHWHN.js";import{$ as d,$a as E,$c as Zt,Aa as En,Ae as Xp,B as jd,Bb as ir,C as qd,Cb as bs,D as Kd,Db as ar,Dc as qp,E as zd,Ee as Qp,F as Hd,Fc as Os,Fd as Qb,G as Bd,Gc as xs,Gd as Zb,H as ms,Hc as Ps,I as ps,Ia as An,Ib as Se,Ic as Ns,Id as ek,Ie as sk,J as us,Jc as Ls,Je as ck,K as fs,Ka as Qd,Kb as B,Kc as $s,Kd as tk,Ke as lk,L as _s,Lc as Fs,Ld as nk,Le as dk,M as hs,Ma as ys,Mb as Jt,Mc as O,Md as Ds,Me as Qo,Na as ws,Nc as In,Nd as Us,Ne as Zp,Oc as Qt,Od as Gs,P as so,Pc as Y,Pd as Bp,Qa as vs,Qc as Wo,Ra as nr,Rc as Rn,Rd as Vp,Sa as Ae,Sb as Cn,Sd as rk,U as gs,Uc as Yo,Ud as ok,Va as x,Vd as ik,W as Vd,Wa as ke,Wc as Ee,Wd as ak,Xa as po,Xc as Jo,Ya as Tn,Yd as k,Z as At,Za as rr,_a as Zd,_c as Kp,aa as l,ab as em,ae as Xo,bb as lt,bc as xp,cb as ne,cc as Pp,ce as ie,db as dt,dc as Np,ec as Lp,fb as tt,fc as $p,fe as Te,gb as uo,gc as Fp,hc as Cs,ia as Wd,ic as Mp,ka as Yd,kb as tm,kc as Dp,lb as nm,lc as Up,le as Wp,ma as mo,mb as rm,nb as om,nd as zp,o as oo,oa as Jd,ob as im,oc as Is,p as Gd,pa as Xd,pb as am,pc as Gp,q as io,qb as sm,qc as Rs,r as ds,rd as Hp,sa as q,sb as or,se as Yp,ta as Wt,tb as Yt,te as Jp,ua as Be,ub as Le,v as Vt,va as J,w as ct,wd as Ms,we as On,x as kn,xc as jp,y as Sn,ya as te,z as ao}from"./focused-chunks/chunk-B3YW6H2I.js";import{AsyncLocalStorage as SM}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="73dbe40e-f7a2-5aca-85aa-a5775e5e981a")}catch{}})();var Nk=js("list").properties.outputSession,Lk={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...Nk},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},K_={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},z_={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},ce={type:"string",description:"pm item id, for example pm-abc1."},$k=`Operation name (one of): ${Rs.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,Fk={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},Mk={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function D(e,t=[]){return{...z_,properties:{...z_.properties,...e},required:t}}var Dk=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:D({action:{type:"string",enum:[...Rs],description:$k},id:ce,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...Lk},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:D({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:D({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:D({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:D({query:{type:"string"},options:{type:"object"},...Mk},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:D({options:{type:"object"},...Fk})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:D({id:ce,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:D({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:D({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:ce,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:ce,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:D({id:ce,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:D({id:ce,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:ce,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:D({id:ce,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:D({id:ce,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:ce,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:D({id:ce,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:D({id:ce,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:D({id:ce,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:D({id:ce,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:D({id:ce,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:D({id:ce,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:D({subcommand:{type:"string",enum:[...Mp]},id:ce,target:ce,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:D({id:ce,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:D({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:D({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:D({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:D({...K_,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...Cn],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...ds]},description:`Lifecycle roles for add-status: ${ds.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:K_}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:D({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:D({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:D({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],Uk={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},Gk=Dk.map(e=>{let t=Uk[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:js(t,{properties:n,required:r})}});function H_(){return Gk.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48a78171-1f14-5e93-82a2-27108ee87f4f")}catch{}})();var B_=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),jk=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],nh=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Ki=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),rn=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),rh=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),oh=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),ih=new Map([...oh.entries()].flatMap(([e,t])=>gt(t).map(n=>[n,e]))),ah=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Ac=new Map(ah.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),qk=10,Kk=20,V_=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),sh=[["init",Im],["install",Om],["uninstall",xm],["explore",Pm],["manage",Dm],["describe",Nm],["reload",Um],["doctor",Gm],["catalog",jm],["adopt",qm],["adopt-all",Lm],["activate",$m],["deactivate",Fm],["migrate",Mm]],zk=[...sh.map(([e,t])=>e==="init"?[e,Rm]:[e,t]),["upgrade",cr]],Hk=[...sh.map(([e,t])=>[`extension ${e}`,t]),...zk.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",bo],["config",Cm],["extension",ko],["package",sr],["packages",sr],["install",Km],["create",Io],["item mutate",cp],["item complete",lp],["item reopen",dp],["copy",Ro],["focus",Oo],["update",xo],["update-many",Po],["upgrade",cr],["calendar",lr],["cal",lr],["context",dr],["ctx",dr],["get",Lo],["search",Uo],["eval",pp],["events",No],["workspace",Ct],["workspace position",[]],["workspace snapshot",Ct],["workspace snapshot create",Ct],["workspace snapshot list",Ct],["workspace snapshot inspect",Ct],["workspace snapshot restore",Ct],["workspace snapshot delete",Ct],["next",Do],["aggregate",go],["deps",Fo],["graph",Mo],["guide",$o],["reindex",zm],["history",yo],["history-compact",Sm],["history-attest",Em],["history-redact",bm],["history-repair",km],["history-author-acknowledge",wo],["merge",vm],["schema",Am],["profile",Tm],["plan",vo],["restore",Vm],["delete",Wm],["close",Hm],["close-many",So],["append",Eo],["claim",Bm],["release",Ym],["start-task",Jm],["pause-task",Xm],["close-task",Qm],["comments",_m],["notes",hm],["learnings",gm],["files",ym],["docs",wm],["test",tp],["test-runs-worker",[]],["test-all",np],["telemetry",rp],["test-runs",op],["gc",ip],["stats",Ao],["ops",[]],["duplicates",To],["validate",ap],["health",Co],["assurance",sp],...up,["contracts",Go],["completion",jo],["activity",mp],...[...nh].map(e=>[e,ho])],Or=new Map(Hk);for(let{alias:e,canonical:t}of Se){let n=Or.get(e);n!==void 0&&Or.set(t,n)}function Bk(e){return ih.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function W_(e){let t=Se.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Cs.includes(e)?we(e):e.startsWith("extension-")?we(`extension ${e.slice(10)}`):e.startsWith("package-")?we(`package ${e.slice(8)}`):e.startsWith("item-")?we(`item ${e.slice(5)}`):e.startsWith("test-runs-")?we(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?we(`templates ${e.slice(10)}`):Ki.has(e)?oh.get(e)??we(e):null}function Vk(e,t){let n=B(t);return n!==t||Se.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:gt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function gt(e){return e.split("|").map(t=>we(t)).filter(t=>t.length>0)}function Wk(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let i of gt(o.command_path)){let a=i.split(" ").filter(s=>s.length>0);if(a.length!==0)for(let s=a.length;s>0;s-=1){let c=a.slice(0,s).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function qi(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function xr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function Yk(e,t){if(!t)return{...e};let n=xr(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:n}}function Sc(e,t){let n=xr(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:n}}function we(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function ch(e){return e.replace(/\s+/g,"-")}function it(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Y_(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=it(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function Ec(e,t,n){n&&(e[t]=!0)}function J_(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function Jk(e){let t=J_(e.long,"long"),n=J_(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),Ec(o,"required",e.required===!0),Ec(o,"repeatable",e.repeatable===!0),Ec(o,"list",e.list===!0);let i=it(e.description);i&&(o.description=i);let a=it(e.value_name);a&&(o.value_name=a);let s=[it(e.value_type),it(e.type),a?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return s&&(o.value_type=s),o}function lh(e){let t=new Map;for(let r of e){let o=we(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},a=`${r.layer}:${r.name}`;i.sourceDedupe.has(a)||(i.sourceDedupe.add(a),i.sources.push({layer:r.layer,name:r.name}));for(let s of r.flags){let c=Jk(s);if(!c)continue;let m=`${c.flag}|${c.short??""}`;i.dedupe.has(m)||(i.dedupe.add(m),i.flags.push(c))}t.set(o,i)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((i,a)=>{let s=i.layer.localeCompare(a.layer);return s!==0?s:(i.name??"").localeCompare(a.name??"")})});return n}function Xk(e){let t=lh(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let a=we(i.command);if(a.length===0)continue;let s=it(i.action)??ch(a),c=Array.isArray(i.arguments)?i.arguments.map(m=>{let p=it(m.name);return p?{name:p,required:m.required===!0,variadic:m.variadic===!0,description:it(m.description)}:null}).filter(m=>m!==null):[];n.set(a,{...i.tier===void 0?{}:{tier:i.tier},command:a,action:s,source:{layer:i.layer,name:i.name},description:it(i.description),intent:it(i.intent),arguments:c,flags:t.get(a)?.flags??[],examples:Y_(i.examples),failure_hints:Y_(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(we(i));for(let i of n.keys())r.add(i);for(let i of t.keys())r.add(i);let o=[];for(let i of[...r].sort((a,s)=>a.localeCompare(s))){let a=n.get(i);o.push(Qk(i,a,t.get(i)?.flags??[]))}return o}function Qk(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:ch(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function Zk(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let n=t.replace(/-([a-z0-9])/g,(r,o)=>o.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return n.length>0?n:null}function eS(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function tS(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function nS(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=eS(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=Zk(o);!i||n[i]!==void 0||(n[i]=tS(o,e.action),o.required===!0&&r.push(i))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function rS(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function oS(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((i,a)=>i.localeCompare(a)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(i=>`${i.flag}|${i.short??""}`));for(let i of n.flags){let a=`${i.flag}|${i.short??""}`;if(!o.has(a))o.add(a),r.flags.push(i);else{let s=r.flags.find(c=>`${c.flag}|${c.short??""}`===a);s&&rS(s,i)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function iS(e,t=A){let n={mode:At.extensions.policy.mode,trust_mode:At.extensions.policy.trust_mode,default_sandbox_profile:At.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await q(ne(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await ir({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),a=await ar({...i,loaded:i.loaded});return{handlers:new Set(a.commands.handlers.map(s=>we(s.command))),disabledReason:null,commandDefinitions:a.registrations.commands,flagRegistrations:a.registrations.flags,registrations:a.registrations,policyState:{mode:i.policy.mode,trust_mode:i.policy.trust_mode,default_sandbox_profile:i.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function aS(e,t={}){let n=new Map;for(let r of Is){let o=Ki.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=W_(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of Ki)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:W_(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:Se.find(o=>o.alias===r.command)?.canonical??we(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function sS(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null&&(!rn.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?gt(e.command_path):[],r=n.some(a=>t.handlers.has(a)||t.handlers.has(B(a))),o=n.map(a=>rh.get(B(a))).find(a=>typeof a=="string"),i=t.disabledReason===null&&r;return{action:e.action,invocable:i,available:i,requires_extension:!0,provider:"extension",disabled_reason:i?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function dh(e){return Or.get(e)??_o}function cS(e){return rn.has(B(e))?!1:Or.has(e)}function lS(e){return nh.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function X_(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function dS(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function mS(e){let t=new Map;for(let r of e.definitions){let o=X_(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(s=>dS(s)).find(s=>s!==null),a=r.cli_aliases.map(s=>X_(s)).filter(s=>s!==null&&s!==o);for(let s of r.commands){let c=t.get(s)??{flags:[],seen:new Set},m=i?{flag:o,short:i}:{flag:o},p=`${m.flag}|${m.short??""}`;c.seen.has(p)||(c.seen.add(p),c.flags.push(m));for(let u of a){let f=`${u}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:u}))}t.set(s,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,Es(o.flags));return n}function Q_(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let i=`${o.flag}|${o.short??""}`;r.has(i)||(r.add(i),n.push(o))}return Es(n)}function pS(e,t,n,r,o){let i=new Map(t);for(let{alias:a,canonical:s}of Se){let c=t.get(s)??t.get(a);c&&(i.set(a,c),i.set(s,c))}return e.map(a=>{let s=cS(a),c=s?dh(a):[],m=n.get(lS(a))??[],p=i.get(a),u=Q_(c,m),f=Q_(u,p?.flags??[]),_=c.length>0&&(p?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:a,flags:f,...r?{canonical_command:ph(a),visibility:mh(a,o),positionals:um(a)?.slots??[],flag_invocations:mr(a,f)}:{},provider:_,extension_sources:p?.sources}}).sort((a,s)=>a.command.localeCompare(s.command))}function uS(e,t=Jt){let n=new Set(e),r=new Map;for(let o of ah){let i=o.aliases.filter(a=>n.has(a));r.set(o.canonical,{canonical:o.canonical,aliases:i,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let i=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};i.aliases.includes(o.alias)||i.aliases.push(o.alias),i.contracts.push(o),r.set(o.canonical,i)}return[...r.values()].map(({contracts:o,...i})=>o.length===0?i:{...i,contracts:o}).sort((o,i)=>o.canonical.localeCompare(i.canonical))}function fS(){return{create_string_options:ru,create_repeatable_options:Zo,update_string_options:ou,update_repeatable_options:iu,list_string_options:cm,search_string_options:lm,calendar_string_options:dm,context_string_options:mm,activity_string_options:pm}}function Z_(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let s of e.required_create_fields)n.add(s);for(let s of e.required_create_repeatables)n.add(s)}let r=Tn(e,"create",n),o=[...new Set(r.required)].sort((s,c)=>s.localeCompare(c)),i=[...new Set(o.map(s=>Ae("create",s)))].sort((s,c)=>s.localeCompare(c)),a=[...new Set(e.options.filter(s=>s.required===!0).map(s=>s.key))].sort((s,c)=>s.localeCompare(c));return{required_option_keys:o,required_flags:i,required_type_options:a,policy_errors:[...new Set(r.errors)].sort((s,c)=>s.localeCompare(c))}}function _S(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){let o=e.by_type[r];t[r]=Z_(o,"strict"),n[r]=Z_(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function hS(e,t){let n=xr(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let a=i.properties;if(typeof a!="object"||a===null)return i;let s=a.action;return typeof s!="object"||s===null||s.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function gS(e){let t=qi(e.action)!==void 0||qi(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,i=e.flagsOnly===!0,a=e.availabilityOnly===!0,s=e.runtimeOnly===!0,c=e.full===!0,m=qi(e.action),p=qi(e.command),u=!r&&!c&&!o&&!i&&!a&&!m&&!p;return{selectedAction:m,selectedCommand:p,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:a,runtimeOnly:s,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||p!==void 0&&!c}}function yS(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",d.USAGE)}async function wS(e,t=A){try{return await t(e)}catch{return structuredClone(At)}}async function vS(e,t,n){let r=await wS(t),o=await iS(e),i=x(r,o.registrations??O()),a=nt(r.schema),s=Xk(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:$(r.schema),runtimeFieldRegistry:a,runtimeFieldFlagMap:mS(a),createRequiredOptionContracts:_S(i),extensionContracts:s,mergedExtensionContracts:oS(s.filter(c=>zi(n,c.command,s))),extensionFlagMap:lh(o.flagRegistrations)}}function eh(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Ki.has(e.selectedAction)||e.selectedCommand!==void 0&&rn.has(B(e.selectedCommand)))}function bS(e,t){let n=aS(t,{includePackageOwnedActions:eh(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Gp);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(i=>i.action===o.action)?.tier??ei(o.action))!=="internal"))}return eh(e)&&e.selectedCommand!==void 0&&rn.has(B(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:Bk(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function kS(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new l(`Unknown action: "${e.selectedAction}".`,d.USAGE)}function SS(e,t){return[...new Set([...Cs.filter(n=>!rn.has(B(n))),...[...Or.keys()].filter(n=>!rn.has(B(n))),...e.flatMap(n=>n.command_path?gt(n.command_path).filter(r=>n.provider==="extension"||!rn.has(B(r))||t.some(o=>o.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let o=Se.find(i=>i.alias===r||i.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>we(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function ES(e,t){let n=t.slice(0,qk),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,Kk),a=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),s=t[0];return new l(`Command "${e}" is a command namespace. Choose a concrete child command: ${o}.`,d.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:a,nextSteps:[`Retry with a child command, for example: ${a[0]}`],recovery:{suggested_retry:`pm contracts --command "${s}" --flags-only --json`,fallback_candidates:i.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function AS(e,t){return new l(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,d.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function TS(e){return new l(`Unknown command: "${e}".`,d.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function CS(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(o=>o.startsWith(`${e.selectedCommand} `));if(n.length>0)throw ES(e.selectedCommand,n);let r=rh.get(B(e.selectedCommand));throw r?AS(e.selectedCommand,r):TS(e.selectedCommand)}function IS(e,t){let n=bS(e,t.mergedExtensionContracts);kS(e,n);let r=SS(n,t.mergedExtensionContracts);CS(e,r);let o=e.selectedCommand?ih.get(B(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(m=>o?m.action===o:Vk(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.some(m=>m.action===e.selectedAction))throw new l(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,d.USAGE);let a=e.selectedAction?i.filter(m=>m.action===e.selectedAction):i,s=[...new Map(a.map(m=>sS(m,t.runtimeProbe)).map(m=>[o?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?s.filter(m=>m.invocable):s;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:i,scopedActionDescriptors:a,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function RS(e){return new Set(xr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function OS(e){let t=eu,n=xr(t),r=RS(t),o=e.filter(i=>!r.has(i.action)).map(i=>nS(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function th(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?Yk(n,e.selectedAction):e.selectedCommand?Sc(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):Sc(n,r);return e.runtimeOnly&&!e.selectedAction?Sc(o,new Set(t.actions)):o}function xS(e,t,n){let r=OS(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?hS(th(e,n,r),t.createRequiredOptionContracts):th(e,n,r);return{mergedSchema:r,filteredSchema:o}}function PS(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?Wk(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function mh(e,t){return t.find(n=>B(n.command)===B(e))?.tier??ei(e)}function zi(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||mh(t,n)!=="internal"}function NS(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(Jt.filter(o=>o.hidden&&(o.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(o=>o.alias));if(e.summary&&!e.fullOutput)for(let o of Ac.keys())r.add(o);return t.filter(o=>!r.has(o)&&zi(e,o,n))}function ph(e){let t=Se.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Ac.get(n)??n}var LS=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),$S=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function FS(e,t){let n=V_.get(B(e))??(e.includes(" ")?void 0:V_.get(ph(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>gt(m.command).some(p=>B(p)===B(e)));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let o=e.split(" "),i=o.at(-1),a=o.slice(0,-1).join(" "),s=LS.get(i),c=$S.get(e)??a;return{intent:s===void 0||a.length===0?`Run ${e}.`:`${s} ${c}.`,intent_source:"generated"}}function MS(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(we))].filter(i=>i.length>0).sort((i,a)=>i.localeCompare(a)).map(i=>{let a=Ms(i,{generateFallback:!0}),s=i.split(" ")[0],c=Ac.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),m=new Set([...dh(i).map(f=>f.flag),...t.filter(f=>gt(f.command).some(_=>B(_)===B(i))).flatMap(f=>f.flags.map(_=>_.flag))]),p=(B_.get(B(i))??B_.get(c)??jk).filter(f=>m.has(f)),u=FS(i,t);return{command:i,intent:u.intent,...o||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...p.length>0?{flags:p}:{},default_max_estimated_tokens:a.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...a.default_max_estimated_tokens_by_format}}:{}}})}function DS(e){return e.map(t=>({budget:Ms(t,{generateFallback:!0}),envelope:mu(t)}))}function US(e){let t=new Map;for(let n of e){let r=su(n),o=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,i=o.join(","),a=t.get(i)??{commands:[],exit_codes:o};a.commands.push(n),t.set(i,a)}return[...t.values()]}function GS(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>gt(r.command).some(o=>B(o)===B(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>gt(o.command).some(i=>r.has(i)))}return t.extensionContracts.filter(r=>zi(e,r.command,t.extensionContracts))}function jS(e,t,n,r){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function qS(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=pu);let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,i])=>[o,[...new Set(i.map(a=>`--${a.cli_flag}`))].sort((a,s)=>a.localeCompare(s))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...xp],services:[...Pp],policy_modes:[...Np],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Fp],trust_modes:[...Lp],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...$p],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...jd],create_modes:[...qd],close_validation_modes:[...Kd],workflow_enforcement_modes:[...zd]},e.relationship_kind_contracts=[...Wd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,i)=>o.kind.localeCompare(i.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function KS(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function zS(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=pS(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(_u).filter(([a])=>i.has(a)).map(([a,s])=>({command:a,default:s,brief_fields:[...fu],compact_fields:[...uu]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:a})=>({canonical:i,aliases:a})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function HS(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=fS();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function BS(e,t,n,r){e.command_summaries=MS(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...zp],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(we))].filter(o=>Us(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...Bp(o).keys()]}))}:{}},e.grammar_contracts={nouns:Xt.nouns,shared_verbs:Xt.shared_verbs,scope_before_verb:Xt.scope_before_verb,visible_top_level_ceiling:Xt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Xt.ceiling_raise_requires_pm_item,positional_shape_budget:Xt.positional_shape_budget,positional_shape_count:new Set(Ss.map(({slots:o})=>fm(o))).size,positional_action_count:ks.length,positional_action_parents:[...new Set(ks.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:Ss}:{}}}async function Tc(e,t){let n=gS(e);yS(n);let r=E(process.cwd(),t.path),o=await vS(t,r,n),i=IS(n,o),a=xS(n,o,i),s=PS(n,i),c=NS(n,s,o.extensionContracts),m=jS(n,a,i,c),p=GS(n,o,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&BS(m,c,p,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return m;let f=uS(i.commandCatalog.filter(_=>zi(n,_,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||qS(m,o,n),KS(m,n,a,p),zS(m,n,o,c,f),HS(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...mf],gate_triggers:[...df]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=fo.map(_=>({..._,reason:_.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=H_(),m.context_intents=Yp(),m.read_output_dimensions=Ds,m.error_codes=cu,m.command_output_contracts=DS(c),m.diagnostic_output_contracts=Hp,m.command_exit_contracts={vocabulary:au,command_sets:US(c)}),m}import{readFile as VS}from"node:fs/promises";import WS from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="20a3a324-d176-5918-8167-5e548be4abc9")}catch{}})();var Cc="context-intents.json";function Hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function YS(e,t,n){if(!Hi(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function uh(e,t){let n=Array.isArray(e)?e:Hi(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,o)=>YS(r,t,o))}async function JS(e){let t=WS.join(e,Cc),n;try{n=await VS(t,"utf8")}catch(o){if(Wt(o))return[];throw await Xu(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Cc}: ${i}`,{cause:o})}return uh(r,Cc)}function XS(e){if(!Hi(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Hi(n)?n.contextIntents??n.context_intents:void 0}function QS(e){return e.flatMap(t=>{let n=XS(t.module);return n===void 0?[]:uh(n,`package ${t.name}`)})}async function ZS(e){let t=await JS(e.pmRoot),n=QS(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Ic(e,t){let n=await ZS(e);return await Jp(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a4abc17-0fcb-573f-8f89-6e505e112261")}catch{}})();async function fh(e,t,n=Wp){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=t,o=Array.isArray(r.warnings)?r.warnings.filter(i=>typeof i=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as eE}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="93e1b043-89b2-546e-b238-1b9f4a1df742")}catch{}})();function Rc(e){let t=Yd();for(let n of e)t.register(n);return t}function tE(e,t,n=[]){if(n.length===0)return e;let r=JSON.parse(e),o=JSON.parse(Js(t));for(let i of n){let a=i.split("."),s=o;for(let p of a){let u=ys(s);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(p)||["constructor","prototype","__proto__"].includes(p)||u===null||!Object.hasOwn(u,p))throw new l(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,d.USAGE);s=u[p]}if(ys(s)===null)throw new l(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,d.USAGE);let c=r,m=o;for(let p of a.slice(0,-1)){let u=c[p];m=m[p],u===void 0&&Object.defineProperty(c,p,{value:structuredClone(m),enumerable:!0,writable:!0,configurable:!0}),c=c[p]}Object.defineProperty(c,a.at(-1),{value:s,enumerable:!0,writable:!0,configurable:!0})}return Le(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
2
- `}function _h(e,t,n,r){return{client:t,isItemNotFoundError:o=>Ti(o)&&o.exitCode===d.NOT_FOUND,getItemAt:(o,i)=>ff(o,i,{pmRoot:e}),openRelationshipEventStore:o=>hf.open({pmRoot:e,nodes:o.nodes,registry:Rc(o.definitions),...o.relativePath===void 0?{}:{relativePath:o.relativePath}}),createRelationshipGraph:o=>new Xd(o.nodes,o.edges,Rc(o.definitions)),analyzeRelationshipImpact:(o,i,a)=>gf(o,i,a),validateRelationshipEvents:o=>{let i=new _f(o.nodes,{registry:Rc(o.definitions)});return o.events.map(a=>i.append({...a,expectedVersion:i.version}))},commitWorkspaceTransaction:o=>yf({...o,pmRoot:e}),mutateWorkspaceSettings:async o=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(o.operationId))throw new l("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",d.USAGE);let i=o.dryRun===!0?await Du(e,()=>A(e)):await A(e);try{let a=await ii({pmRoot:e,filePath:ne(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${eE("sha256").update(r).digest("hex").slice(0,16)}:${o.operationId}`,author:n??C(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!1,dryRun:o.dryRun===!0,mutate:async s=>{let c=s===null?null:JSON.parse(s),m=ti(c);if(!m.success)throw new l("Workspace settings mutation requires a valid initialized settings.json.",d.USAGE);let p=Ys(m.data),u=await o.mutate(structuredClone(p));if(!ti(u).success)throw new l("Workspace settings mutation returned invalid settings.json.",d.USAGE);let f=Le(p,u)?s:Js(u,{source:{raw:c,validated:m.data}});f=tE(f,u,o.replaceSubtrees);let _=ti(JSON.parse(f));if(!_.success)throw new l("Workspace settings mutation serialized invalid settings.json.",d.USAGE);return{raw:f,result:o.includePreview===!0?Ys(_.data):void 0}}});return a.changed&&o.dryRun!==!0&&await Y({path:ne(e),scope:"project",op:"extension:pm:settings"}),{changed:a.changed,dry_run:o.dryRun===!0,replayed:a.replayed===!0,...a.result===void 0?{}:{preview:a.result}}}finally{Mu(e)}}}}import nE from"node:fs/promises";import X from"node:path";import rE from"node:readline/promises";import{stdin as oE,stdout as De}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ffab1407-659d-5bc4-95ff-5efe52baf522")}catch{}})();var xc=Symbol.for("pm.sdk.init-invocation-cwd");var iE=()=>rE.createInterface({input:oE,output:De});function aE(){return structuredClone(At)}var sE=["minimal","default","strict"];function gh(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--preset must not be empty",d.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new l(`Invalid --preset value "${e}". Allowed: ${sE.join(", ")}`,d.USAGE)}function cE(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return yp(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${gp.join(", ")}`,d.USAGE)}}}function lE(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new l("--author must not be empty",d.USAGE);return t}function Oc(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:X.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function dE(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(o!==void 0){if(t.path!==void 0||Oc(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=X.resolve(e,o),p=X.join(m,".agents","pm");return{pmRoot:p,prefixArg:n,target:{mode:"workspace-path",tracker_root:p,workspace_root:m}}}if(t.path===void 0&&Oc(n)){let m=X.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let i=E(e,t.path),a=X.join(X.resolve(e),".agents","pm"),s=X.dirname(X.dirname(i)),c=X.resolve(i)===a?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:c,requested_cwd:X.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function mE(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new l("--id-prefix must not be empty",d.USAGE);if(Oc(t))throw new l(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,d.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&Lt(e)!==Lt(t))throw new l(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,d.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Lt(e)}`,`pm init --id-prefix ${Lt(t)}`]});return t}function pE(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--agent-guidance must not be empty",d.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new l(`Invalid --agent-guidance value "${e}". Allowed: ${Gf.join(", ")}`,d.USAGE)}function uE(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function yh(e,t){let n=Vd[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function fE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _E(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(fE).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function hE(e,t,n){let r=zo(t.schema),o=pt(e,r.files.types,mt.types),i=_p(await J(o)),a=[],s=[];for(let c of wp(n)){let m=hp(i,c);i=m.file,(m.replaced?s:a).push(m.definition.name)}return await We({pmRoot:e,filePath:o,raw:qo(i),op:"init:type-preset",author:C(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:s,file:o}}async function gE(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",X.join(".agents","pm")];for(let n of t)if(await q(X.join(e,n)))return!0;return!1}async function yE(e,t,n){if(!t||n||await q(X.join(e,"settings.json"))||!await gE(e))return;let r=X.join(e,".agents","pm");throw new l(`Refusing to initialize tracker files directly in workspace root "${e}".`,d.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function wh(e,t){let n=[],r=[];for(let o of t){let i=o?X.join(e,o):e,a=await q(i);await nE.mkdir(i,{recursive:!0}),a?r.push(`already_exists:${i}`):n.push(i),r.push(...await Y({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function wE(e,t){let n=iE();try{De.write(`pm init setup wizard (agent-optimized)
3
- `),De.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
1
+ import{n as Dp,o as zo,p as Kp,q as zp,r as $s,s as Vo,t as Hp,u as Fs,v as Wo,y as du,z as mu}from"./focused-chunks/chunk-SOB7X4FJ.js";import{a as gu,f as yu,h as Zt,m as wu,o as pr,r as ti,s as vu,t as bu,x as ku}from"./focused-chunks/chunk-73UNAJHD.js";import{$ as Un,$a as y_,A as Er,Ab as x_,B as xf,Bb as P_,C as Ii,Cb as N_,D as Pf,Db as L_,E as Nf,Eb as $_,Fb as F_,Gb as Cr,Ha as d_,Hb as yc,Ib as wc,J as Lf,Ja as p_,Jb as Di,K as $f,Ka as Li,Kb as vc,L as Ff,La as Vk,Lb as M_,M as Mf,Ma as u_,Mb as bc,N as Df,Na as f_,Nb as Ui,O as Uf,Oa as gc,Ob as qn,P as Gf,Pb as kc,Q as jf,Qb as Sc,R as qf,Rb as D_,S as Kf,Sb as U_,T as zf,Tb as wt,U as Hf,Ub as G_,V as Bf,Vb as Gi,W as Vf,Wb as j_,X as Wf,Xb as q_,Y as Yf,Yb as Kn,Z as Jf,Za as h_,Zb as Ec,_ as Xf,_a as g_,_b as K_,aa as Qf,ab as w_,ba as Zf,bb as v_,bc as ji,ca as e_,cb as b_,da as t_,db as k_,ea as Ut,eb as tn,fa as v,fb as S_,g as kf,ga as n_,gb as E_,h as Sf,ha as r_,hb as $i,ia as De,ib as A_,ic as z_,ja as o_,jb as T_,jc as H_,ka as uc,kb as C_,kc as B_,la as i_,lb as I_,ma as fc,mb as R_,na as Ar,nb as Fi,oa as Ri,ob as Gt,oc as V_,pa as Gn,pb as O_,pc as rh,qa as a_,qb as Mi,ra as Oi,sa as ye,ta as _c,tb as Tr,ua as he,va as s_,wa as c_,xa as xi,y as Of,ya as l_,z as dc,za as Pi}from"./focused-chunks/chunk-QMNAY25P.js";import{e as $p,g as Fp,h as Mp,k as Up,q as qp}from"./focused-chunks/chunk-R23T7GFZ.js";import{a as pu,b as uu,c as ei,d as fu,e as _u,f as hu,g as Rk}from"./focused-chunks/chunk-DVK7VKZL.js";import{M as cu,T as Ws,X as lu,a as Tm,b as Cm,c as Im,d as Rm,f as Om}from"./focused-chunks/chunk-IOTNG6CN.js";import{a as Cf,b as If,c as qi,d as Ki,e as zi}from"./focused-chunks/chunk-RAA7SVRA.js";import{K as __,b as Rf}from"./focused-chunks/chunk-RU6GCFN3.js";import{A as Q_,Aa as Ic,B as Z_,Fa as Rc,Ha as eh,Wa as Or,Ya as th,Za as nh,a as Ef,b as Bk,c as Af,d as Ci,g as mc,i as pc,k as hc,l as Ir,m as Wk,n as Ac,o as Tc,p as Hi,q as Yk,r as Jk,ta as Cc,w as W_,x as Y_,y as J_,ya as Rr,z as X_}from"./focused-chunks/chunk-3LQEBXU5.js";import{$a as vr,A as fe,B as Ln,C as _i,D as hi,G as gi,H as yi,I as af,Ia as Dn,J as wi,Ja as hf,K as vi,Ka as cc,L as $n,La as gf,M as ac,N as bi,O as sf,Oa as lc,P as cf,Pa as yf,Q as yr,Xa as Ei,_a as vf,a as Zu,b as si,c as ci,cb as bf,d as li,e as di,i as ef,j as Lt,k as Pn,kb as yt,l as mi,m as Nn,mb as Sr,n as pi,nb as en,o as pe,p as ui,pb as Tf,q as oc,qb as Ni,r as Je,s as ic,sa as _f,t as tf,u as Oe,vb as jn,w as ht,x as nf,y as fi,z as $t}from"./focused-chunks/chunk-S6ITXQ5T.js";import{c as Pp,f as Np,g as Lp,i as Ko,j as xt,k as Bp,l as Vp,m as Wp}from"./focused-chunks/chunk-6BTUISKV.js";import{a as Eu,b as Au,c as Tu}from"./focused-chunks/chunk-KGFRQ34R.js";import{$ as op,A as wo,Aa as Ep,B as Dm,Ba as Ap,C as Um,Ca as Ro,D as Gm,Da as Tp,E as vo,Ea as Cp,F as jm,Fa as Ip,G as qm,Ga as Oo,H as Km,Ha as xo,I as zm,Ia as Po,J as bo,Ja as No,K as ko,Ka as dr,L as Hm,La as Rp,M as So,Ma as Lo,Na as mr,O as Bm,Oa as $o,P as cr,Pa as Fo,Q as Vm,Qa as Mo,R as Wm,Ra as Do,S as Ym,Sa as Op,T as Jm,Ta as Rt,U as Xm,Ua as Uo,V as Qm,Va as Go,W as Zm,Wa as jo,X as ep,Xa as qo,Y as tp,Z as np,_ as rp,_a as xp,aa as ip,ab as Ot,ba as ap,bb as N,ca as sp,d as xs,da as lr,e as xm,ea as cp,fa as lp,ga as Eo,h as _o,ha as Ao,i as Ps,ia as dp,j as Xt,ja as mp,ka as pp,l as Pm,la as up,ma as fp,na as _p,oa as hp,pa as gp,q as Ns,r as Ls,ra as yp,s as ho,sa as wp,t as go,ta as vp,u as yo,ua as bp,v as Nm,va as kp,w as Lm,wa as Sp,x as $m,xa as To,y as Fm,ya as Co,z as Mm,za as Io}from"./focused-chunks/chunk-IIKFTJVC.js";import{$ as it,$a as rf,A as zk,Aa as Bu,Ab as mf,B as Hk,Ba as hr,Bb as I,C as xn,Cb as z,D as C,Db as ce,Eb as pf,Gb as _e,H as _t,Hb as uf,Ia as Vu,Ib as ki,Jb as gt,Ka as tc,Kb as Si,L as Ru,Lb as le,M as ii,Mb as ff,N as Ou,Na as Wu,O as xu,Oa as ai,P as Pu,Pa as Ye,Q as Nu,Qb as wf,R as Lu,Ra as Yu,Sa as Ju,T as ee,U as Ys,Ua as Xu,V as re,Va as nc,Wa as rc,Wb as br,X as $u,Xa as Qu,Xb as kr,Y as Js,Ya as A,Yb as Ai,Z as Fu,Za as Me,Zb as Xe,_ as We,_a as Re,a as ni,aa as Mu,ab as of,b as Ok,ba as Du,bb as Ft,c as xk,cc as Ti,d as Pk,da as Uu,db as ze,e as Nk,ea as Gu,eb as gr,fa as Xs,fb as Fn,gb as lf,hb as Mn,ia as Qs,ib as sc,jb as df,k as ri,ka as ju,l as Cu,la as qu,m as Iu,ma as Ku,n as On,na as zu,o as ur,oa as Hu,p as Lk,pb as wr,q as $k,r as Fk,s as Mk,sa as Fe,t as Dk,ta as Nt,tc as m_,u as Uk,v as Gk,va as Zs,w as jk,wa as fr,wb as Mt,x as qk,xa as _r,y as oi,ya as ec,yb as Dt,z as Kk,za as at}from"./focused-chunks/chunk-F5J3ATMV.js";import{b as It,c as mo,d as po,g as ut,i as Ho,j as ft,k as Pt,l as Gp,n as F,o as Bo,p as ot,r as jp}from"./focused-chunks/chunk-NNW5BS5L.js";import{e as Su}from"./focused-chunks/chunk-YLVHHWHN.js";import{$ as d,$a as E,Aa as Sn,Ae as iu,B as Yd,Bb as Ee,C as Jd,D as Xd,Db as B,E as Qd,Ec as Jp,Ee as au,F as Zd,Fb as Jt,G as em,Gc as Ms,Gd as hk,H as gs,Hc as Ds,Hd as gk,I as ys,Ia as En,Ic as Us,Ie as Ak,J as ws,Jb as lm,Jc as Gs,Jd as yk,Je as Tk,K as vs,Ka as am,Kb as dm,Kc as js,Kd as wk,Ke as Ck,L as bs,Lb as mm,Lc as qs,Ld as vk,Le as Ik,M as ks,Ma as Es,Mb as pm,Mc as Ks,Md as Hs,Me as Zo,Na as As,Nb as um,Nc as R,Nd as Bs,Ne as su,Ob as fm,Oc as Cn,Od as Vs,P as lo,Pb as Cs,Pc as Qt,Pd as eu,Qa as Ts,Qb as _m,Qc as Y,Ra as rr,Rc as Yo,Rd as tu,Sa as Ce,Sb as hm,Sc as In,Sd as bk,Tb as gm,U as Ss,Ud as kk,Va as x,Vc as Jo,Vd as Sk,W as tm,Wa as ke,Wb as Is,Wd as Ek,Xa as uo,Xb as ym,Xc as Ae,Ya as An,Yb as Rs,Yd as k,Z as Ct,Za as or,_a as sm,aa as l,ab as cm,ad as Xo,ae as Qo,bb as mt,cb as ne,ce as se,db as pt,dd as Xp,ed as Te,fb as rt,fe as Ie,gb as fo,gc as wm,hc as vm,ia as nm,ib as Yt,ic as bm,jb as Se,jc as km,ka as rm,kc as Sm,lc as Em,le as nu,mb as Tn,mc as Am,o as ao,oa as om,oc as ir,od as Qp,p as Wd,pa as im,q as so,r as hs,sa as j,sd as Zp,se as ru,ta as Wt,tc as ar,te as ou,ua as Ve,uc as Os,v as nr,va as X,vc as sr,w as dt,we as Rn,x as bn,xd as zs,y as kn,ya as te,yc as Yp,z as co}from"./focused-chunks/chunk-UPJA45K7.js";import{AsyncLocalStorage as zM}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="73dbe40e-f7a2-5aca-85aa-a5775e5e981a")}catch{}})();var Xk=Ws("list").properties.outputSession,Qk={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...Xk},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},oh={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},ih={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},de={type:"string",description:"pm item id, for example pm-abc1."},Zk=`Operation name (one of): ${Rs.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,eS={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},tS={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function D(e,t=[]){return{...ih,properties:{...ih.properties,...e},required:t}}var nS=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:D({action:{type:"string",enum:[...Rs],description:Zk},id:de,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...Qk},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:D({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:D({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:D({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:D({query:{type:"string"},options:{type:"object"},...tS},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:D({options:{type:"object"},...eS})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:D({id:de,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:D({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:D({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:de,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:de,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:D({id:de,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:D({id:de,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:de,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:D({id:de,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:D({id:de,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:de,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:D({id:de,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:D({id:de,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:D({id:de,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:D({id:de,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:D({id:de,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:D({id:de,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:D({subcommand:{type:"string",enum:[..._m]},id:de,target:de,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:D({id:de,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:D({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:D({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:D({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:D({...oh,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...Tn],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...hs]},description:`Lifecycle roles for add-status: ${hs.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:oh}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:D({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:D({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:D({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],rS={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},oS=nS.map(e=>{let t=rS[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Ws(t,{properties:n,required:r})}});function ah(){return oS.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e3cc5eb4-e3d3-54ee-99fb-4afb13905077")}catch{}})();var sh=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),iS=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],gh=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Vi=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),nn=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),yh=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),wh=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),vh=new Map([...wh.entries()].flatMap(([e,t])=>vt(t).map(n=>[n,e]))),bh=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Pc=new Map(bh.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),aS=10,sS=20,ch=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),kh=[["init",Bm],["install",Wm],["uninstall",Ym],["explore",Jm],["manage",np],["describe",Xm],["reload",rp],["doctor",op],["catalog",ip],["adopt",ap],["adopt-all",Qm],["activate",Zm],["deactivate",ep],["migrate",tp]],cS=[...kh.map(([e,t])=>e==="init"?[e,Vm]:[e,t]),["upgrade",lr]],lS=[...kh.map(([e,t])=>[`extension ${e}`,t]),...cS.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",ko],["config",Hm],["extension",So],["package",cr],["packages",cr],["install",sp],["create",Ro],["item mutate",Tp],["item complete",Cp],["item reopen",Ip],["copy",Oo],["focus",xo],["update",Po],["update-many",No],["upgrade",lr],["calendar",dr],["cal",dr],["context",mr],["ctx",mr],["get",$o],["search",Go],["eval",Op],["events",Lo],["workspace",Rt],["workspace position",[]],["workspace snapshot",Rt],["workspace snapshot create",Rt],["workspace snapshot list",Rt],["workspace snapshot inspect",Rt],["workspace snapshot restore",Rt],["workspace snapshot delete",Rt],["next",Uo],["aggregate",yo],["deps",Mo],["graph",Do],["guide",Fo],["reindex",cp],["history",wo],["history-compact",jm],["history-attest",qm],["history-redact",Um],["history-repair",Gm],["history-author-acknowledge",vo],["merge",Dm],["schema",Km],["profile",zm],["plan",bo],["restore",mp],["delete",pp],["close",lp],["close-many",Eo],["append",Ao],["claim",dp],["release",up],["start-task",fp],["pause-task",_p],["close-task",hp],["comments",Nm],["notes",Lm],["learnings",$m],["files",Fm],["docs",Mm],["test",wp],["test-runs-worker",[]],["test-all",vp],["telemetry",bp],["test-runs",kp],["gc",Sp],["stats",To],["ops",[]],["duplicates",Co],["validate",Ep],["health",Io],["assurance",Ap],...xp,["contracts",jo],["completion",qo],["activity",Rp],...[...gh].map(e=>[e,go])],xr=new Map(lS);for(let{alias:e,canonical:t}of Ee){let n=xr.get(e);n!==void 0&&xr.set(t,n)}function dS(e){return vh.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function lh(e){let t=Ee.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Cs.includes(e)?we(e):e.startsWith("extension-")?we(`extension ${e.slice(10)}`):e.startsWith("package-")?we(`package ${e.slice(8)}`):e.startsWith("item-")?we(`item ${e.slice(5)}`):e.startsWith("test-runs-")?we(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?we(`templates ${e.slice(10)}`):Vi.has(e)?wh.get(e)??we(e):null}function mS(e,t){let n=B(t);return n!==t||Ee.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:vt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function vt(e){return e.split("|").map(t=>we(t)).filter(t=>t.length>0)}function pS(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let i of vt(o.command_path)){let a=i.split(" ").filter(s=>s.length>0);if(a.length!==0)for(let s=a.length;s>0;s-=1){let c=a.slice(0,s).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function Bi(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Pr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function uS(e,t){if(!t)return{...e};let n=Pr(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:n}}function Oc(e,t){let n=Pr(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:n}}function we(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Sh(e){return e.replace(/\s+/g,"-")}function st(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function dh(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=st(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function xc(e,t,n){n&&(e[t]=!0)}function mh(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function fS(e){let t=mh(e.long,"long"),n=mh(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),xc(o,"required",e.required===!0),xc(o,"repeatable",e.repeatable===!0),xc(o,"list",e.list===!0);let i=st(e.description);i&&(o.description=i);let a=st(e.value_name);a&&(o.value_name=a);let s=[st(e.value_type),st(e.type),a?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return s&&(o.value_type=s),o}function Eh(e){let t=new Map;for(let r of e){let o=we(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},a=`${r.layer}:${r.name}`;i.sourceDedupe.has(a)||(i.sourceDedupe.add(a),i.sources.push({layer:r.layer,name:r.name}));for(let s of r.flags){let c=fS(s);if(!c)continue;let m=`${c.flag}|${c.short??""}`;i.dedupe.has(m)||(i.dedupe.add(m),i.flags.push(c))}t.set(o,i)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((i,a)=>{let s=i.layer.localeCompare(a.layer);return s!==0?s:(i.name??"").localeCompare(a.name??"")})});return n}function _S(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...Ls.filter(({flag:n})=>n.startsWith("--output-"))]}}function hS(e){let t=Eh(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let a=we(i.command);if(a.length===0)continue;let s=st(i.action)??Sh(a),c=Array.isArray(i.arguments)?i.arguments.map(m=>{let p=st(m.name);return p?{name:p,required:m.required===!0,variadic:m.variadic===!0,description:st(m.description)}:null}).filter(m=>m!==null):[];n.set(a,{...i.tier===void 0?{}:{tier:i.tier},..._S(i,t.get(a)?.flags??[]),command:a,action:s,source:{layer:i.layer,name:i.name},description:st(i.description),intent:st(i.intent),arguments:c,examples:dh(i.examples),failure_hints:dh(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(we(i));for(let i of n.keys())r.add(i);for(let i of t.keys())r.add(i);let o=[];for(let i of[...r].sort((a,s)=>a.localeCompare(s))){let a=n.get(i);o.push(gS(i,a,t.get(i)?.flags??[]))}return o}function gS(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Sh(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function yS(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let n=t.replace(/-([a-z0-9])/g,(r,o)=>o.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return n.length>0?n:null}function wS(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function vS(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function bS(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=wS(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=yS(o);!i||n[i]!==void 0||(n[i]=Ls.some(a=>a.flag===o.flag&&a.flag.startsWith("--output-"))?cu[i]:vS(o,e.action),o.required===!0&&r.push(i))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function kS(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function SS(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((i,a)=>i.localeCompare(a)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(i=>`${i.flag}|${i.short??""}`));for(let i of n.flags){let a=`${i.flag}|${i.short??""}`;if(!o.has(a))o.add(a),r.flags.push(i);else{let s=r.flags.find(c=>`${c.flag}|${c.short??""}`===a);s&&kS(s,i)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function ES(e,t=A){let n={mode:Ct.extensions.policy.mode,trust_mode:Ct.extensions.policy.trust_mode,default_sandbox_profile:Ct.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await j(ne(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await ar({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),a=await sr({...i,loaded:i.loaded});return{handlers:new Set(a.commands.handlers.map(s=>we(s.command))),disabledReason:null,commandDefinitions:a.registrations.commands,flagRegistrations:a.registrations.flags,registrations:a.registrations,policyState:{mode:i.policy.mode,trust_mode:i.policy.trust_mode,default_sandbox_profile:i.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function AS(e,t={}){let n=new Map;for(let r of Is){let o=Vi.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=lh(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of Vi)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:lh(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:Ee.find(o=>o.alias===r.command)?.canonical??we(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function TS(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null&&(!nn.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?vt(e.command_path):[],r=n.some(a=>t.handlers.has(a)||t.handlers.has(B(a))),o=n.map(a=>yh.get(B(a))).find(a=>typeof a=="string"),i=t.disabledReason===null&&r;return{action:e.action,invocable:i,available:i,requires_extension:!0,provider:"extension",disabled_reason:i?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function Ah(e){return xr.get(e)??ho}function CS(e){return nn.has(B(e))?!1:xr.has(e)}function IS(e){return gh.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function ph(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function RS(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function OS(e){let t=new Map;for(let r of e.definitions){let o=ph(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(s=>RS(s)).find(s=>s!==null),a=r.cli_aliases.map(s=>ph(s)).filter(s=>s!==null&&s!==o);for(let s of r.commands){let c=t.get(s)??{flags:[],seen:new Set},m=i?{flag:o,short:i}:{flag:o},p=`${m.flag}|${m.short??""}`;c.seen.has(p)||(c.seen.add(p),c.flags.push(m));for(let u of a){let f=`${u}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:u}))}t.set(s,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,Ns(o.flags));return n}function uh(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let i=`${o.flag}|${o.short??""}`;r.has(i)||(r.add(i),n.push(o))}return Ns(n)}function xS(e,t,n,r,o){let i=new Map(t);for(let{alias:a,canonical:s}of Ee){let c=t.get(s)??t.get(a);c&&(i.set(a,c),i.set(s,c))}return e.map(a=>{let s=CS(a),c=s?Ah(a):[],m=n.get(IS(a))??[],p=i.get(a),u=uh(c,m),f=uh(u,p?.flags??[]),_=c.length>0&&(p?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:a,flags:f,...r?{canonical_command:Ch(a),visibility:Th(a,o),positionals:xm(a)?.slots??[],flag_invocations:pr(a,f)}:{},provider:_,extension_sources:p?.sources}}).sort((a,s)=>a.command.localeCompare(s.command))}function PS(e,t=Jt){let n=new Set(e),r=new Map;for(let o of bh){let i=o.aliases.filter(a=>n.has(a));r.set(o.canonical,{canonical:o.canonical,aliases:i,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let i=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};i.aliases.includes(o.alias)||i.aliases.push(o.alias),i.contracts.push(o),r.set(o.canonical,i)}return[...r.values()].map(({contracts:o,...i})=>o.length===0?i:{...i,contracts:o}).sort((o,i)=>o.canonical.localeCompare(i.canonical))}function NS(){return{create_string_options:uu,create_repeatable_options:ei,update_string_options:_u,update_repeatable_options:hu,list_string_options:Tm,search_string_options:Cm,calendar_string_options:Im,context_string_options:Rm,activity_string_options:Om}}function fh(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let s of e.required_create_fields)n.add(s);for(let s of e.required_create_repeatables)n.add(s)}let r=An(e,"create",n),o=[...new Set(r.required)].sort((s,c)=>s.localeCompare(c)),i=[...new Set(o.map(s=>Ce("create",s)))].sort((s,c)=>s.localeCompare(c)),a=[...new Set(e.options.filter(s=>s.required===!0).map(s=>s.key))].sort((s,c)=>s.localeCompare(c));return{required_option_keys:o,required_flags:i,required_type_options:a,policy_errors:[...new Set(r.errors)].sort((s,c)=>s.localeCompare(c))}}function LS(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){let o=e.by_type[r];t[r]=fh(o,"strict"),n[r]=fh(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function $S(e,t){let n=Pr(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let a=i.properties;if(typeof a!="object"||a===null)return i;let s=a.action;return typeof s!="object"||s===null||s.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function FS(e){let t=Bi(e.action)!==void 0||Bi(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,i=e.flagsOnly===!0,a=e.availabilityOnly===!0,s=e.runtimeOnly===!0,c=e.full===!0,m=Bi(e.action),p=Bi(e.command),u=!r&&!c&&!o&&!i&&!a&&!m&&!p;return{selectedAction:m,selectedCommand:p,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:a,runtimeOnly:s,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||p!==void 0&&!c}}function MS(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",d.USAGE)}async function DS(e,t=A){try{return await t(e)}catch{return structuredClone(Ct)}}async function US(e,t,n){let r=await DS(t),o=await ES(e),i=x(r,o.registrations??R()),a=ot(r.schema),s=hS(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:F(r.schema),runtimeFieldRegistry:a,runtimeFieldFlagMap:OS(a),createRequiredOptionContracts:LS(i),extensionContracts:s,mergedExtensionContracts:SS(s.filter(c=>Wi(n,c.command,s))),extensionFlagMap:Eh(o.flagRegistrations)}}function _h(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Vi.has(e.selectedAction)||e.selectedCommand!==void 0&&nn.has(B(e.selectedCommand)))}function GS(e,t){let n=AS(t,{includePackageOwnedActions:_h(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(ym);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(i=>i.action===o.action)?.tier??ti(o.action))!=="internal"))}return _h(e)&&e.selectedCommand!==void 0&&nn.has(B(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:dS(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function jS(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new l(`Unknown action: "${e.selectedAction}".`,d.USAGE)}function qS(e,t){return[...new Set([...Cs.filter(n=>!nn.has(B(n))),...[...xr.keys()].filter(n=>!nn.has(B(n))),...e.flatMap(n=>n.command_path?vt(n.command_path).filter(r=>n.provider==="extension"||!nn.has(B(r))||t.some(o=>o.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let o=Ee.find(i=>i.alias===r||i.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>we(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function KS(e,t){let n=t.slice(0,aS),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,sS),a=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),s=t[0];return new l(`Command "${e}" is a command namespace. Choose a concrete child command: ${o}.`,d.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:a,nextSteps:[`Retry with a child command, for example: ${a[0]}`],recovery:{suggested_retry:`pm contracts --command "${s}" --flags-only --json`,fallback_candidates:i.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function zS(e,t){return new l(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,d.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function HS(e){return new l(`Unknown command: "${e}".`,d.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function BS(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(o=>o.startsWith(`${e.selectedCommand} `));if(n.length>0)throw KS(e.selectedCommand,n);let r=yh.get(B(e.selectedCommand));throw r?zS(e.selectedCommand,r):HS(e.selectedCommand)}function VS(e,t){let n=GS(e,t.mergedExtensionContracts);jS(e,n);let r=qS(n,t.mergedExtensionContracts);BS(e,r);let o=e.selectedCommand?vh.get(B(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(m=>o?m.action===o:mS(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.some(m=>m.action===e.selectedAction))throw new l(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,d.USAGE);let a=e.selectedAction?i.filter(m=>m.action===e.selectedAction):i,s=[...new Map(a.map(m=>TS(m,t.runtimeProbe)).map(m=>[o?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?s.filter(m=>m.invocable):s;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:i,scopedActionDescriptors:a,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function WS(e){return new Set(Pr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function YS(e){let t=lu,n=Pr(t),r=WS(t),o=e.filter(i=>!r.has(i.action)).map(i=>bS(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function hh(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?uS(n,e.selectedAction):e.selectedCommand?Oc(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):Oc(n,r);return e.runtimeOnly&&!e.selectedAction?Oc(o,new Set(t.actions)):o}function JS(e,t,n){let r=YS(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?$S(hh(e,n,r),t.createRequiredOptionContracts):hh(e,n,r);return{mergedSchema:r,filteredSchema:o}}function XS(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?pS(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Th(e,t){return t.find(n=>B(n.command)===B(e))?.tier??ti(e)}function Wi(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||Th(t,n)!=="internal"}function QS(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(Jt.filter(o=>o.hidden&&(o.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(o=>o.alias));if(e.summary&&!e.fullOutput)for(let o of Pc.keys())r.add(o);return t.filter(o=>!r.has(o)&&Wi(e,o,n))}function Ch(e){let t=Ee.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Pc.get(n)??n}var ZS=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),eE=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function tE(e,t){let n=ch.get(B(e))??(e.includes(" ")?void 0:ch.get(Ch(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>vt(m.command).some(p=>B(p)===B(e)));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let o=e.split(" "),i=o.at(-1),a=o.slice(0,-1).join(" "),s=ZS.get(i),c=eE.get(e)??a;return{intent:s===void 0||a.length===0?`Run ${e}.`:`${s} ${c}.`,intent_source:"generated"}}function nE(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(we))].filter(i=>i.length>0).sort((i,a)=>i.localeCompare(a)).map(i=>{let a=zs(i,{generateFallback:!0}),s=i.split(" ")[0],c=Pc.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),m=new Set([...Ah(i).map(f=>f.flag),...t.filter(f=>vt(f.command).some(_=>B(_)===B(i))).flatMap(f=>f.flags.map(_=>_.flag))]),p=(sh.get(B(i))??sh.get(c)??iS).filter(f=>m.has(f)),u=tE(i,t);return{command:i,intent:u.intent,...o||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...p.length>0?{flags:p}:{},default_max_estimated_tokens:a.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...a.default_max_estimated_tokens_by_format}}:{}}})}function rE(e){return e.map(t=>({budget:zs(t,{generateFallback:!0}),envelope:ku(t)}))}function oE(e){let t=new Map;for(let n of e){let r=yu(n),o=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,i=o.join(","),a=t.get(i)??{commands:[],exit_codes:o};a.commands.push(n),t.set(i,a)}return[...t.values()]}function iE(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>vt(r.command).some(o=>B(o)===B(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>vt(o.command).some(i=>r.has(i)))}return t.extensionContracts.filter(r=>Wi(e,r.command,t.extensionContracts))}function aE(e,t,n,r){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function sE(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=Su);let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,i])=>[o,[...new Set(i.map(a=>`--${a.cli_flag}`))].sort((a,s)=>a.localeCompare(s))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...lm],services:[...dm],policy_modes:[...mm],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...fm],trust_modes:[...pm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...um],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Yd],create_modes:[...Jd],close_validation_modes:[...Xd],workflow_enforcement_modes:[...Qd]},e.relationship_kind_contracts=[...nm,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,i)=>o.kind.localeCompare(i.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function cE(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function lE(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=xS(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(Tu).filter(([a])=>i.has(a)).map(([a,s])=>({command:a,default:s,brief_fields:[...Au],compact_fields:[...Eu]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:a})=>({canonical:i,aliases:a})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function dE(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=NS();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function mE(e,t,n,r){e.command_summaries=nE(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Qp],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(we))].filter(o=>Bs(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...eu(o).keys()]}))}:{}},e.grammar_contracts={nouns:Xt.nouns,shared_verbs:Xt.shared_verbs,scope_before_verb:Xt.scope_before_verb,visible_top_level_ceiling:Xt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Xt.ceiling_raise_requires_pm_item,positional_shape_budget:Xt.positional_shape_budget,positional_shape_count:new Set(Ps.map(({slots:o})=>Pm(o))).size,positional_action_count:xs.length,positional_action_parents:[...new Set(xs.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:Ps}:{}}}async function Nc(e,t){let n=FS(e);MS(n);let r=E(process.cwd(),t.path),o=await US(t,r,n),i=VS(n,o),a=JS(n,o,i),s=XS(n,i),c=QS(n,s,o.extensionContracts),m=aE(n,a,i,c),p=iE(n,o,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&mE(m,c,p,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return m;let f=PS(i.commandCatalog.filter(_=>Wi(n,_,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||sE(m,o,n),cE(m,n,a,p),lE(m,n,o,c,f),dE(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...Sf],gate_triggers:[...kf]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=_o.map(_=>({..._,reason:_.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=ah(),m.context_intents=ru(),m.read_output_dimensions=Hs,m.error_codes=wu,m.command_output_contracts=rE(c),m.diagnostic_output_contracts=Zp,m.command_exit_contracts={vocabulary:gu,command_sets:oE(c)}),m}import{readFile as pE}from"node:fs/promises";import uE from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="20a3a324-d176-5918-8167-5e548be4abc9")}catch{}})();var Lc="context-intents.json";function Yi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fE(e,t,n){if(!Yi(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function Ih(e,t){let n=Array.isArray(e)?e:Yi(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,o)=>fE(r,t,o))}async function _E(e){let t=uE.join(e,Lc),n;try{n=await pE(t,"utf8")}catch(o){if(Wt(o))return[];throw await mf(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Lc}: ${i}`,{cause:o})}return Ih(r,Lc)}function hE(e){if(!Yi(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Yi(n)?n.contextIntents??n.context_intents:void 0}function gE(e){return e.flatMap(t=>{let n=hE(t.module);return n===void 0?[]:Ih(n,`package ${t.name}`)})}async function yE(e){let t=await _E(e.pmRoot),n=gE(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function $c(e,t){let n=await yE(e);return await ou(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a4abc17-0fcb-573f-8f89-6e505e112261")}catch{}})();async function Rh(e,t,n=nu){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=t,o=Array.isArray(r.warnings)?r.warnings.filter(i=>typeof i=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as wE}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="93e1b043-89b2-546e-b238-1b9f4a1df742")}catch{}})();function Fc(e){let t=rm();for(let n of e)t.register(n);return t}function vE(e,t,n=[]){if(n.length===0)return e;let r=JSON.parse(e),o=JSON.parse(rc(t));for(let i of n){let a=i.split("."),s=o;for(let p of a){let u=Es(s);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(p)||["constructor","prototype","__proto__"].includes(p)||u===null||!Object.hasOwn(u,p))throw new l(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,d.USAGE);s=u[p]}if(Es(s)===null)throw new l(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,d.USAGE);let c=r,m=o;for(let p of a.slice(0,-1)){let u=c[p];m=m[p],u===void 0&&Object.defineProperty(c,p,{value:structuredClone(m),enumerable:!0,writable:!0,configurable:!0}),c=c[p]}Object.defineProperty(c,a.at(-1),{value:s,enumerable:!0,writable:!0,configurable:!0})}return Se(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
2
+ `}function Oh(e,t,n,r){return{client:t,isItemNotFoundError:o=>Ci(o)&&o.exitCode===d.NOT_FOUND,getItemAt:(o,i)=>Tf(o,i,{pmRoot:e}),openRelationshipEventStore:o=>If.open({pmRoot:e,nodes:o.nodes,registry:Fc(o.definitions),...o.relativePath===void 0?{}:{relativePath:o.relativePath}}),createRelationshipGraph:o=>new im(o.nodes,o.edges,Fc(o.definitions)),analyzeRelationshipImpact:(o,i,a)=>Rf(o,i,a),validateRelationshipEvents:o=>{let i=new Cf(o.nodes,{registry:Fc(o.definitions)});return o.events.map(a=>i.append({...a,expectedVersion:i.version}))},commitWorkspaceTransaction:o=>Of({...o,pmRoot:e}),mutateWorkspaceSettings:async o=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(o.operationId))throw new l("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",d.USAGE);let i=o.dryRun===!0?await Ju(e,()=>A(e)):await A(e);try{let a=await ai({pmRoot:e,filePath:ne(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${wE("sha256").update(r).digest("hex").slice(0,16)}:${o.operationId}`,author:n??C(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!1,dryRun:o.dryRun===!0,mutate:async s=>{let c=s===null?null:JSON.parse(s),m=ni(c);if(!m.success)throw new l("Workspace settings mutation requires a valid initialized settings.json.",d.USAGE);let p=nc(m.data),u=await o.mutate(structuredClone(p));if(!ni(u).success)throw new l("Workspace settings mutation returned invalid settings.json.",d.USAGE);let f=Se(p,u)?s:rc(u,{source:{raw:c,validated:m.data}});f=vE(f,u,o.replaceSubtrees);let _=ni(JSON.parse(f));if(!_.success)throw new l("Workspace settings mutation serialized invalid settings.json.",d.USAGE);return{raw:f,result:o.includePreview===!0?nc(_.data):void 0}}});return a.changed&&o.dryRun!==!0&&await Y({path:ne(e),scope:"project",op:"extension:pm:settings"}),{changed:a.changed,dry_run:o.dryRun===!0,replayed:a.replayed===!0,...a.result===void 0?{}:{preview:a.result}}}finally{Yu(e)}}}}import bE from"node:fs/promises";import Q from"node:path";import kE from"node:readline/promises";import{stdin as SE,stdout as Ue}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ffab1407-659d-5bc4-95ff-5efe52baf522")}catch{}})();var Dc=Symbol.for("pm.sdk.init-invocation-cwd");var EE=()=>kE.createInterface({input:SE,output:Ue});function AE(){return structuredClone(Ct)}var TE=["minimal","default","strict"];function Ph(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--preset must not be empty",d.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new l(`Invalid --preset value "${e}". Allowed: ${TE.join(", ")}`,d.USAGE)}function CE(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return Fp(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${$p.join(", ")}`,d.USAGE)}}}function IE(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new l("--author must not be empty",d.USAGE);return t}function Mc(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:Q.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function RE(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(o!==void 0){if(t.path!==void 0||Mc(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=Q.resolve(e,o),p=Q.join(m,".agents","pm");return{pmRoot:p,prefixArg:n,target:{mode:"workspace-path",tracker_root:p,workspace_root:m}}}if(t.path===void 0&&Mc(n)){let m=Q.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let i=E(e,t.path),a=Q.join(Q.resolve(e),".agents","pm"),s=Q.dirname(Q.dirname(i)),c=Q.resolve(i)===a?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:c,requested_cwd:Q.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function OE(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new l("--id-prefix must not be empty",d.USAGE);if(Mc(t))throw new l(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,d.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&Ft(e)!==Ft(t))throw new l(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,d.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Ft(e)}`,`pm init --id-prefix ${Ft(t)}`]});return t}function xE(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--agent-guidance must not be empty",d.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new l(`Invalid --agent-guidance value "${e}". Allowed: ${Qf.join(", ")}`,d.USAGE)}function PE(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Nh(e,t){let n=tm[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function NE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function LE(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(NE).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function $E(e,t,n){let r=Ho(t.schema),o=ft(e,r.files.types,ut.types),i=Np(await X(o)),a=[],s=[];for(let c of Mp(n)){let m=Lp(i,c);i=m.file,(m.replaced?s:a).push(m.definition.name)}return await Ye({pmRoot:e,filePath:o,raw:Ko(i),op:"init:type-preset",author:C(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:s,file:o}}async function FE(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",Q.join(".agents","pm")];for(let n of t)if(await j(Q.join(e,n)))return!0;return!1}async function ME(e,t,n){if(!t||n||await j(Q.join(e,"settings.json"))||!await FE(e))return;let r=Q.join(e,".agents","pm");throw new l(`Refusing to initialize tracker files directly in workspace root "${e}".`,d.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function Lh(e,t){let n=[],r=[];for(let o of t){let i=o?Q.join(e,o):e,a=await j(i);await bE.mkdir(i,{recursive:!0}),a?r.push(`already_exists:${i}`):n.push(i),r.push(...await Y({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function DE(e,t){let n=EE();try{Ue.write(`pm init setup wizard (agent-optimized)
3
+ `),Ue.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
4
4
 
5
- `),De.write(`1/3 Item ID prefix
6
- `),De.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
7
- `);let r=await n.question(`Item ID prefix [${e}]: `),o=r.trim().length>0?Lt(r):e;De.write(`
5
+ `),Ue.write(`1/3 Item ID prefix
6
+ `),Ue.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
7
+ `);let r=await n.question(`Item ID prefix [${e}]: `),o=r.trim().length>0?Ft(r):e;Ue.write(`
8
8
  2/3 Governance preset
9
- `),De.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
10
- `),De.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
11
- `),De.write(`strict: ownership blocking, strict create defaults, close validation strict.
12
- `);let i=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),a=i.trim().length>0?i.trim():"minimal",s="minimal";try{s=gh(a)}catch{De.write(`Unrecognized governance preset "${a}"; using minimal.
13
- `)}De.write(`
9
+ `),Ue.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
10
+ `),Ue.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
11
+ `),Ue.write(`strict: ownership blocking, strict create defaults, close validation strict.
12
+ `);let i=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),a=i.trim().length>0?i.trim():"minimal",s="minimal";try{s=Ph(a)}catch{Ue.write(`Unrecognized governance preset "${a}"; using minimal.
13
+ `)}Ue.write(`
14
14
  3/3 Project telemetry
15
- `),De.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
16
- `);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),p=uE(m,t);return De.write(`
17
- `),{prefix:o,preset:s,telemetry_enabled:p}}finally{n.close()}}function vE(e){return{presetFromOption:gh(e.preset),useDefaults:e.defaults===!0,authorFromOption:lE(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:pE(e.agentGuidance),typePreset:cE(e.typePreset)}}function bE(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function kE(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function SE(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(yh(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function EE(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=bE({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return kE(e.settingsPath,n,e.options.force===!0,e.target),SE({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Fe(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function AE(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await wE(t,At.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let i=n??"minimal",a=aE();a.id_prefix=t,yh(a,i);let s=ri()?.trim()||void 0;return a.author_default=e.normalizedOptions.authorFromOption??s??"",r!==void 0&&(a.telemetry.enabled=r,a.telemetry.first_run_prompt_completed=!0),await Fe(e.pmRoot,a),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function hh(e){return e.settingsExists?await EE(e):await AE({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function TE(e){let t=await jf({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await Fe(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function CE(e,t){let n=[],r=[],o=await kp(e,t.schema);for(let i of o.created_paths)n.push(i),r.push(...await Y({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function IE(e){if(e.typePreset===void 0)return;let t=await hE(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await Y({path:t.file,scope:"project",op:"init:type_preset"})),t}async function RE(e){let t=x(e.settings,O()).folders.filter(r=>!gs.includes(r)),n=await wh(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function OE(e){let t=X.resolve(e.tracker_root),n=X.dirname(t);return X.basename(t)==="pm"&&X.basename(n)===".agents"?X.dirname(n):e.workspace_root}async function xE(e,t,n,r){if(!e)return;let o=await Gn("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let i=_E(o),a=i.packages.filter(s=>!s.ok).map(s=>s.alias);if(!i.installed_all||a.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,d.GENERIC_FAILURE);return i}function PE(e){let t=r=>Zt([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function NE(e,t,n,r=bf){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function LE(e,t,n,r){if(e==null||n==="status")return;let o=await rc(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Pr(e,t,n={}){let r=t[xc],o=typeof r=="string"?r:process.cwd(),i=dE(o,t,e,n.workspace),a=i.pmRoot;e=mE(i.prefixArg,n.idPrefix);let s=vE(n);await yE(a,i.target.mode==="tracker-path",n.force===!0);let c=[],m=[],p=X.join(a,"settings.json"),u=await q(p),f;u&&(f=await hh({pmRoot:a,settingsPath:p,settingsExists:u,normalizedPrefix:Lt(e),prefixArg:e,options:n,normalizedOptions:s,warnings:m,target:i.target}));let _=await wh(a,gs);c.push(..._.createdDirs),m.push(..._.warnings),f??=await hh({pmRoot:a,settingsPath:p,settingsExists:u,normalizedPrefix:Lt(e),prefixArg:e,options:n,normalizedOptions:s,warnings:m,target:i.target});let{settings:h}=f,g=OE(i.target),y=await Ci(g??X.dirname(a)),w=g??y,b=await TE({pmRoot:a,cwd:w??o,agentGuidanceMode:s.agentGuidanceMode,settings:h,warnings:m}),S=await CE(a,h);c.push(...S.createdDirs),m.push(...S.warnings);let T=await IE({pmRoot:a,settings:h,typePreset:s.typePreset,warnings:m});T&&(h=await A(a)),await RE({pmRoot:a,settings:h,createdDirs:c,warnings:m}),await LE(w,a,s.agentGuidanceMode,m),!u&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await NE(a,y,m);let L=await xE(s.installBundledPackages,t,a,m),P=PE({installBundledPackages:s.installBundledPackages,registeredTypePreset:T,agentGuidanceNextSteps:b.next_steps,target:i.target});return{ok:!0,path:a,target:i.target,settings:h,created_dirs:c,warnings:m,governance_preset:h.governance.preset,wizard_used:f.wizardUsed,...T?{registered_type_preset:T}:{},...L?{installed_packages:L}:{},next_steps:P,agent_guidance:b}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08ad3dd1-a1ec-5ee8-9f0f-1350dd91f25e")}catch{}})();async function vh(e,t){let n=E(t??process.cwd(),e),r=await A(n);return _e(n,r.item_format,x(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="247354d6-fccb-58f8-b969-b1952abf181e")}catch{}})();var $E={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function bh(e){return Object.fromEntries(Dp.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var kh={ctx:{action:"context"},...$E,...bh("extension"),...bh("package"),...Object.fromEntries(Up.map(e=>[`package-${e}`,{action:e}]))};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="baa27a48-c538-574c-9d05-1f1c0f4f429c")}catch{}})();function Sh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function FE(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function Pc(e,t){let n=FE(t),r=n==="brief"?n:Sh(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:Sh(e.filters)?e.filters:{},projection:r}}}import{readFile as ME}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35773218-9c35-51d9-a19b-e9094bd23b66")}catch{}})();function Vi(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Ie(e,t)}function Eh(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,d.USAGE,{code:"structured_event_immutable"})}function Nc(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function on(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Hn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let o=me(n,"--add");return Object.keys(o).map(i=>i.trim().toLowerCase()).some(i=>i!=="text")?n:o.text?.trim()||n}catch{return n}}function Lc(e){return typeof e=="object"&&e!==null&&"code"in e}function Lr(e,t){if(!ft(e))throw new l(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,d.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function DE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,d.USAGE);let n=Nt(),r=ft(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return Lr(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let o=e.file.trim();if(!o)throw new l("--file path cannot be empty",d.USAGE);if(o==="-")return Lr(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await ME(o,"utf8"),emptyFlag:"--file"}}catch(i){if(Lc(i)&&Wt(i))throw new l(`--file path not found: ${o}. Use --file - to read stdin.`,d.USAGE);let a=i instanceof Error?i.message:String(i);throw new l(`Failed to read --file path "${o}": ${a}. Use --file - to read stdin.`,d.USAGE)}}async function Wi(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",d.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",d.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",d.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",d.USAGE);let n=await DE(e,t);if(e.edit!==void 0){if(!n)throw new l("--edit requires replacement text from --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function Nr(e,t){throw e instanceof l&&e.exitCode===d.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Th(e){return e==="comments"?"--stdin":"--add -"}function UE(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let n=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(n))return;let r=Th(t.collectionKey),o=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new l(`--add value "${n}" looks like an option, not annotation text. Use ${r} to read stdin, or use text=${n} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${r} for stdin input, pass plain text, or use text=${n} when the text really starts with "-".`,examples:[`${o} ${r}`,`${o} --add text=${n}`]})}function GE(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new l(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,d.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,d.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${Th(e.collectionKey)}`]})}function jE(e,t,n,r,o,i){let a=on(e.metadata,t),s=o?a.findIndex(c=>c.author===n&&c.text===r):-1;return s>=0?{changedFields:[],entryIndex:s+1}:(a.push(i({created_at:k(),author:n,text:r})),e.metadata[t]=a,{changedFields:[t],entryIndex:a.length})}async function Bn(e,t,n,r){GE(r,t);let o=E(process.cwd(),n.path);await I(o);let i=await A(o),a=x(i,O()),s=gr(t.limit);if(r.input.mode==="list"){let h=await z(o,e,i.id_prefix,i.item_format,a.type_to_folder);if(!h)throw new l(`Item ${e} not found`,d.NOT_FOUND);let g=await ae(h,{schema:i.schema}),y=on(g.document.metadata,r.collectionKey);return Bi(h.id,r.collectionKey,y,s,t.includeMeta===!0)}let c=C(t.author,i.author_default);if(r.input.mode==="delete"){let h=r.deleteOp??r.op,g;try{g=await se({pmRoot:o,settings:i,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=on(w.metadata,r.collectionKey),S=Ah(r.input.index,b.length,r.collectionKey);return Eh(b[S],"deleted"),b.splice(S,1),w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){Nr(w,r.conflictGuidance)}let y=on(g.item,r.collectionKey);return Bi(g.item.id,r.collectionKey,y,s,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";UE(m,r);let p=r.parseText(r.input.value??"");if(!p.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,d.USAGE);if(r.input.mode==="edit"){let h=r.editOp??r.op,g;try{g=await se({pmRoot:o,settings:i,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=on(w.metadata,r.collectionKey),S=Ah(r.input.index,b.length,r.collectionKey),T=b[S];return Eh(T,"edited"),b[S]={...T,text:p,edited_at:k()},w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){Nr(w,r.conflictGuidance)}let y=on(g.item,r.collectionKey);return Bi(g.item.id,r.collectionKey,y,s,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:y[r.input.index-1]},t.fullHistory===!0)}let u,f=0;try{u=await se({pmRoot:o,settings:i,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(h){let g=jE(h,r.collectionKey,c,p,t.ifAbsent===!0,r.createEntry);return f=g.entryIndex,{changedFields:g.changedFields}}})}catch(h){Nr(h,r.conflictGuidance)}let _=on(u.item,r.collectionKey);return Bi(u.item.id,r.collectionKey,_,s,t.includeMeta===!0,{action:"add",entryIndex:f,entry:_[f-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Ah(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,i=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${o} index ${e??"(missing)"} out of range (item has ${i})`,d.USAGE)}return e-1}function qE(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function Bi(e,t,n,r,o,i,a=!1){let s=i===void 0||a?Nc(n,i!==void 0&&a?void 0:r):i.entry===void 0?[]:[i.entry],c=i!==void 0&&s.length<n.length;return{id:e,[t]:s,count:s.length,...i?.changedCount===void 0?{}:{changed:i.changedCount===1},...[o,i!==void 0].includes(!0)?{total_count:n.length,returned_count:s.length,has_more:c||s.length<n.length,...r!==void 0?{limit:r}:{}}:{},...qE(t,i,c)}}import{readFile as KE}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8513dce5-85a0-56aa-bb8f-c64756ac4b2e")}catch{}})();async function $c(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",i=Number(n)+Number(r)+Number(o);if(i===0)return;if(i>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",d.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",ft(e))??"",emptyFlag:"--add"};if(r)return Lr(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let a=e.file.trim();if(!a)throw new l("--file path cannot be empty",d.USAGE);if(a==="-")return Lr(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await KE(a,"utf8"),emptyFlag:"--file"}}catch(s){if(Lc(s)&&Wt(s))throw new l(`--file path not found: ${a}. Use --file - to read stdin.`,d.USAGE);let c=s instanceof Error?s.message:String(s);throw new l(`Failed to read --file path "${a}": ${c}. Use --file - to read stdin.`,d.USAGE)}}async function zE(e,t){let n=e.edit,r=e.delete,o=n!==void 0,i=r!==void 0;if(o&&i)throw new l("Specify only one of --edit or --delete",d.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",d.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",d.USAGE);if(i){if(await $c(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(o){let s=await $c(e,t);if(s===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:n,value:s.value,emptyFlag:s.emptyFlag}}let a=await $c(e,t);return a===void 0?{mode:"list"}:{mode:a.emptyFlag==="--add"?"add":a.emptyFlag==="--stdin"?"stdin":"file",value:a.value,emptyFlag:a.emptyFlag}}async function Ch(e,t,n){let r=Nt(),o=await zE(t,r),i=o.mode==="add"||o.mode==="edit",a=o.value??"";return Bn(e,t,n,{input:{...o,rawValue:t.add??a,value:i?Hn(a,{stripPlainTextPrefix:!0}):a},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:s=>s,createEntry:s=>s,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm comments --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78e92b9c-f3da-594e-8158-00409222308f")}catch{}})();var Ih=new Set(["item_format"]),Rh=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),HE=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),BE=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),VE={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function WE(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(Ih.has(t)||Rh.has(t)||HE.has(t)||t==="context")return t}function YE(e){let t=e.trim().toLowerCase();return VE[t]??e}function Oh(e,t){let n=WE(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:Ih.has(n)?{routable:!0,flag:"format",value:t}:Rh.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:BE.has(n)?YE(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="544840da-22f5-5734-81ec-e12c5612545c")}catch{}})();var JE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function xh(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>128)throw new Error("A legacy author must contain 1-128 characters.");return t}function XE(e){let t=e?.trim().toLowerCase();if(!t||!JE.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function QE(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function ZE(e,t){let n=new Set;for(let r of(e??[]).slice(0,1e4)){let o=r.trim().slice(0,128);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function eA(e,t){let n=xh(t.legacy_author),r=XE(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function tA(e,t){if(t.operation==="add")return eA(e,t);if(t.operation==="remove"){let r=xh(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function Fc(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function Ph(e,t){let n=e?.version??1,r={...e?.aliases},o=tA(r,t),i={version:o?n+1:n,aliases:QE(r)};return{vocabulary:i,preview:{operation:t.operation,changed:o,version_before:n,version_after:i.version,alias_count:Object.keys(i.aliases).length,residual_author_count:ZE(t.observed_authors,i.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d9b6f2ba-2c5e-52ea-891d-53124601fb89")}catch{}})();var Nh=["project","global"],yt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},nA=Object.keys(yt).map(e=>yt[e][0]),rA=Object.fromEntries(Object.keys(yt).flatMap(e=>yt[e].map(t=>[t,e]))),oA={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},iA=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],aA=new Set(["metadata_required_fields",...iA]),sA=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),cA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),lA=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),dA=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),mA=new Set(["governance_preset","governance_create_default_type"]),Dh=e=>aA.has(e),pA=e=>lA.has(e),uA=e=>dA.has(e),fA=e=>mA.has(e);function Mc(e){return e==="definition_of_done"||Dh(e)}function _A(e){if(Nh.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${Nh.join(", ")}`,d.USAGE)}function hA(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Ce({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function gA(e){let t=rA[e];if(t)return t;let n=As.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${nA.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function yA(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",d.USAGE);return n}function wA(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",d.USAGE):new l("Config set item-format requires --format toon",d.USAGE)}function Uh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",d.USAGE)}function vA(e){return Uc(e,"test-result-tracking")}function Uc(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,d.USAGE)}function Gh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function Gc(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",d.USAGE)}function jh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",d.USAGE)}function qh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",d.USAGE)}function Kh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",d.USAGE)}function zh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",d.USAGE)}function Hh(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-workflow-enforcement requires one of: off, warn, strict",d.USAGE)}function Bh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",d.USAGE)}function Vh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",d.USAGE)}var bA={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function Lh(e,t){let n=bA[e];if(n)return Uc(t,n);switch(e){case"history_missing_stream_policy":return Uh(t);case"sprint_release_format_policy":return Zs(t);case"parent_reference_policy":case"governance_parent_reference_policy":return gi(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Gc(t);case"governance_preset":return jh(t);case"governance_ownership_enforcement":return qh(t);case"governance_create_mode_default":return Kh(t);case"governance_close_validation_default":return zh(t);case"governance_require_close_reason":return Vh(t);case"governance_workflow_enforcement":return Hh(t);case"governance_force_required_for_stale_lock":return Bh(t);case"telemetry_tracking":return Gh(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var $h={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},kA=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function SA(e,t){let n=[...new Set((e??[]).map(i=>i.trim()).filter(i=>i.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",d.USAGE);let r=n.map(i=>i.toLowerCase().replaceAll("-","_")),o=r.filter(i=>$h[i]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${kA.join(", ")}`,d.USAGE);return[...new Set(r.map(i=>$h[i]))].sort((i,a)=>i.localeCompare(a))}function EA(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));if(n){if(r.length>0)throw new l(`Config set ${yt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${yt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function AA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function TA(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,d.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,d.USAGE);return gA(t)}function Wh(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var CA={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>Fc(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function jc(e,t){return CA[t](e)}function Re(e,t){return t.length===0?e:{...e,warnings:t}}async function IA(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):lt(n),o=ne(r);return e==="project"&&await I(r),{pmRoot:r,settingsPath:o}}function RA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,d.USAGE)}function Fh(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new l(`Context ${t} must be a positive integer`,d.USAGE)}async function OA(e,t,n,r,o){let i=!1,a=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!hs.includes(c))throw new l(`Context --default-depth must be one of ${hs.join("|")}`,d.USAGE);a.default_depth!==c&&(a.default_depth=c,i=!0)}if(t.activityLimit!==void 0){let c=Fh(t.activityLimit,"--activity-limit");a.activity_limit!==c&&(a.activity_limit=c,i=!0)}if(t.staleThresholdDays!==void 0){let c=Fh(t.staleThresholdDays,"--stale-threshold-days");a.stale_threshold_days!==c&&(a.stale_threshold_days=c,i=!0)}let s=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of s){let p=RA(m);if(p!==void 0){let u=c;a.sections[u]!==p&&(a.sections[u]=p,i=!0)}}return i&&await Fe(n.pmRoot,e,"config:set:context"),Re({scope:r,key:"context",context_settings:{default_depth:a.default_depth,activity_limit:a.activity_limit,stale_threshold_days:a.stale_threshold_days,sections:{...a.sections}},settings_path:n.settingsPath,changed:i},o)}function xA(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,d.USAGE);return{...n,value:t}}function PA(e,t,n,r,o,i){if(o===void 0)return i;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,d.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',d.USAGE);if(r)return xA(t,o,i);Wh(n);let a=Oh(n,o);if(!a.routable)throw new l(a.reason,d.USAGE);if(a.flag==="criterion"){if(i.criterion!==void 0&&i.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...i,criterion:a.values}}if(a.flag==="format")return{...i,format:a.value};if(i.policy!==void 0&&Lh(n,i.policy)!==Lh(n,a.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${i.policy}". Pass only one.`,d.USAGE);return{...i,policy:a.value}}function NA(e){let t=Object.keys(yt).map(r=>({key:r,aliases:yt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":Mc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:Mc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:oA[r],value:jc(e.settings,r)})),n=As.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Ts(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Re({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function LA(e){let t=Object.fromEntries(Object.keys(yt).map(n=>[n,jc(e.settings,n)]));return Re({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function $A(e,t){let n=jc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Re({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Re({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Re({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Re({...r,criteria:n},e.warnings):Re({...r,policy:n},e.warnings)}async function FA(e,t,n,r){if(t==="get"){let s=Ts(e.settings,n);return Re({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:s},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let i=Cp(n,o);if(!i.ok)throw new l(i.error.message,d.USAGE);let a=Vo(e.settings,n,i.parsed.value);return a&&await Fe(e.target.pmRoot,e.settings,`config:set:${n.path}`),Re({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:i.parsed.value},settings_path:e.target.settingsPath,changed:a},e.warnings)}async function Q(e,t,n){t&&await Fe(e.target.pmRoot,e.settings,n)}function Mh(e,t,n){return e!==n||t!==n}function pe(e,t,n,r){return Re({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Dc(e,t,n,r){return Re({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function MA(e,t){let n=wA(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let i=x(e.settings,O()),a=await rf(e.target.pmRoot,n,"config:set:item_format:migrate",i.type_to_folder,e.settings.schema);o={target_format:a.target_format,scanned:a.scanned,migrated:a.migrated,removed:a.removed,warnings:a.warnings},e.settings.item_format=n,await Fe(e.target.pmRoot,e.settings,"config:set:item_format")}return Re({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function DA(e,t,n){if(t==="history_missing_stream_policy"){let i=Uh(n.policy),a=e.settings.history.missing_stream!==i;return e.settings.history.missing_stream=i,await Q(e,a,"config:set:history_missing_stream_policy"),pe(e,t,e.settings.history.missing_stream,a)}if(t==="sprint_release_format_policy"){let i=Zs(n.policy),a=e.settings.validation.sprint_release_format!==i;return e.settings.validation.sprint_release_format=i,await Q(e,a,"config:set:sprint_release_format_policy"),pe(e,t,e.settings.validation.sprint_release_format,a)}if(t==="parent_reference_policy"){let i=gi(n.policy),a=e.settings.validation.parent_reference!==i||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==i;return e.settings.validation.parent_reference=i,e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,await Q(e,a,"config:set:parent_reference_policy"),pe(e,t,e.settings.validation.parent_reference,a)}let r=Gc(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Q(e,o,"config:set:metadata_validation_profile"),pe(e,t,e.settings.validation.metadata_profile,o)}async function UA(e,t,n){if(t==="metadata_required_fields"){let a=SA(n.criterion,n.clearCriteria),s=a.length!==e.settings.validation.metadata_required_fields.length||a.some((c,m)=>c!==e.settings.validation.metadata_required_fields[m]);return e.settings.validation.metadata_required_fields=a,await Q(e,s,"config:set:metadata_required_fields"),Dc(e,t,[...e.settings.validation.metadata_required_fields],s)}let r={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],o=EA(t,n.criterion,n.clearCriteria),i=o.length!==r.length||o.some((a,s)=>a!==r[s]);return r.splice(0,r.length,...o),await Q(e,i,`config:set:${t}`),Dc(e,t,[...r],i)}async function GA(e,t,n){if(t==="governance_preset"){let c=jh(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Q(e,m,"config:set:governance_preset"),pe(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Q(e,c,"config:set:governance_create_default_type"),pe(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let i=x(e.settings,O()),a=ke(o,i);if(!a)throw new l(Rt(o,i.types,Ot(e.target.pmRoot,e.settings.schema)),d.USAGE);let s=e.settings.governance.create_default_type!==a;return e.settings.governance.create_default_type=a,await Q(e,s,"config:set:governance_create_default_type"),pe(e,t,e.settings.governance.create_default_type,s)}async function jA(e,t,n){if(t==="governance_ownership_enforcement"){let i=qh(n.policy),a=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==i;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=i,await Q(e,a,"config:set:governance_ownership_enforcement"),pe(e,t,e.settings.governance.ownership_enforcement,a)}if(t==="governance_create_mode_default"){let i=Kh(n.policy),a=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==i;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=i,await Q(e,a,"config:set:governance_create_mode_default"),pe(e,t,e.settings.governance.create_mode_default,a)}let r=zh(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Q(e,o,"config:set:governance_close_validation_default"),pe(e,t,e.settings.governance.close_validation_default,o)}async function qA(e,t,n){if(t==="governance_parent_reference_policy"){let i=gi(n.policy),a=e.settings.governance.preset!=="custom"||Mh(e.settings.governance.parent_reference,e.settings.validation.parent_reference,i);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,e.settings.validation.parent_reference=i,await Q(e,a,"config:set:governance_parent_reference_policy"),pe(e,t,e.settings.governance.parent_reference,a)}if(t==="governance_metadata_validation_profile"){let i=Gc(n.policy),a=e.settings.governance.preset!=="custom"||Mh(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,i);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=i,e.settings.validation.metadata_profile=i,await Q(e,a,"config:set:governance_metadata_validation_profile"),pe(e,t,e.settings.governance.metadata_profile,a)}let r=Hh(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Q(e,o,"config:set:governance_workflow_enforcement"),pe(e,t,e.settings.governance.workflow_enforcement,o)}async function KA(e,t,n){if(t==="governance_require_close_reason"){let i=Vh(n.policy)==="enabled",a=e.settings.governance.require_close_reason!==i;return e.settings.governance.require_close_reason=i,await Q(e,a,"config:set:governance_require_close_reason"),pe(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",a)}let r=Bh(n.policy)==="enabled",o=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==r;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=r,await Q(e,o,"config:set:governance_force_required_for_stale_lock"),pe(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function zA(e,t,n){if(t==="test_result_tracking"){let i=vA(n.policy)==="enabled",a=e.settings.testing.record_results_to_items!==i;return e.settings.testing.record_results_to_items=i,await Q(e,a,"config:set:test_result_tracking"),pe(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",a)}if(t==="untrusted_linked_test_execution"){let i=Uc(n.policy,"untrusted-linked-test-execution")==="enabled",a=e.settings.testing.allow_untrusted_linked_tests!==i;return e.settings.testing.allow_untrusted_linked_tests=i,await Q(e,a,"config:set:untrusted_linked_test_execution"),pe(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",a)}let r=Gh(n.policy)==="enabled",o=e.settings.telemetry.enabled!==r||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=r,e.settings.telemetry.first_run_prompt_completed=!0,await Q(e,o,"config:set:telemetry_tracking"),pe(e,t,e.settings.telemetry.enabled?"enabled":"disabled",o)}async function HA(e,t,n){let r=yA(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((i,a)=>i!==e.settings.workflow.definition_of_done[a]);return e.settings.workflow.definition_of_done=r,await Q(e,o,"config:set:definition_of_done"),Dc(e,t,[...e.settings.workflow.definition_of_done],o)}function BA(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",d.USAGE)}function VA(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',d.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",d.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",d.USAGE);return{}}async function WA(e,t){let{operation:n,dryRun:r}=BA(t.policy),o=VA(n,t.value),i;try{i=Ph(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(a){throw new l(a.message,d.USAGE)}return i.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:i.vocabulary},await Q(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${i.preview.version_after}`)),Re({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:Fc(r?e.settings.agent_identity?.identity_vocabulary:i.vocabulary),vocabulary_mutation:i.preview,settings_path:e.target.settingsPath,changed:i.preview.changed&&!r},e.warnings)}async function YA(e,t,n){if(n.clearCriteria===!0&&!Mc(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?MA(e,n):t==="context"?OA(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?WA(e,n):t==="definition_of_done"?HA(e,t,n):Dh(t)?UA(e,t,n):sA.has(t)?zA(e,t,n):cA.has(t)?KA(e,t,n):pA(t)?jA(e,t,n):uA(t)?qA(e,t,n):fA(t)?GA(e,t,n):DA(e,t,n)}async function Yh(e,t,n,r,o,i){let a=_A(e),s=hA(t),c=s==="get"||s==="set"?Bo(n):void 0,m=c?void 0:TA(s,n),p=PA(s,n,m,c,i,r),u=await IA(a,o),{settings:f,metadata:_,warnings:h}=await Gu(u.pmRoot),g={scope:a,target:u,settings:f,metadata:_,warnings:AA(h)};return c?FA(g,s,c,p):s==="list"?NA(g):s==="export"?LA(g):(Wh(m),s==="get"?$A(g,m):YA(g,m,p))}import Xh from"node:fs/promises";import Qh from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3603dce-8aeb-5409-80f4-ad3367e35eb9")}catch{}})();function JA(e,t,n){let r=new Set,o=[];for(let i of e){let a=i.trim();if(a.length===0||r.has(a))continue;r.add(a);let s=t.get(a);if(s===void 0){o.push({id:a,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(s.entries<=n){o.push({id:a,entries:s.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:a,entries:s.entries,selected:!0,skip_reason:null})}return o}function XA(e,t){let n=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function Jh(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return JA(t.ids,n,t.minEntries)}return XA(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6009e5f-840e-5e3a-b8b9-6e9d42d63410")}catch{}})();function QA(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(n)){let i=Number.parseInt(n,10),a=Mn(t);if(!Number.isSafeInteger(i)||i<a+1||i>a+t.length+1)throw new l(`history-compact --before version must be between ${a+1} and ${a+t.length+1}.`,d.USAGE);let s=i-a-1;return{kind:"version",raw:n,compactCount:s,retainedCount:t.length-s}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let o=0;for(let[i,a]of t.entries()){let s=Date.parse(a.ts);if(!Number.isFinite(s))throw new l(`History for this item contains invalid timestamp at entry ${i+1}.`,d.GENERIC_FAILURE);if(s>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function ZA(e,t){let n=ur(),r=ur();for(let o=0;o<e.length;o+=1){let i=e[o];n=Dn(n,i.patch,o+1,i.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function eT(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:Ru.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&Vs(_r(e.document),r,ut(n.hash_algorithm)).includes(n.after_hash))}}function tT(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function nT(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function rT(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=ZA(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Mn(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],a=$e({hashAlgorithm:ut(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:ot(ur()),after:ot(t),message:nT(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:Ou(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),s=[xu({...a,before_hash:Vs(ur(),i.item_hash_version??1,ut(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...r];return e.dryRun||s.push($e({nowIso:k(),author:e.author,op:"history_compact",before:ot(n),after:ot(n),message:tT(e.options,e.boundary)})),{rewrittenEntries:s,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function qc(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await kr(n.path),a=await tn(r,e,o,i.type_to_folder);return $i({pmRoot:r,subject:a,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:s=>oT(a,t,s)})}function oT(e,t,n){let r=e.historyPath,o=n.entries,i=n.verification;if(!i.ok)throw new l(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,d.CONFLICT);let a=QA(t.before,o),s=a.compactCount>0,c=!!t.dryRun,m=n.author,p=[];s||p.push("history_compact_noop_before_boundary");let u=eT(n.loadedItem,o);u.matchedChainBefore===!1&&p.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:_,auditEntryAdded:h}=rT({historyEntries:o,boundary:a,changed:s,dryRun:c,author:m,options:t}),g=Mn(o,!0),y=a.retainedCount>0&&g!==null?g+a.compactCount+1:null;return{changed:s,rewrittenEntries:f,report:({verification:w,warnings:b})=>({id:e.id,dry_run:c,changed:s,compact_boundary:{kind:a.kind,before:a.raw,entries_compacted:a.compactCount,entries_retained:a.retainedCount,first_retained_entry:y},history:{path:r,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:_,audit_entry_added:h,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:u.matchedChainBefore},warnings:[...new Set([...p,...b])].sort((S,T)=>S.localeCompare(T)),generated_at:k()})}}var iT=3;function aT(e){for(let n of["allOver","minEntries"]){let r=e[n];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new l(`history-compact ${n} must be a non-negative safe integer.`,d.USAGE)}let t=hi(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:_i(t)}}function Zh(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)==0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function sT(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function cT(e){let t=$(e.settings.schema),n=Si(t),r=await _e(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),i=Qh.join(e.pmRoot,"history"),a=[],s=[];if(!await q(i))return{candidates:a,preselectionErrors:s};let c=(await Xh.readdir(i)).filter(m=>m.endsWith(".jsonl")).sort((m,p)=>m.localeCompare(p));for(let m of c){let p=Qh.join(i,m),u=m.slice(0,-6);try{let f=await Xh.readFile(p,"utf8");await Rn({path:p,scope:"project"}),a.push({id:u,entries:sT(f),bucket:o.get(u)??null})}catch(f){s.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:a,preselectionErrors:s}}async function lT(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await qc(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function eg(e,t){let n=aT(e),{pmRoot:r,settings:o,typeRegistry:i}=await kr(t.path),{candidates:a,preselectionErrors:s}=await cT({pmRoot:r,settings:o,typeToFolder:i.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??iT,p=o.history.compact_policy,u=c==="scan"&&e.allOver===void 0&&p.enabled,f=e.allOver??(u?p.max_entries:void 0),_=Jh(a,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),h=!!e.dryRun,g=[...s],y={streams_considered:a.length+s.length,selected:0,items_compacted:0,items_skipped:0,items_errored:s.length};for(let w of _){let b=await lT({row:w,options:n,dryRun:h,global:t});if(g.push(b.result),!b.selected){y.items_skipped+=1;continue}y.selected+=1,b.compacted&&(y.items_compacted+=1),b.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:h,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:u},totals:y,results:g,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="feb8c44f-a6bd-5a7e-9600-eb5c45c0a5b4")}catch{}})();function tg(e){let t=e.options.all===!0,n=e.id??v(e.options,"id");return g_(n,t),t?Fi(e.options,e.global):Ut(n,e.options,e.global)}function ng(e){let t=e.options.ids,n=hi(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:_i(n),o=Me(e.options.allOver??e.options.all_over,"history-compact allOver"),i=Me(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),a=v(e.options,"scope"),s=[];e.options.closed===!0&&s.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&s.push("all-streams"),(a==="closed"||a==="all-streams")&&s.push(a);let c=[...new Set(s)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let m=c[0];return Zh(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?qc(e.id,{before:v(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:v(e.options,"author"),message:v(e.options,"message"),force:e.force},e.global):eg({ids:r,scope:m,allOver:o,minEntries:i,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:v(e.options,"author"),message:v(e.options,"message"),force:e.force},e.global)}import Kc from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebf3254f-1fed-5972-b91a-b8ff101675f4")}catch{}})();function rg(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function dT(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function mT(e){let t=e.trim();if(t.length===0)throw new l("history-redact --regex requires a non-empty pattern.",d.USAGE);let n=t,r="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(n=t.slice(1,o),r=dT(t.slice(o+1)))}if(n.length===0)throw new l("history-redact --regex cannot use an empty pattern.",d.USAGE);try{new RegExp(n,r)}catch{throw new l("Invalid --regex value; provide a valid JavaScript regular expression.",d.USAGE)}return{kind:"regex",source:n,flags:r}}function pT(e,t){let n=[...new Set(rg(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),r=[...new Set(rg(t).map(i=>i.trim()))].filter(i=>i.length>0).map(mT),o=[...n,...r];if(o.length===0)throw new l("history-redact requires at least one matcher via --literal or --regex.",d.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return o}function uT(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){let i=e.indexOf(t,r);if(i===-1)break;o+=1,r=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function fT(e,t,n){let r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function ig(e,t,n){let r=e,o=0;for(let i of t){let a=i.kind==="literal"?uT(r,i.value,n):fT(r,i,n);r=a.value,o+=a.replacements}return{value:r,replacements:o}}function Yi(e,t,n){if(typeof e=="string")return ig(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(o=>{let i=Yi(o,t,n);return r+=i.replacements,i.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,o={};for(let[i,a]of Object.entries(e)){let s=Yi(a,t,n);r+=s.replacements,o[i]=s.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function og(e,t,n){let r=0;return{patch:e.map(o=>{if(!Object.prototype.hasOwnProperty.call(o,"value"))return o;let i=Yi(o.value,t,n);return r+=i.replacements,i.replacements>0?{...o,value:i.value}:o}),replacements:r}}function _T(e){let t=structuredClone(Bs),n=0,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];fr(t,void 0,ut(i.hash_algorithm))!==i.before_hash&&(n+=1),t=Dn(t,i.patch,o+1,i.op),fr(t,void 0,ut(i.hash_algorithm))!==i.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function hT(e,t,n){let r=0,o=!1,i=!1,a=e.message;if(typeof e.message=="string"){let m=ig(e.message,t,n);a=m.value,r+=m.replacements,m.replacements>0&&(o=!0)}let s=og(e.patch,t,n);r+=s.replacements,o||=s.replacements>0;let c=e.reanchor_evidence?.map(m=>{let p=m.patch?og(m.patch,t,n):{patch:void 0,replacements:0},u=m.record?Yi(m.record,t,n):{value:void 0,replacements:0};r+=p.replacements,r+=u.replacements;let f=p.replacements>0||u.replacements>0;if(o||=f,!f)return m;i=!0;let{patch:_,record:h,record_hash:g,record_hash_version:y,...w}=m;return p.replacements>0?w:{...w,patch:m.patch}});return{entry:{...e,message:a,patch:s.patch,...c?{reanchor_evidence:c}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:i}}function gT(e,t,n){let r=structuredClone(Bs),o=0,i=0,a=[];for(let s=0;s<e.length;s+=1){let c=e[s],m=Pu(c);if(!m.ok)throw new l(`history-redact refuses invalid immutable record ${s+1} (${m.error}).`,d.GENERIC_FAILURE);let p=hT(c,t,n);i+=p.replacements,p.changed&&(o+=1);let u=fr(r,void 0,ut(c.hash_algorithm));r=Dn(r,p.entry.patch,s+1,p.entry.op);let f=fr(r,void 0,ut(c.hash_algorithm));a.push(Nu(c,{...p.entry,before_hash:u,after_hash:f},{retainPriorRecord:p.changed,retainPriorRecordHash:!p.changed}))}return{entries:a,finalDocument:r,entriesChanged:o,replacements:i}}function yT(e){return Object.keys(e.metadata).length>0}function wT(e){if(!yT(e.finalDocument))return{raw:null,path:null,document:null};let t=rt(ot(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new l("history-redact would change the item id; narrow your patterns.",d.USAGE);return{document:t,path:dt(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:Ve(t,{format:"toon",schema:e.settings.schema})}}function vT(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function bT(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??ot(e.rewritten.finalDocument);return t.push($e({nowIso:k(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function kT(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await $t(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let a=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await te(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await Kc.rm(e.currentItem.path,{force:!0}),await te(e.subject.historyPath,$u(e.rewrittenEntries))}catch(c){try{await ST(e.subject.historyPath,n,o,i)}finally{await Hs(e.subject.historyPath)}throw c}await Hs(e.subject.historyPath);let s=e.nextItem.path??e.currentItem.path;s&&(t=await Ft({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:s,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(s=>{a=()=>{throw s}})}a()},afterWrite:async()=>[...t,...await ET(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function ST(e,t,n,r){t===null?await Kc.rm(e,{force:!0}):await te(e,t);for(let o of n){let i=r.get(o);i===void 0?await Kc.rm(o,{force:!0}):await te(o,i)}}async function ET(e,t){let n=[],r=new Set(t.filter(o=>o!==null));for(let o of r)n.push(...await Y({path:o,scope:"project",op:"history_redact"}));return n.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),n}async function ag(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await kr(n.path),a=t.replacement??"",s=a.length===0,c=s?"[redacted]":a,m=pT(t.literal,t.regex),p=await tn(r,e,o,i.type_to_folder);return $i({pmRoot:r,subject:p,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>AT({pmRoot:r,subject:p,settings:o,typeRegistry:i,options:t,rules:m,replacement:c,replacementIsDefault:s},u)})}function AT(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:i,options:a,rules:s,replacement:c,replacementIsDefault:m}=e,p=t.entries,u=_T(p),f=gT(p,s,c),_=u.hashMismatchesBefore+u.hashMismatchesAfter,h=!!a.dryRun,g=f.replacements>0,y=[];_>0&&y.push(`history_redact_preexisting_hash_mismatches:${_}`),g||y.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},b=wT({pmRoot:n,subject:r,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),S=(w.path??null)!==(b.path??null)||(w.raw??null)!==(b.raw??null),T=t.author,L=vT(a,f),{rewrittenEntries:P,auditEntryAdded:M}=bT({rewritten:f,dryRun:h,changed:g,nextItemDocument:b.document,author:T,message:L});return{changed:g,rewrittenEntries:P,...kT({pmRoot:n,subject:r,settings:o,typeRegistry:i,currentItem:w,nextItem:b,author:T,rewrittenEntries:P}),report:({verification:K,warnings:H})=>({id:r.id,dry_run:h,changed:g,patterns:{literal_count:s.filter(Z=>Z.kind==="literal").length,regex_count:s.filter(Z=>Z.kind==="regex").length,total_count:s.length,replacement_is_default:m},history:{path:r.historyPath,entries_scanned:p.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:_,audit_entry_added:M,verify_ok:K.ok,verify_errors:K.errors},item:{existed_before:w.path!==null,exists_after:b.path!==null,path_before:w.path,path_after:b.path,changed:S},warnings:[...new Set([...y,...H])].sort((Z,le)=>Z.localeCompare(le)),generated_at:k()})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7317758-33fb-52ee-a94b-1b97c4920773")}catch{}})();async function sg(e,t,n){return Bn(e,t,n,{input:await Wi(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Hn(r),createEntry:r=>r,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm learnings --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5bdc2e7-1633-5bc8-97c7-8f6ecd253294")}catch{}})();async function cg(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=Nt(),o=E(process.cwd(),n.path);await I(o);let i=await A(o),a=C(t.author,i.author_default),s=(await r.resolveValue(t.body,"--body",Ku(t,"body"))).trim();if(s.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",d.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let c=await se({pmRoot:o,settings:i,id:e,op:"append",author:a,message:t.message,force:t.force,mutate(m){let p=m.body.trim().length>0?`
15
+ `),Ue.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
16
+ `);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),p=PE(m,t);return Ue.write(`
17
+ `),{prefix:o,preset:s,telemetry_enabled:p}}finally{n.close()}}function UE(e){return{presetFromOption:Ph(e.preset),useDefaults:e.defaults===!0,authorFromOption:IE(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:xE(e.agentGuidance),typePreset:CE(e.typePreset)}}function GE(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function jE(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function qE(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(Nh(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function KE(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=GE({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return jE(e.settingsPath,n,e.options.force===!0,e.target),qE({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Me(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function zE(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await DE(t,Ct.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let i=n??"minimal",a=AE();a.id_prefix=t,Nh(a,i);let s=oi()?.trim()||void 0;return a.author_default=e.normalizedOptions.authorFromOption??s??"",r!==void 0&&(a.telemetry.enabled=r,a.telemetry.first_run_prompt_completed=!0),await Me(e.pmRoot,a),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function xh(e){return e.settingsExists?await KE(e):await zE({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function HE(e){let t=await Zf({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await Me(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function BE(e,t){let n=[],r=[],o=await Gp(e,t.schema);for(let i of o.created_paths)n.push(i),r.push(...await Y({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function VE(e){if(e.typePreset===void 0)return;let t=await $E(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await Y({path:t.file,scope:"project",op:"init:type_preset"})),t}async function WE(e){let t=x(e.settings,R()).folders.filter(r=>!Ss.includes(r)),n=await Lh(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function YE(e){let t=Q.resolve(e.tracker_root),n=Q.dirname(t);return Q.basename(t)==="pm"&&Q.basename(n)===".agents"?Q.dirname(n):e.workspace_root}async function JE(e,t,n,r){if(!e)return;let o=await Un("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let i=LE(o),a=i.packages.filter(s=>!s.ok).map(s=>s.alias);if(!i.installed_all||a.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,d.GENERIC_FAILURE);return i}function XE(e){let t=r=>Te([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function QE(e,t,n,r=Nf){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function ZE(e,t,n,r){if(e==null||n==="status")return;let o=await dc(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Nr(e,t,n={}){let r=t[Dc],o=typeof r=="string"?r:process.cwd(),i=RE(o,t,e,n.workspace),a=i.pmRoot;e=OE(i.prefixArg,n.idPrefix);let s=UE(n);await ME(a,i.target.mode==="tracker-path",n.force===!0);let c=[],m=[],p=Q.join(a,"settings.json"),u=await j(p),f;u&&(f=await xh({pmRoot:a,settingsPath:p,settingsExists:u,normalizedPrefix:Ft(e),prefixArg:e,options:n,normalizedOptions:s,warnings:m,target:i.target}));let _=await Lh(a,Ss);c.push(..._.createdDirs),m.push(..._.warnings),f??=await xh({pmRoot:a,settingsPath:p,settingsExists:u,normalizedPrefix:Ft(e),prefixArg:e,options:n,normalizedOptions:s,warnings:m,target:i.target});let{settings:h}=f,g=YE(i.target),y=await Ii(g??Q.dirname(a)),w=g??y,b=await HE({pmRoot:a,cwd:w??o,agentGuidanceMode:s.agentGuidanceMode,settings:h,warnings:m}),S=await BE(a,h);c.push(...S.createdDirs),m.push(...S.warnings);let T=await VE({pmRoot:a,settings:h,typePreset:s.typePreset,warnings:m});T&&(h=await A(a)),await WE({pmRoot:a,settings:h,createdDirs:c,warnings:m}),await ZE(w,a,s.agentGuidanceMode,m),!u&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await QE(a,y,m);let $=await JE(s.installBundledPackages,t,a,m),P=XE({installBundledPackages:s.installBundledPackages,registeredTypePreset:T,agentGuidanceNextSteps:b.next_steps,target:i.target});return{ok:!0,path:a,target:i.target,settings:h,created_dirs:c,warnings:m,governance_preset:h.governance.preset,wizard_used:f.wizardUsed,...T?{registered_type_preset:T}:{},...$?{installed_packages:$}:{},next_steps:P,agent_guidance:b}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08ad3dd1-a1ec-5ee8-9f0f-1350dd91f25e")}catch{}})();async function $h(e,t){let n=E(t??process.cwd(),e),r=await A(n);return _e(n,r.item_format,x(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="247354d6-fccb-58f8-b969-b1952abf181e")}catch{}})();var eA={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function Fh(e){return Object.fromEntries(hm.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Mh={ctx:{action:"context"},...eA,...Fh("extension"),...Fh("package"),...Object.fromEntries(gm.map(e=>[`package-${e}`,{action:e}]))};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="baa27a48-c538-574c-9d05-1f1c0f4f429c")}catch{}})();function Dh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tA(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function Uc(e,t){let n=tA(t),r=n==="brief"?n:Dh(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:Dh(e.filters)?e.filters:{},projection:r}}}import{readFile as nA}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35773218-9c35-51d9-a19b-e9094bd23b66")}catch{}})();function Xi(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Oe(e,t)}function Uh(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,d.USAGE,{code:"structured_event_immutable"})}function Gc(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function rn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function zn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let o=pe(n,"--add");return Object.keys(o).map(i=>i.trim().toLowerCase()).some(i=>i!=="text")?n:o.text?.trim()||n}catch{return n}}function jc(e){return typeof e=="object"&&e!==null&&"code"in e}function $r(e,t){if(!ht(e))throw new l(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,d.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function rA(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,d.USAGE);let n=$t(),r=ht(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return $r(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let o=e.file.trim();if(!o)throw new l("--file path cannot be empty",d.USAGE);if(o==="-")return $r(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await nA(o,"utf8"),emptyFlag:"--file"}}catch(i){if(jc(i)&&Wt(i))throw new l(`--file path not found: ${o}. Use --file - to read stdin.`,d.USAGE);let a=i instanceof Error?i.message:String(i);throw new l(`Failed to read --file path "${o}": ${a}. Use --file - to read stdin.`,d.USAGE)}}async function Qi(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",d.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",d.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",d.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",d.USAGE);let n=await rA(e,t);if(e.edit!==void 0){if(!n)throw new l("--edit requires replacement text from --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function Lr(e,t){throw e instanceof l&&e.exitCode===d.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function jh(e){return e==="comments"?"--stdin":"--add -"}function oA(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let n=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(n))return;let r=jh(t.collectionKey),o=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new l(`--add value "${n}" looks like an option, not annotation text. Use ${r} to read stdin, or use text=${n} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${r} for stdin input, pass plain text, or use text=${n} when the text really starts with "-".`,examples:[`${o} ${r}`,`${o} --add text=${n}`]})}function iA(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new l(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,d.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,d.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${jh(e.collectionKey)}`]})}function aA(e,t,n,r,o,i){let a=rn(e.metadata,t),s=o?a.findIndex(c=>c.author===n&&c.text===r):-1;return s>=0?{changedFields:[],entryIndex:s+1}:(a.push(i({created_at:k(),author:n,text:r})),e.metadata[t]=a,{changedFields:[t],entryIndex:a.length})}async function Hn(e,t,n,r){iA(r,t);let o=E(process.cwd(),n.path);await I(o);let i=await A(o),a=x(i,R()),s=yr(t.limit);if(r.input.mode==="list"){let h=await z(o,e,i.id_prefix,i.item_format,a.type_to_folder);if(!h)throw new l(`Item ${e} not found`,d.NOT_FOUND);let g=await ce(h,{schema:i.schema}),y=rn(g.document.metadata,r.collectionKey);return Ji(h.id,r.collectionKey,y,s,t.includeMeta===!0)}let c=C(t.author,i.author_default);if(r.input.mode==="delete"){let h=r.deleteOp??r.op,g;try{g=await le({pmRoot:o,settings:i,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=rn(w.metadata,r.collectionKey),S=Gh(r.input.index,b.length,r.collectionKey);return Uh(b[S],"deleted"),b.splice(S,1),w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){Lr(w,r.conflictGuidance)}let y=rn(g.item,r.collectionKey);return Ji(g.item.id,r.collectionKey,y,s,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";oA(m,r);let p=r.parseText(r.input.value??"");if(!p.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,d.USAGE);if(r.input.mode==="edit"){let h=r.editOp??r.op,g;try{g=await le({pmRoot:o,settings:i,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=rn(w.metadata,r.collectionKey),S=Gh(r.input.index,b.length,r.collectionKey),T=b[S];return Uh(T,"edited"),b[S]={...T,text:p,edited_at:k()},w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){Lr(w,r.conflictGuidance)}let y=rn(g.item,r.collectionKey);return Ji(g.item.id,r.collectionKey,y,s,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:y[r.input.index-1]},t.fullHistory===!0)}let u,f=0;try{u=await le({pmRoot:o,settings:i,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(h){let g=aA(h,r.collectionKey,c,p,t.ifAbsent===!0,r.createEntry);return f=g.entryIndex,{changedFields:g.changedFields}}})}catch(h){Lr(h,r.conflictGuidance)}let _=rn(u.item,r.collectionKey);return Ji(u.item.id,r.collectionKey,_,s,t.includeMeta===!0,{action:"add",entryIndex:f,entry:_[f-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Gh(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,i=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${o} index ${e??"(missing)"} out of range (item has ${i})`,d.USAGE)}return e-1}function sA(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function Ji(e,t,n,r,o,i,a=!1){let s=i===void 0||a?Gc(n,i!==void 0&&a?void 0:r):i.entry===void 0?[]:[i.entry],c=i!==void 0&&s.length<n.length;return{id:e,[t]:s,count:s.length,...i?.changedCount===void 0?{}:{changed:i.changedCount===1},...[o,i!==void 0].includes(!0)?{total_count:n.length,returned_count:s.length,has_more:c||s.length<n.length,...r!==void 0?{limit:r}:{}}:{},...sA(t,i,c)}}import{readFile as cA}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8513dce5-85a0-56aa-bb8f-c64756ac4b2e")}catch{}})();async function qc(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",i=Number(n)+Number(r)+Number(o);if(i===0)return;if(i>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",d.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",ht(e))??"",emptyFlag:"--add"};if(r)return $r(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let a=e.file.trim();if(!a)throw new l("--file path cannot be empty",d.USAGE);if(a==="-")return $r(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await cA(a,"utf8"),emptyFlag:"--file"}}catch(s){if(jc(s)&&Wt(s))throw new l(`--file path not found: ${a}. Use --file - to read stdin.`,d.USAGE);let c=s instanceof Error?s.message:String(s);throw new l(`Failed to read --file path "${a}": ${c}. Use --file - to read stdin.`,d.USAGE)}}async function lA(e,t){let n=e.edit,r=e.delete,o=n!==void 0,i=r!==void 0;if(o&&i)throw new l("Specify only one of --edit or --delete",d.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",d.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",d.USAGE);if(i){if(await qc(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(o){let s=await qc(e,t);if(s===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:n,value:s.value,emptyFlag:s.emptyFlag}}let a=await qc(e,t);return a===void 0?{mode:"list"}:{mode:a.emptyFlag==="--add"?"add":a.emptyFlag==="--stdin"?"stdin":"file",value:a.value,emptyFlag:a.emptyFlag}}async function qh(e,t,n){let r=$t(),o=await lA(t,r),i=o.mode==="add"||o.mode==="edit",a=o.value??"";return Hn(e,t,n,{input:{...o,rawValue:t.add??a,value:i?zn(a,{stripPlainTextPrefix:!0}):a},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:s=>s,createEntry:s=>s,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm comments --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78e92b9c-f3da-594e-8158-00409222308f")}catch{}})();var Kh=new Set(["item_format"]),zh=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),dA=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),mA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),pA={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function uA(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(Kh.has(t)||zh.has(t)||dA.has(t)||t==="context")return t}function fA(e){let t=e.trim().toLowerCase();return pA[t]??e}function Hh(e,t){let n=uA(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:Kh.has(n)?{routable:!0,flag:"format",value:t}:zh.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:mA.has(n)?fA(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="544840da-22f5-5734-81ec-e12c5612545c")}catch{}})();var _A=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Bh(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>128)throw new Error("A legacy author must contain 1-128 characters.");return t}function hA(e){let t=e?.trim().toLowerCase();if(!t||!_A.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function gA(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function yA(e,t){let n=new Set;for(let r of(e??[]).slice(0,1e4)){let o=r.trim().slice(0,128);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function wA(e,t){let n=Bh(t.legacy_author),r=hA(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function vA(e,t){if(t.operation==="add")return wA(e,t);if(t.operation==="remove"){let r=Bh(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function Kc(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function Vh(e,t){let n=e?.version??1,r={...e?.aliases},o=vA(r,t),i={version:o?n+1:n,aliases:gA(r)};return{vocabulary:i,preview:{operation:t.operation,changed:o,version_before:n,version_after:i.version,alias_count:Object.keys(i.aliases).length,residual_author_count:yA(t.observed_authors,i.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d9b6f2ba-2c5e-52ea-891d-53124601fb89")}catch{}})();var Wh=["project","global"],bt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},bA=Object.keys(bt).map(e=>bt[e][0]),kA=Object.fromEntries(Object.keys(bt).flatMap(e=>bt[e].map(t=>[t,e]))),SA={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},EA=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],AA=new Set(["metadata_required_fields",...EA]),TA=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),CA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),IA=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),RA=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),OA=new Set(["governance_preset","governance_create_default_type"]),Zh=e=>AA.has(e),xA=e=>IA.has(e),PA=e=>RA.has(e),NA=e=>OA.has(e);function zc(e){return e==="definition_of_done"||Zh(e)}function LA(e){if(Wh.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${Wh.join(", ")}`,d.USAGE)}function $A(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Re({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function FA(e){let t=kA[e];if(t)return t;let n=$s.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${bA.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function MA(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",d.USAGE);return n}function DA(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",d.USAGE):new l("Config set item-format requires --format toon",d.USAGE)}function eg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",d.USAGE)}function UA(e){return Bc(e,"test-result-tracking")}function Bc(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,d.USAGE)}function tg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function Vc(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",d.USAGE)}function ng(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",d.USAGE)}function rg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",d.USAGE)}function og(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",d.USAGE)}function ig(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",d.USAGE)}function ag(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-workflow-enforcement requires one of: off, warn, strict",d.USAGE)}function sg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",d.USAGE)}function cg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",d.USAGE)}var GA={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function Yh(e,t){let n=GA[e];if(n)return Bc(t,n);switch(e){case"history_missing_stream_policy":return eg(t);case"sprint_release_format_policy":return ac(t);case"parent_reference_policy":case"governance_parent_reference_policy":return gi(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Vc(t);case"governance_preset":return ng(t);case"governance_ownership_enforcement":return rg(t);case"governance_create_mode_default":return og(t);case"governance_close_validation_default":return ig(t);case"governance_require_close_reason":return cg(t);case"governance_workflow_enforcement":return ag(t);case"governance_force_required_for_stale_lock":return sg(t);case"telemetry_tracking":return tg(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var Jh={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},jA=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function qA(e,t){let n=[...new Set((e??[]).map(i=>i.trim()).filter(i=>i.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",d.USAGE);let r=n.map(i=>i.toLowerCase().replaceAll("-","_")),o=r.filter(i=>Jh[i]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${jA.join(", ")}`,d.USAGE);return[...new Set(r.map(i=>Jh[i]))].sort((i,a)=>i.localeCompare(a))}function KA(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));if(n){if(r.length>0)throw new l(`Config set ${bt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${bt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function zA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function HA(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,d.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,d.USAGE);return FA(t)}function lg(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var BA={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>Kc(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function Wc(e,t){return BA[t](e)}function xe(e,t){return t.length===0?e:{...e,warnings:t}}async function VA(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):mt(n),o=ne(r);return e==="project"&&await I(r),{pmRoot:r,settingsPath:o}}function WA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,d.USAGE)}function Xh(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new l(`Context ${t} must be a positive integer`,d.USAGE)}async function YA(e,t,n,r,o){let i=!1,a=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!ks.includes(c))throw new l(`Context --default-depth must be one of ${ks.join("|")}`,d.USAGE);a.default_depth!==c&&(a.default_depth=c,i=!0)}if(t.activityLimit!==void 0){let c=Xh(t.activityLimit,"--activity-limit");a.activity_limit!==c&&(a.activity_limit=c,i=!0)}if(t.staleThresholdDays!==void 0){let c=Xh(t.staleThresholdDays,"--stale-threshold-days");a.stale_threshold_days!==c&&(a.stale_threshold_days=c,i=!0)}let s=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of s){let p=WA(m);if(p!==void 0){let u=c;a.sections[u]!==p&&(a.sections[u]=p,i=!0)}}return i&&await Me(n.pmRoot,e,"config:set:context"),xe({scope:r,key:"context",context_settings:{default_depth:a.default_depth,activity_limit:a.activity_limit,stale_threshold_days:a.stale_threshold_days,sections:{...a.sections}},settings_path:n.settingsPath,changed:i},o)}function JA(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,d.USAGE);return{...n,value:t}}function XA(e,t,n,r,o,i){if(o===void 0)return i;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,d.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',d.USAGE);if(r)return JA(t,o,i);lg(n);let a=Hh(n,o);if(!a.routable)throw new l(a.reason,d.USAGE);if(a.flag==="criterion"){if(i.criterion!==void 0&&i.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...i,criterion:a.values}}if(a.flag==="format")return{...i,format:a.value};if(i.policy!==void 0&&Yh(n,i.policy)!==Yh(n,a.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${i.policy}". Pass only one.`,d.USAGE);return{...i,policy:a.value}}function QA(e){let t=Object.keys(bt).map(r=>({key:r,aliases:bt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":zc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:zc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:SA[r],value:Wc(e.settings,r)})),n=$s.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Fs(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return xe({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function ZA(e){let t=Object.fromEntries(Object.keys(bt).map(n=>[n,Wc(e.settings,n)]));return xe({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function eT(e,t){let n=Wc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?xe({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?xe({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?xe({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?xe({...r,criteria:n},e.warnings):xe({...r,policy:n},e.warnings)}async function tT(e,t,n,r){if(t==="get"){let s=Fs(e.settings,n);return xe({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:s},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let i=Hp(n,o);if(!i.ok)throw new l(i.error.message,d.USAGE);let a=Wo(e.settings,n,i.parsed.value);return a&&await Me(e.target.pmRoot,e.settings,`config:set:${n.path}`),xe({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:i.parsed.value},settings_path:e.target.settingsPath,changed:a},e.warnings)}async function Z(e,t,n){t&&await Me(e.target.pmRoot,e.settings,n)}function Qh(e,t,n){return e!==n||t!==n}function ue(e,t,n,r){return xe({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Hc(e,t,n,r){return xe({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function nT(e,t){let n=DA(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let i=x(e.settings,R()),a=await hf(e.target.pmRoot,n,"config:set:item_format:migrate",i.type_to_folder,e.settings.schema);o={target_format:a.target_format,scanned:a.scanned,migrated:a.migrated,removed:a.removed,warnings:a.warnings},e.settings.item_format=n,await Me(e.target.pmRoot,e.settings,"config:set:item_format")}return xe({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function rT(e,t,n){if(t==="history_missing_stream_policy"){let i=eg(n.policy),a=e.settings.history.missing_stream!==i;return e.settings.history.missing_stream=i,await Z(e,a,"config:set:history_missing_stream_policy"),ue(e,t,e.settings.history.missing_stream,a)}if(t==="sprint_release_format_policy"){let i=ac(n.policy),a=e.settings.validation.sprint_release_format!==i;return e.settings.validation.sprint_release_format=i,await Z(e,a,"config:set:sprint_release_format_policy"),ue(e,t,e.settings.validation.sprint_release_format,a)}if(t==="parent_reference_policy"){let i=gi(n.policy),a=e.settings.validation.parent_reference!==i||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==i;return e.settings.validation.parent_reference=i,e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,await Z(e,a,"config:set:parent_reference_policy"),ue(e,t,e.settings.validation.parent_reference,a)}let r=Vc(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Z(e,o,"config:set:metadata_validation_profile"),ue(e,t,e.settings.validation.metadata_profile,o)}async function oT(e,t,n){if(t==="metadata_required_fields"){let a=qA(n.criterion,n.clearCriteria),s=a.length!==e.settings.validation.metadata_required_fields.length||a.some((c,m)=>c!==e.settings.validation.metadata_required_fields[m]);return e.settings.validation.metadata_required_fields=a,await Z(e,s,"config:set:metadata_required_fields"),Hc(e,t,[...e.settings.validation.metadata_required_fields],s)}let r={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],o=KA(t,n.criterion,n.clearCriteria),i=o.length!==r.length||o.some((a,s)=>a!==r[s]);return r.splice(0,r.length,...o),await Z(e,i,`config:set:${t}`),Hc(e,t,[...r],i)}async function iT(e,t,n){if(t==="governance_preset"){let c=ng(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Z(e,m,"config:set:governance_preset"),ue(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Z(e,c,"config:set:governance_create_default_type"),ue(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let i=x(e.settings,R()),a=ke(o,i);if(!a)throw new l(xt(o,i.types,Pt(e.target.pmRoot,e.settings.schema)),d.USAGE);let s=e.settings.governance.create_default_type!==a;return e.settings.governance.create_default_type=a,await Z(e,s,"config:set:governance_create_default_type"),ue(e,t,e.settings.governance.create_default_type,s)}async function aT(e,t,n){if(t==="governance_ownership_enforcement"){let i=rg(n.policy),a=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==i;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=i,await Z(e,a,"config:set:governance_ownership_enforcement"),ue(e,t,e.settings.governance.ownership_enforcement,a)}if(t==="governance_create_mode_default"){let i=og(n.policy),a=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==i;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=i,await Z(e,a,"config:set:governance_create_mode_default"),ue(e,t,e.settings.governance.create_mode_default,a)}let r=ig(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Z(e,o,"config:set:governance_close_validation_default"),ue(e,t,e.settings.governance.close_validation_default,o)}async function sT(e,t,n){if(t==="governance_parent_reference_policy"){let i=gi(n.policy),a=e.settings.governance.preset!=="custom"||Qh(e.settings.governance.parent_reference,e.settings.validation.parent_reference,i);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,e.settings.validation.parent_reference=i,await Z(e,a,"config:set:governance_parent_reference_policy"),ue(e,t,e.settings.governance.parent_reference,a)}if(t==="governance_metadata_validation_profile"){let i=Vc(n.policy),a=e.settings.governance.preset!=="custom"||Qh(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,i);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=i,e.settings.validation.metadata_profile=i,await Z(e,a,"config:set:governance_metadata_validation_profile"),ue(e,t,e.settings.governance.metadata_profile,a)}let r=ag(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Z(e,o,"config:set:governance_workflow_enforcement"),ue(e,t,e.settings.governance.workflow_enforcement,o)}async function cT(e,t,n){if(t==="governance_require_close_reason"){let i=cg(n.policy)==="enabled",a=e.settings.governance.require_close_reason!==i;return e.settings.governance.require_close_reason=i,await Z(e,a,"config:set:governance_require_close_reason"),ue(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",a)}let r=sg(n.policy)==="enabled",o=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==r;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=r,await Z(e,o,"config:set:governance_force_required_for_stale_lock"),ue(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function lT(e,t,n){if(t==="test_result_tracking"){let i=UA(n.policy)==="enabled",a=e.settings.testing.record_results_to_items!==i;return e.settings.testing.record_results_to_items=i,await Z(e,a,"config:set:test_result_tracking"),ue(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",a)}if(t==="untrusted_linked_test_execution"){let i=Bc(n.policy,"untrusted-linked-test-execution")==="enabled",a=e.settings.testing.allow_untrusted_linked_tests!==i;return e.settings.testing.allow_untrusted_linked_tests=i,await Z(e,a,"config:set:untrusted_linked_test_execution"),ue(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",a)}let r=tg(n.policy)==="enabled",o=e.settings.telemetry.enabled!==r||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=r,e.settings.telemetry.first_run_prompt_completed=!0,await Z(e,o,"config:set:telemetry_tracking"),ue(e,t,e.settings.telemetry.enabled?"enabled":"disabled",o)}async function dT(e,t,n){let r=MA(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((i,a)=>i!==e.settings.workflow.definition_of_done[a]);return e.settings.workflow.definition_of_done=r,await Z(e,o,"config:set:definition_of_done"),Hc(e,t,[...e.settings.workflow.definition_of_done],o)}function mT(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",d.USAGE)}function pT(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',d.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",d.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",d.USAGE);return{}}async function uT(e,t){let{operation:n,dryRun:r}=mT(t.policy),o=pT(n,t.value),i;try{i=Vh(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(a){throw new l(a.message,d.USAGE)}return i.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:i.vocabulary},await Z(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${i.preview.version_after}`)),xe({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:Kc(r?e.settings.agent_identity?.identity_vocabulary:i.vocabulary),vocabulary_mutation:i.preview,settings_path:e.target.settingsPath,changed:i.preview.changed&&!r},e.warnings)}async function fT(e,t,n){if(n.clearCriteria===!0&&!zc(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?nT(e,n):t==="context"?YA(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?uT(e,n):t==="definition_of_done"?dT(e,t,n):Zh(t)?oT(e,t,n):TA.has(t)?lT(e,t,n):CA.has(t)?cT(e,t,n):xA(t)?aT(e,t,n):PA(t)?sT(e,t,n):NA(t)?iT(e,t,n):rT(e,t,n)}async function dg(e,t,n,r,o,i){let a=LA(e),s=$A(t),c=s==="get"||s==="set"?Vo(n):void 0,m=c?void 0:HA(s,n),p=XA(s,n,m,c,i,r),u=await VA(a,o),{settings:f,metadata:_,warnings:h}=await Qu(u.pmRoot),g={scope:a,target:u,settings:f,metadata:_,warnings:zA(h)};return c?tT(g,s,c,p):s==="list"?QA(g):s==="export"?ZA(g):(lg(m),s==="get"?eT(g,m):fT(g,m,p))}import pg from"node:fs/promises";import ug from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3603dce-8aeb-5409-80f4-ad3367e35eb9")}catch{}})();function _T(e,t,n){let r=new Set,o=[];for(let i of e){let a=i.trim();if(a.length===0||r.has(a))continue;r.add(a);let s=t.get(a);if(s===void 0){o.push({id:a,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(s.entries<=n){o.push({id:a,entries:s.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:a,entries:s.entries,selected:!0,skip_reason:null})}return o}function hT(e,t){let n=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function mg(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return _T(t.ids,n,t.minEntries)}return hT(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6009e5f-840e-5e3a-b8b9-6e9d42d63410")}catch{}})();function gT(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(n)){let i=Number.parseInt(n,10),a=Fn(t);if(!Number.isSafeInteger(i)||i<a+1||i>a+t.length+1)throw new l(`history-compact --before version must be between ${a+1} and ${a+t.length+1}.`,d.USAGE);let s=i-a-1;return{kind:"version",raw:n,compactCount:s,retainedCount:t.length-s}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let o=0;for(let[i,a]of t.entries()){let s=Date.parse(a.ts);if(!Number.isFinite(s))throw new l(`History for this item contains invalid timestamp at entry ${i+1}.`,d.GENERIC_FAILURE);if(s>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function yT(e,t){let n=fr(),r=fr();for(let o=0;o<e.length;o+=1){let i=e[o];n=Mn(n,i.patch,o+1,i.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function wT(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:ju.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&ec(hr(e.document),r,_t(n.hash_algorithm)).includes(n.after_hash))}}function vT(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function bT(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function kT(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=yT(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Fn(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],a=Fe({hashAlgorithm:_t(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:at(fr()),after:at(t),message:bT(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:qu(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),s=[Ku({...a,before_hash:ec(fr(),i.item_hash_version??1,_t(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...r];return e.dryRun||s.push(Fe({nowIso:k(),author:e.author,op:"history_compact",before:at(n),after:at(n),message:vT(e.options,e.boundary)})),{rewrittenEntries:s,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Yc(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await Sr(n.path),a=await en(r,e,o,i.type_to_folder);return Fi({pmRoot:r,subject:a,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:s=>ST(a,t,s)})}function ST(e,t,n){let r=e.historyPath,o=n.entries,i=n.verification;if(!i.ok)throw new l(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,d.CONFLICT);let a=gT(t.before,o),s=a.compactCount>0,c=!!t.dryRun,m=n.author,p=[];s||p.push("history_compact_noop_before_boundary");let u=wT(n.loadedItem,o);u.matchedChainBefore===!1&&p.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:_,auditEntryAdded:h}=kT({historyEntries:o,boundary:a,changed:s,dryRun:c,author:m,options:t}),g=Fn(o,!0),y=a.retainedCount>0&&g!==null?g+a.compactCount+1:null;return{changed:s,rewrittenEntries:f,report:({verification:w,warnings:b})=>({id:e.id,dry_run:c,changed:s,compact_boundary:{kind:a.kind,before:a.raw,entries_compacted:a.compactCount,entries_retained:a.retainedCount,first_retained_entry:y},history:{path:r,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:_,audit_entry_added:h,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:u.matchedChainBefore},warnings:[...new Set([...p,...b])].sort((S,T)=>S.localeCompare(T)),generated_at:k()})}}var ET=3;function AT(e){for(let n of["allOver","minEntries"]){let r=e[n];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new l(`history-compact ${n} must be a non-negative safe integer.`,d.USAGE)}let t=hi(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:_i(t)}}function fg(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)==0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function TT(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function CT(e){let t=F(e.settings.schema),n=Ei(t),r=await _e(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),i=ug.join(e.pmRoot,"history"),a=[],s=[];if(!await j(i))return{candidates:a,preselectionErrors:s};let c=(await pg.readdir(i)).filter(m=>m.endsWith(".jsonl")).sort((m,p)=>m.localeCompare(p));for(let m of c){let p=ug.join(i,m),u=m.slice(0,-6);try{let f=await pg.readFile(p,"utf8");await In({path:p,scope:"project"}),a.push({id:u,entries:TT(f),bucket:o.get(u)??null})}catch(f){s.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:a,preselectionErrors:s}}async function IT(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await Yc(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function _g(e,t){let n=AT(e),{pmRoot:r,settings:o,typeRegistry:i}=await Sr(t.path),{candidates:a,preselectionErrors:s}=await CT({pmRoot:r,settings:o,typeToFolder:i.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??ET,p=o.history.compact_policy,u=c==="scan"&&e.allOver===void 0&&p.enabled,f=e.allOver??(u?p.max_entries:void 0),_=mg(a,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),h=!!e.dryRun,g=[...s],y={streams_considered:a.length+s.length,selected:0,items_compacted:0,items_skipped:0,items_errored:s.length};for(let w of _){let b=await IT({row:w,options:n,dryRun:h,global:t});if(g.push(b.result),!b.selected){y.items_skipped+=1;continue}y.selected+=1,b.compacted&&(y.items_compacted+=1),b.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:h,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:u},totals:y,results:g,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="feb8c44f-a6bd-5a7e-9600-eb5c45c0a5b4")}catch{}})();function hg(e){let t=e.options.all===!0,n=e.id??v(e.options,"id");return O_(n,t),t?Mi(e.options,e.global):Gt(n,e.options,e.global)}function gg(e){let t=e.options.ids,n=hi(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:_i(n),o=De(e.options.allOver??e.options.all_over,"history-compact allOver"),i=De(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),a=v(e.options,"scope"),s=[];e.options.closed===!0&&s.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&s.push("all-streams"),(a==="closed"||a==="all-streams")&&s.push(a);let c=[...new Set(s)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let m=c[0];return fg(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?Yc(e.id,{before:v(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:v(e.options,"author"),message:v(e.options,"message"),force:e.force},e.global):_g({ids:r,scope:m,allOver:o,minEntries:i,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:v(e.options,"author"),message:v(e.options,"message"),force:e.force},e.global)}import Jc from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebf3254f-1fed-5972-b91a-b8ff101675f4")}catch{}})();function yg(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function RT(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function OT(e){let t=e.trim();if(t.length===0)throw new l("history-redact --regex requires a non-empty pattern.",d.USAGE);let n=t,r="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(n=t.slice(1,o),r=RT(t.slice(o+1)))}if(n.length===0)throw new l("history-redact --regex cannot use an empty pattern.",d.USAGE);try{new RegExp(n,r)}catch{throw new l("Invalid --regex value; provide a valid JavaScript regular expression.",d.USAGE)}return{kind:"regex",source:n,flags:r}}function xT(e,t){let n=[...new Set(yg(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),r=[...new Set(yg(t).map(i=>i.trim()))].filter(i=>i.length>0).map(OT),o=[...n,...r];if(o.length===0)throw new l("history-redact requires at least one matcher via --literal or --regex.",d.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return o}function PT(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){let i=e.indexOf(t,r);if(i===-1)break;o+=1,r=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function NT(e,t,n){let r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function vg(e,t,n){let r=e,o=0;for(let i of t){let a=i.kind==="literal"?PT(r,i.value,n):NT(r,i,n);r=a.value,o+=a.replacements}return{value:r,replacements:o}}function Zi(e,t,n){if(typeof e=="string")return vg(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(o=>{let i=Zi(o,t,n);return r+=i.replacements,i.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,o={};for(let[i,a]of Object.entries(e)){let s=Zi(a,t,n);r+=s.replacements,o[i]=s.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function wg(e,t,n){let r=0;return{patch:e.map(o=>{if(!Object.prototype.hasOwnProperty.call(o,"value"))return o;let i=Zi(o.value,t,n);return r+=i.replacements,i.replacements>0?{...o,value:i.value}:o}),replacements:r}}function LT(e){let t=structuredClone(Zs),n=0,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];_r(t,void 0,_t(i.hash_algorithm))!==i.before_hash&&(n+=1),t=Mn(t,i.patch,o+1,i.op),_r(t,void 0,_t(i.hash_algorithm))!==i.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function $T(e,t,n){let r=0,o=!1,i=!1,a=e.message;if(typeof e.message=="string"){let m=vg(e.message,t,n);a=m.value,r+=m.replacements,m.replacements>0&&(o=!0)}let s=wg(e.patch,t,n);r+=s.replacements,o||=s.replacements>0;let c=e.reanchor_evidence?.map(m=>{let p=m.patch?wg(m.patch,t,n):{patch:void 0,replacements:0},u=m.record?Zi(m.record,t,n):{value:void 0,replacements:0};r+=p.replacements,r+=u.replacements;let f=p.replacements>0||u.replacements>0;if(o||=f,!f)return m;i=!0;let{patch:_,record:h,record_hash:g,record_hash_version:y,...w}=m;return p.replacements>0?w:{...w,patch:m.patch}});return{entry:{...e,message:a,patch:s.patch,...c?{reanchor_evidence:c}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:i}}function FT(e,t,n){let r=structuredClone(Zs),o=0,i=0,a=[];for(let s=0;s<e.length;s+=1){let c=e[s],m=zu(c);if(!m.ok)throw new l(`history-redact refuses invalid immutable record ${s+1} (${m.error}).`,d.GENERIC_FAILURE);let p=$T(c,t,n);i+=p.replacements,p.changed&&(o+=1);let u=_r(r,void 0,_t(c.hash_algorithm));r=Mn(r,p.entry.patch,s+1,p.entry.op);let f=_r(r,void 0,_t(c.hash_algorithm));a.push(Hu(c,{...p.entry,before_hash:u,after_hash:f},{retainPriorRecord:p.changed,retainPriorRecordHash:!p.changed}))}return{entries:a,finalDocument:r,entriesChanged:o,replacements:i}}function MT(e){return Object.keys(e.metadata).length>0}function DT(e){if(!MT(e.finalDocument))return{raw:null,path:null,document:null};let t=it(at(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new l("history-redact would change the item id; narrow your patterns.",d.USAGE);return{document:t,path:pt(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:We(t,{format:"toon",schema:e.settings.schema})}}function UT(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function GT(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??at(e.rewritten.finalDocument);return t.push(Fe({nowIso:k(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function jT(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await Mt(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let a=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await te(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await Jc.rm(e.currentItem.path,{force:!0}),await te(e.subject.historyPath,Vu(e.rewrittenEntries))}catch(c){try{await qT(e.subject.historyPath,n,o,i)}finally{await Qs(e.subject.historyPath)}throw c}await Qs(e.subject.historyPath);let s=e.nextItem.path??e.currentItem.path;s&&(t=await Dt({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:s,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(s=>{a=()=>{throw s}})}a()},afterWrite:async()=>[...t,...await KT(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function qT(e,t,n,r){t===null?await Jc.rm(e,{force:!0}):await te(e,t);for(let o of n){let i=r.get(o);i===void 0?await Jc.rm(o,{force:!0}):await te(o,i)}}async function KT(e,t){let n=[],r=new Set(t.filter(o=>o!==null));for(let o of r)n.push(...await Y({path:o,scope:"project",op:"history_redact"}));return n.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),n}async function bg(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await Sr(n.path),a=t.replacement??"",s=a.length===0,c=s?"[redacted]":a,m=xT(t.literal,t.regex),p=await en(r,e,o,i.type_to_folder);return Fi({pmRoot:r,subject:p,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>zT({pmRoot:r,subject:p,settings:o,typeRegistry:i,options:t,rules:m,replacement:c,replacementIsDefault:s},u)})}function zT(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:i,options:a,rules:s,replacement:c,replacementIsDefault:m}=e,p=t.entries,u=LT(p),f=FT(p,s,c),_=u.hashMismatchesBefore+u.hashMismatchesAfter,h=!!a.dryRun,g=f.replacements>0,y=[];_>0&&y.push(`history_redact_preexisting_hash_mismatches:${_}`),g||y.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},b=DT({pmRoot:n,subject:r,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),S=(w.path??null)!==(b.path??null)||(w.raw??null)!==(b.raw??null),T=t.author,$=UT(a,f),{rewrittenEntries:P,auditEntryAdded:L}=GT({rewritten:f,dryRun:h,changed:g,nextItemDocument:b.document,author:T,message:$});return{changed:g,rewrittenEntries:P,...jT({pmRoot:n,subject:r,settings:o,typeRegistry:i,currentItem:w,nextItem:b,author:T,rewrittenEntries:P}),report:({verification:q,warnings:H})=>({id:r.id,dry_run:h,changed:g,patterns:{literal_count:s.filter(J=>J.kind==="literal").length,regex_count:s.filter(J=>J.kind==="regex").length,total_count:s.length,replacement_is_default:m},history:{path:r.historyPath,entries_scanned:p.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:_,audit_entry_added:L,verify_ok:q.ok,verify_errors:q.errors},item:{existed_before:w.path!==null,exists_after:b.path!==null,path_before:w.path,path_after:b.path,changed:S},warnings:[...new Set([...y,...H])].sort((J,ie)=>J.localeCompare(ie)),generated_at:k()})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7317758-33fb-52ee-a94b-1b97c4920773")}catch{}})();async function kg(e,t,n){return Hn(e,t,n,{input:await Qi(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>zn(r),createEntry:r=>r,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm learnings --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5bdc2e7-1633-5bc8-97c7-8f6ecd253294")}catch{}})();async function Sg(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=$t(),o=E(process.cwd(),n.path);await I(o);let i=await A(o),a=C(t.author,i.author_default),s=(await r.resolveValue(t.body,"--body",nf(t,"body"))).trim();if(s.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",d.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let c=await le({pmRoot:o,settings:i,id:e,op:"append",author:a,message:t.message,force:t.force,mutate(m){let p=m.body.trim().length>0?`
18
18
 
19
19
  `:"";return m.body=`${m.body.trimEnd()}${p}${s}
20
- `,{changedFields:["body"]}}});return{item:c.item,appended:s,changed_fields:c.changedFields}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8f7d8635-ea1c-5c87-9001-bfa1d1618478")}catch{}})();var TT=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function lg(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function zc(e,t){return Hc(e,t,{operation:"close"})}function Hc(e,t,n){let r=lg(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",d.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function Bc(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],i=o.filter(m=>m.kind==="blocked_by"),a=e.blocked_reason!==void 0,s=[];if(r&&(delete e.blocked_by,s.push("blocked_by")),a&&(delete e.blocked_reason,s.push("blocked_reason")),t.orderingEdges==="remove"&&i.length>0){let m=new Set(i),p=o.filter(u=>!m.has(u));p.length>0?e.dependencies=p:delete e.dependencies,s.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:s,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...i.length>0?[`closed_removed_predecessors:${e.id}:${i.map(m=>m.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${i.length}`]:[]]};let c=[...new Set([...n?[n]:[],...i.map(m=>m.id)])];return c.length===0?{changedFields:s,warnings:[]}:{changedFields:s,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab15186d-b8bc-5740-bc16-d5af1eeeaa02")}catch{}})();var CT=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function IT(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new l(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,d.USAGE)}function dg(e){let t=[];for(let n of CT){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function mg(e,t,n={}){let r=dg(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},i=r.map(s=>`--${s.key.replaceAll("_","-")}`),a=["--pm-path",t,"update",e.id,...r.flatMap((s,c)=>[i[c],o[s.key]?.trim()||"<value>"])];return{missing:i,suggested_retry:Zt(a),suggested_retry_args:a}}async function RT(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let i=o.trim();if(i===n)return!0;if(r.has(i))return!1;r.add(i),o=(await e(i))?.duplicate_of}return!1}function OT(e){return typeof e!="string"||e.trim().length===0}async function xT(e,t,n,r){let o=n?.trim();if(!o)return;if(o===r)throw new l("An item cannot be closed as a duplicate of itself.",d.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let i=x(t,O()),a=new Map,s=async m=>{if(a.has(m))return a.get(m)??null;let p=await z(e,m,t.id_prefix,t.item_format,i.type_to_folder);if(!p)return a.set(m,null),null;let{document:u}=await ae(p,{schema:t.schema});return a.set(m,u.metadata),u.metadata},c=await s(o);if(!c)throw new l(`Duplicate target "${o}" was not found. Create or locate the canonical item first.`,d.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 ${r} "Duplicate of ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await RT(s,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${o}" points back to "${r}".`,d.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 c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new l(`Duplicate target "${o}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,d.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function PT(e,t,n){return e.filter(r=>r.parent===t&&!re(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function NT(e,t,n){let r=new Map(e.map(s=>[s.id.trim().toLowerCase(),s])),o=sf(e),i=t.trim().toLowerCase(),a=n.blocked_statuses;return e.filter(s=>a.has(s.status)).map(s=>({item:s,blockerIds:o.get(s.id.trim().toLowerCase())})).filter(({blockerIds:s})=>s.includes(i)).filter(({blockerIds:s})=>s.every(c=>{if(c===i)return!0;let m=r.get(c);return m!==void 0&&re(m.status,n)})).map(({item:s,blockerIds:c})=>({id:s.id,blocker_ids:c})).sort((s,c)=>s.id.localeCompare(c.id))}async function LT(e,t,n,r,o,i){let a=NT(n,r,i),s=[];for(let c of a)try{let m=await se({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(p){let u=p.metadata.dependencies??[],f=u.filter(h=>{let g=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(g)});p.metadata.status=i.open_status,delete p.metadata.blocked_by,delete p.metadata.blocked_reason,p.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?p.metadata.dependencies=f:delete p.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==u.length&&_.push("dependencies"),{changedFields:_}}});s.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let p=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";s.push(`auto_unblock_failed:${c.id}:${p}`)}return s}function $T(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:i}of r){if(typeof o!="string")continue;let a=o.trim();a.length!==0&&(e[i]=a,n.push(i))}return n}function FT(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:i}of r)OT(e[o])&&(e[o]=i,n.push(o));return n}function MT(e,t,n,r){let o=[];if(t!=="off"){let i=dg(e);if(i.length>0){let a=i.map(s=>s.label);if(t==="strict"){let s=i.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...s.flatMap(m=>[m,"<value>"])];throw new l(`Cannot close item ${e.id}: missing ${a.join(", ")}. Populate fields or use --validate-close warn.`,d.USAGE,{code:"close_validation_missing_fields",recovery:{missing:s,suggested_retry:Zt(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}o.push(`close_validation_missing_fields:${e.id}:${a.join(",")}`)}if(n.length>0){if(t==="strict")throw new l(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,d.USAGE);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function DT(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function UT(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function GT(e,t){if(re(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,d.CONFLICT,{recovery:mg(e,t.pmRoot,t.options)});let n=$T(e,t.options),r=FT(e,t.duplicateOf),o=MT(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let i=t.options.completedAt!==void 0||e.completed_at===void 0;i&&(e.completed_at=t.completedAt);let a=["status","closed_at",...i?["completed_at"]:[],...DT(e,t.closeReason),...n];if(of(e)&&(e.plan_mode="completed",a.push("plan_mode")),t.duplicateOf!==void 0){a.push("duplicate_of");for(let c of r)a.includes(c)||a.push(c)}a.push(...UT(e));let s=Bc(e,t.lifecyclePolicy);return a.push(...s.changedFields),o.push(...s.warnings),{changedFields:a,...o.length>0?{warnings:o}:{}}}async function pg(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let i=await A(o),a=$(i.schema),s=C(n.author,i.author_default),c=x(i,O()).type_to_folder,m=await z(o,e,i.id_prefix,i.item_format,c);if(!m)throw await _t(o,e,i.id_prefix,c);let p=await xT(o,i,n.duplicateOf,m.id),u={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??i.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=zc({explicit:t,duplicateOf:p,resolution:n.resolution,message:n.message},u.requireCloseReason).closeReason,_=IT(n.validateClose)??i.governance.close_validation_default,h=await _e(o,i.item_format,c,void 0,i.schema),g=PT(h,m.id,a),y=k(),w=n.completedAt===void 0?y:ie(n.completedAt,new Date(y),"completed-at"),b=await se({pmRoot:o,settings:i,id:m.id,op:"close",author:s,message:n.message,force:n.force,mutate(T){return GT(T.metadata,{pmRoot:o,statusRegistry:a,force:n.force,options:n,duplicateOf:p,validateCloseMode:_,activeChildIds:g,closeReason:f,closedAt:y,completedAt:w,lifecyclePolicy:u})}}),S=_==="warn"?mg(b.item,o):void 0;return{item:b.item,changed_fields:b.changedFields,...S?{recovery:S}:{},warnings:[...b.warnings,...await LT(o,i,h,m.id,s,a)]}}function wt(e,t,n,r){return pg(e,t,n,r)}import jT from"fast-json-patch";import Vc from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebfa0c5e-461b-5078-8272-69086e84b4dc")}catch{}})();async function ug(e,t,n){let r=await Qu(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:fg(n),recovered:!0}}function qT(e,t){return Yu(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function fg(e){let t=ec(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:rt(ot(t))}async function KT(e,t,n,r){let o=await tn(e,t,n,r),i=o.located?await zu({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function zT(e,t){let n=_r(e),r=_r(t),o=jT.compare(n,r),i=new Set;for(let a of o){if(a.path==="/body"||a.path.startsWith("/body/")){i.add("body");continue}let s=a.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(s.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((a,s)=>a.localeCompare(s))}async function HT(e){let t=await h_({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>ug(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function BT(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:fg(t),originalRaw:null}}function VT(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new l(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,d.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function WT(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await te(e.existingItemPath,e.resolvedOriginalRaw),await Vc.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await te(e.existingItemPath,e.resolvedOriginalRaw);return}await Vc.rm(e.restoredItemPath,{force:!0})}async function YT(e){return[...await Y({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await Y({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function an(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let i=await A(o),a=x(i,O()),s=await KT(o,e,i,a.type_to_folder),c=s.id,{raw:m,entries:p}=await Au(s.historyPath,c);if(p.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let u=qT(t,p),f=Ju(ec(p,u.historyIndex),u),_=Lu(f,{schema:i.schema});if(_.metadata.id!==c)throw new l(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let h=(s.located?await ug(s.located,i,p):null)?.raw??null,g=C(n.author,i.author_default),y=await Te(o,c,i.locks.ttl_seconds,g,!!n.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let{loadedItemUnderLock:w,existingItemPath:b}=await HT({pmRoot:o,subject:s,settings:i,typeRegistry:a,historyRawBeforeLock:m,currentItemRawBeforeLock:h,history:p}),S="toon",T=BT(w,p),L=VT({document:T.document,author:g,force:n.force,enforcement:i.governance.ownership_enforcement,resolvedId:c}),P=zT(T.document,_),M=await yr({pmRoot:o,settings:i,operation:"restore",author:g,before:T.document,after:_});await Wo({pm_root:o,operation:"restore",before:T.document,after:_,changed_fields:P,sdk:ki({pmRoot:o,settings:i,typeToFolder:a.type_to_folder})});let K=Ve(_,{format:S,schema:i.schema}),H=dt(o,_.metadata.type,c,S,a.type_to_folder),Z=await $t(o,g),le=[];try{await te(H,K),b&&H!==b&&await Vc.rm(b);let ue=$e({nowIso:k(),author:g,op:"restore",before:T.document,after:_,message:n.message,context:M.decisions.length===0?void 0:{workflow_policies:M.decisions}});try{await xt(s.historyPath,ue)}catch(Ze){throw await WT({existingItemPath:b,resolvedOriginalRaw:T.originalRaw,restoredItemPath:H}),Ze}le=await Ft({pmRoot:o,preferredFormat:i.item_format,typeToFolder:a.type_to_folder,schema:i.schema,itemPath:H,previousItemPath:b??void 0,document:_})}finally{await Z()}let de=await YT({restoredItemPath:H,historyPath:s.historyPath,before:T.document,after:_});In({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:T.document.metadata.status,status:_.metadata.status,previous:Qt(T.document.metadata,P),current:Qt(_.metadata,P),changed_fields:P});let qe=p[u.historyIndex],j=Mn(p,!0);return{item:_.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:j===null?null:j+u.historyIndex+1,entry_ts:qe.ts,entry_op:qe.op},changed_fields:P,warnings:[...M.warnings,...w?.recovered?["restore_unreadable_item_recovered"]:[],...s.historyPolicyWarnings,...L,...le,...de]}}finally{await y()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6edfa77d-9b76-540b-a365-a3fef0450c53")}catch{}})();var hg=1,Wc="close-many",JT=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function XT(e,t){return Cr(e,t,{includePagination:!1})}function QT(e,t){return Cr(e,t)}function ZT(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)}function eC(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function tC(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new l("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",d.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function nC(e,t){let n=$(t.schema),r=x(t,O()),o=await _e(e,t.item_format,r.type_to_folder,void 0,t.schema),i=new Map,a=new Map;for(let s of o){if(typeof s.parent!="string"||s.parent.length===0||(a.set(s.id,s.parent),re(s.status,n)))continue;let c=i.get(s.parent);c?c.push(s.id):i.set(s.parent,[s.id])}for(let s of i.values())s.sort((c,m)=>c.localeCompare(m));return{childrenByParent:i,parentByChild:a}}function _g(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,i=t.get(e),a=[],s=new Set,c=!1;for(;i!==void 0&&!s.has(i);){let m=n?.get(i);if(m!==void 0){o+=m+1;break}s.add(i),a.push(i),o+=1,i=t.get(i)}if(i!==void 0&&s.has(i)&&(c=!0),!c){n?.set(e,o);for(let[m,p]of a.entries())n?.set(p,o-m-1)}return o}async function rC(e){let t=await ci(e.pmRoot,Wc,e.rollbackId,hg),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await li(t.items,(o,i)=>an(o,i,{author:e.options.author,message:n,force:!0},e.global));return{...en({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function oC(e,t,n,r,o){return e.map(i=>{let a=(t.get(i.id)??[]).filter(c=>!n.has(c)),s=!gg(i,r,o);return{id:i.id,title:typeof i.title=="string"?i.title:"",status:i.status,action:s?"skip":"close",...s?{skip_reason:"already_terminal"}:{},...a.length>0?{active_child_ids:a}:{}}})}async function iC(e){let t=await si(e.pmRoot,Wc,e.checkpointId,{schema_version:hg,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function aC(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await wt(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){t.push({id:r.id,status:"failed",error:An(o)})}}return{rows:t,closedIds:n}}function sC(e){return typeof e.rollback=="string"?e.rollback:void 0}function cC(e,t){if(t.trim().length===0)throw new l("--rollback requires a checkpoint id",d.USAGE);if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(QT(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function lC(e){if(!XT(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${JT}). Refusing to match every item.`,d.USAGE)}function dC(e,t){let n=new Map;return[...e].sort((r,o)=>{let i=_g(o.id,t,n)-_g(r.id,t,n);return i!==0?i:r.id.localeCompare(o.id)})}function gg(e,t,n){return n||!re(e.status,t)}function mC(e,t,n){return new Set(e.filter(r=>gg(r,t,n)).map(r=>r.id))}async function pC(e){lC(e.options);let t=$(e.settings.schema),n=tC(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await ht(e.options.status,eC(e.options.list),e.global),{childrenByParent:i,parentByChild:a}=await nC(e.pmRoot,e.settings),s=dC(o.items,a),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],m=c.length===0?[]:(await ht(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,p=new Set(m.map(f=>f.id)),u=mC(s,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:s,unmatchedIds:c.length===0?void 0:c.filter(f=>!p.has(f)),planRows:oC(s,i,u,t,r)}}function uC(e){return{outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function fC(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return iC({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function yg(e,t){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=e.dryRun===!0,i=sC(e);if(ZT(e.list),i!==void 0)return cC(e,i),rC({pmRoot:n,rollbackId:i,options:e,global:t});let a=await pC({pmRoot:n,settings:r,options:e,global:t});if(o)return uC(a);let s=new Set(a.planRows.filter(w=>w.action==="close").map(w=>w.id)),c=k(),m=ai(Wc,c),p=await fC({context:a,options:e,closableIds:s,checkpointId:m,nowValue:c}),u={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:a.validateCloseMode,force:a.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await aC({matched:a.matched,closableIds:s,reason:a.reason,closeOptions:u,global:t}),h=f.filter(w=>w.status==="closed").length,g=f.filter(w=>w.status==="skipped").length,y=f.filter(w=>w.status==="failed").length;return{...en({applied:h,skipped:g,failed:y,unmatched:a.unmatchedIds?.length??0}),mode:"apply",matched_count:a.matched.length,dry_run:!1,...a.reason!==void 0?{reason:a.reason}:{},filters:a.listed.filters,...a.validateCloseMode?{validate_close:a.validateCloseMode}:{},...p?{checkpoint:p}:{},closed_count:h,skipped_count:g,failed_count:y,rows:f,ids:_,...a.unmatchedIds!==void 0?{unmatched_ids:a.unmatchedIds,unmatched_count:a.unmatchedIds.length}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="902e9f78-a2c1-59bb-aaa2-763576d5c68b")}catch{}})();function _C(e,t){return[...new Set([...so.filter(n=>e[n]!==void 0),...Object.keys(e).filter(n=>e[n]!==void 0),...t.length>0?["body"]:[]])].sort((n,r)=>n.localeCompare(r))}function hC(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Yc(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),i=x(o,O()),a=await z(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await _t(r,e,o.id_prefix,i.type_to_folder);let s=await ae(a,{schema:o.schema}),c=s.document.metadata,m=k(),p=C(t.author,o.author_default),u=await hr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:i.type_to_folder,probeExisting:!1}),f=$(o.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let h={...c,id:u,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let g=Tt(O()),y=rt({metadata:h,body:s.document.body},{schema:o.schema,extensionFieldNames:g}),w=await qn({title:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[a.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),b=_C(y.metadata,y.body),S=dt(r,y.metadata.type,u,o.item_format,i.type_to_folder),T=tt(r,u),L=await Te(r,u,o.locks.ttl_seconds,p,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),P={metadata:{},body:""},M,K;try{let H=await $t(r,p,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await qn({title:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[a.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let Z=await z(r,u,o.id_prefix,o.item_format,i.type_to_folder);if(Z)throw new l(`Cannot copy to ${u}: an item with that id already exists at ${Z.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${u} already exists at ${Z.itemPath}.`,recovery:{suggested_retry:`pm copy ${a.id}`}});await te(S,Ve(y,{format:o.item_format,schema:o.schema,extensionFieldNames:g}));try{let le=$e({nowIso:m,author:p,op:"create",before:P,after:y,message:hC(a.id,t.message)});await xt(T,le)}catch(le){throw await En(S),le}K=await Ft({pmRoot:r,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:S,document:y})}finally{await H()}M=[...await Y({path:S,scope:"project",op:"create",item_id:y.metadata.id,item_type:y.metadata.type,before:P,after:y,changed_fields:b}),...await Y({path:T,scope:"project",op:"create:history",item_id:y.metadata.id,item_type:y.metadata.type,before:P,after:y,changed_fields:b})],In({id:y.metadata.id,op:"create",item_type:y.metadata.type,status:y.metadata.status,current:Qt(y.metadata,b),changed_fields:b})}finally{await L()}return{source_id:a.id,item:structuredClone(y.metadata),changed_fields:b,warnings:[...Pi(w),...K,...M],...w===void 0?{}:{similarity_advisory:w}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5c8f85c4-33c4-5e7d-b01d-b95c8281250d")}catch{}})();var gC="hierarchy-integrity";async function Ji(e){let t=e.required?await Te(e.pmRoot,gC,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01a312de-88fc-514f-b37b-2e717222a8ed")}catch{}})();function Xi(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Qi(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Zi(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(ao.includes(t))return t;let n=fe(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new l("Confidence must be an integer 0..100 or one of low|med|medium|high",d.USAGE);return n}function ea(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new l("Regression must be one of true|false|1|0",d.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c22dc1f8-285a-5858-9087-17a8deed6db8")}catch{}})();var yC=new Set(["none","null"]);function ta(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function Je(e){return e===void 0?!1:yC.has(e.trim().toLowerCase())}function na(e,t,n){if(!Je(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Oe(e,t,n){if(!e||e.length===0||!e.some(o=>Je(o)))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function ra(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(i=>typeof i=="string"))throw new l(`${n.valueFlag} entries must be strings.`,d.USAGE);let o=r;if(o.some(i=>Je(i))){if(o.filter(i=>!Je(i)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daa816a5-05d4-5e0a-90aa-9d96afdb2117")}catch{}})();var wC=new Set(["event","meeting","reminder","milestone","decision","adr"]);function wg(e,t,n,r){if(wC.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=Ho("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm claim ${e} --start`,to_status:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b968be78-8489-5735-8f95-8e38a36e160a")}catch{}})();var vt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],vC=new Set(vt);function vg(e){return di(e,vt)}function oa(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let a=o.toLowerCase();if(!vC.has(a)){r.push(o);continue}if(Object.hasOwn(n,a))throw new l(`${t} provides key "${o}" more than once after case normalization`,d.USAGE);n[a]=i}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${vt.join(", ")}.`,d.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new l(`${t} command and cmd must match when both are provided`,d.USAGE);let{cmd:o,...i}=n;return{...i,command:i.command??o}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dd87416a-25ec-5dfe-8c54-ef7f43529ecc")}catch{}})();var ln=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Sr,wf,"FORCE_COLOR"]),sa=/^[A-Za-z_][A-Za-z0-9_]*$/,cn=["schema","tracker","auto","none"],bg=["source","isolated","snapshot"];function Fr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,d.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1);if(!sa.test(a))throw new l(`${t} env_set key "${a}" is invalid`,d.USAGE);if(ln.has(a.toUpperCase()))throw new l(`${t} env_set key "${a}" is reserved for sandbox safety`,d.USAGE);r[a]=s}return Object.keys(r).length>0?r:void 0}function Mr(e,t){if(!e)return;let n=Un(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,d.USAGE);for(let r of n){if(!sa.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(ln.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function ca(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,d.USAGE)}function la(e,t){if(!e)return;let n=e.trim().toLowerCase();if(cn.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${cn.join(", ")}`,d.USAGE)}function dn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(bg.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${bg.join(", ")}`,d.USAGE)}function mn(e){if(!e)return;let t=Un(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Vn(e,t,n){let r=mn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(i){throw new l(`${t} ${n} includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`,d.USAGE)}return r}}function da(e,t){if(!e)return;let n=fe(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,d.USAGE);return n}function ma(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0||s.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[a]=s}return Object.keys(r).length>0?r:void 0}function pa(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0||s.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,d.USAGE);let c=Number(s);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${a}" must be numeric`,d.USAGE);r[a]=c}return Object.keys(r).length>0?r:void 0}var bC=new Set(vt);function ua(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kC(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let a=o.toLowerCase();if(!bC.has(a)){r.push(o);continue}if(Object.hasOwn(n,a))throw t(`provides key "${o}" more than once after case normalization`);n[a]=i}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${vt.join(", ")}.`);return n}function sn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function ia(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(a=>typeof a!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=o.filter(a=>a.length>0);return i.length>0?i:void 0}function kg(e,t,n){let r=ia(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(i){throw n(`field "${t}" includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`)}return r}}function aa(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function SC(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:aa(n,"timeout_seconds",t),i=r===void 0?void 0:aa(r,"timeout",t);if(o!==void 0&&i!==void 0&&o!==i)throw t("timeout and timeout_seconds must match when both are provided");let a=o??i;if(!Number.isInteger(a)||a<=0)throw t("timeout_seconds must be a positive integer");return a}function EC(e,t){let n=sn(e,"scope",t);if(n===void 0)return"project";if(!ct.includes(n))throw t(`field "scope" must be one of: ${ct.join(", ")}`);return n}function AC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!ua(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(typeof i!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!sa.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(ln.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=i}return Object.keys(r).length>0?r:void 0}function TC(e,t){let n=ia(e,"env_clear",t);if(n){for(let r of n){if(!sa.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(ln.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function CC(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function IC(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=aa(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function RC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!ua(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof i!="string"&&typeof i!="number"&&typeof i!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(i)}return Object.keys(r).length>0?r:void 0}function OC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!ua(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=aa(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function xC(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!ua(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${vt.join(", ")}.`);let o=kC(e,r),i=sn(o,"command",r),a=sn(o,"cmd",r);if(i!==void 0&&a!==void 0&&i!==a)throw r("command and cmd must match when both are provided");let s=i??a;if(s===void 0||s.trim().length===0)throw r('requires a non-empty "command" string');let c=sn(o,"path",r),m=sn(o,"pm_context_mode",r);if(m!==void 0&&!cn.includes(m))throw r(`field "pm_context_mode" must be one of: ${cn.join(", ")}`);let p=dn(sn(o,"workspace_context_mode",r),`${n} ${t}`),u=sn(o,"note",r);return{command:s,path:c!==void 0&&c.length>0?c:void 0,scope:EC(o,r),timeout_seconds:SC(o,r),pm_context_mode:m,workspace_context_mode:p,env_set:AC(o,r),env_clear:TC(o,r),shared_host_safe:CC(o,"shared_host_safe",r),assert_stdout_contains:ia(o,"assert_stdout_contains",r),assert_stdout_regex:kg(o,"assert_stdout_regex",r),assert_stderr_contains:ia(o,"assert_stderr_contains",r),assert_stderr_regex:kg(o,"assert_stderr_regex",r),assert_stdout_min_lines:IC(o,r),assert_json_field_equals:RC(o,r),assert_json_field_gte:OC(o,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function Sg(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,d.USAGE);let r;try{r=JSON.parse(n)}catch(i){throw new l(`${t} value is not valid JSON: ${i instanceof Error?i.message:String(i)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return o.map((i,a)=>xC(i,o.length>1?`entry ${a+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1ffee31a-c272-5494-a04a-01a17b78dd2d")}catch{}})();var Jc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Xc=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],Eg=[...Jc,...Xc],fa=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function _a(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let o=r.trim().toLowerCase();if(!o)throw new l("--unset values must not be empty",d.USAGE);if(Je(o))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let i=e.resolveDefinition(o);if(!i)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(i.metadataKey),n.add(i.optionKey)}return{metadataKeys:t,optionKeys:n}}function ha(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let i of o){if(i.allow_unset===!1)continue;let a=new Set;if(typeof i.key=="string"&&i.key.length>0&&a.add(i.key.toLowerCase()),typeof i.metadata_key=="string"&&i.metadata_key.length>0&&a.add(i.metadata_key.toLowerCase()),typeof i.cli_flag=="string"&&i.cli_flag.length>0&&(a.add(i.cli_flag.replaceAll("-","_").toLowerCase()),a.add(i.cli_flag.toLowerCase())),Array.isArray(i.cli_aliases))for(let s of i.cli_aliases)typeof s!="string"||s.length===0||(a.add(s.replaceAll("-","_").toLowerCase()),a.add(s.toLowerCase()));if(a.has(r))return{optionKey:i.key,metadataKey:i.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48975dc8-636f-51a1-858a-f97c7a037688")}catch{}})();function Tg(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,d.USAGE)}function Qc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function xe(e,t,n,r=n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE,{field:r,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var Cg=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function PC(e,t){return t==="defined"?e!==void 0:!!e}function Ag(e,t,n){if(!PC(e,n))return;let r=fe(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function NC(e,t,n){let r=e?ie(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new l("--event recur_until must be at or after start",d.USAGE);return r}function LC(e){return Array.from(new Set(Qc(e).map(t=>xe(t.toLowerCase(),Bd,"event weekday")))).sort((t,n)=>ms(t)-ms(n))}function $C(e){return Array.from(new Set(Qc(e).map(t=>{let n=fe(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new l("--event recur_by_month_day values must be integers 1..31",d.USAGE);return n}))).sort((t,n)=>t-n)}function FC(e,t){return Array.from(new Set(Qc(e).map(n=>ie(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Ig(e,t,n,r){let o=e.recur_freq?.trim(),i=e.recur_interval?.trim(),a=e.recur_count?.trim(),s=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),p=e.recur_exdates?.trim();if(![o,i,a,s,c,m,p].some(b=>b!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let u=xe(o.toLowerCase(),Hd,"event recurrence frequency"),f=Ag(i,"recur_interval",r),_=Ag(a,"recur_count",r),h=NC(s,t,n),g=LC(c),y=$C(m),w=FC(p,n);return{freq:u,interval:f,count:_,until:h,by_weekday:g.length>0?g:void 0,by_month_day:y.length>0?y:void 0,exdates:w.length>0?w:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2c9f586-3e93-5caf-a5c2-38be30c67171")}catch{}})();function Dr(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function Ur(e,t,n=Mt()){for(let r of t??[])try{Jd(e,r.id,r.kind,n)}catch(o){throw new l(An(o),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Rg(e,t){return(await ae(e,{schema:t})).document.metadata.created_at}async function MC(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await z(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Rg(n,t.schema)}function DC(e){let t=e.registry.require(e.dependency.kind);return new l(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,d.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function UC(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:i})=>i===null?[]:[[o,i]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await Rg(n.get(o),e.context.schema)])));for(let o of e.holders){let i=await MC(o,e.context);if(i!==void 0)for(let a of t){let s=r.get(a.id),c=Date.parse(i),m=Date.parse(s);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw DC({holder:o,dependency:a,sourceCreatedAt:i,targetCreatedAt:s,registry:e.registry})}}}async function pn(e){let t=e.registry??Mt(),n=(e.dependencies??[]).filter(a=>!Zp(a.source_kind)),r=[...new Set(n.map(a=>a.id))],o=await Promise.all(r.map(async a=>({target:a,located:await z(e.pmRoot,a,e.idPrefix,e.itemFormat,e.typeToFolder)}))),i=o.filter(({located:a})=>a===null).map(({target:a})=>a).sort((a,s)=>a<s?-1:1);if(i.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${i.length===1?"":"s"} not found: ${i.join(", ")}`,d.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:i,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${i.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:i,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${i[0]}" --limit 10`}});return await UC({dependencies:n,missingTargets:i,resolutions:o,holders:e.holders??[],registry:t,context:e}),i.map(a=>`dependency_target_unresolved:${a}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var GC={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function jC(e){return GC[e]}function Zc(e){return jC(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3950ef46-cc2b-5b8e-97d6-34c739bd816e")}catch{}})();var Og="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",qC="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",KC=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,zC=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Pg=1e3,el=60*Pg,HC=60*el;function xg(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new l(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,d.USAGE);return n.toISOString()}function BC(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new l(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,d.USAGE);let o=r.replace(/^([+-]?\d+)mo$/i,"$1m"),i=KC.exec(r);if(i){let c=i[1]==="-"?-1:1,m=Number.parseInt(i[2],10)*c;return xg(n.getTime()+m*el,r)}let a=zC.exec(r);if(a){let[,c,m,p,u]=a;if(m||p||u){let f=c==="-"?-1:1,_=Number.parseInt(m??"0",10),h=Number.parseInt(p??"0",10),g=Number.parseInt(u??"0",10),y=_*HC+h*el+g*Pg;return xg(n.getTime()+f*y,r)}}let s=o.startsWith("+")||o.startsWith("-")?o:`+${o}`;return ie(s,n,"event.duration")}function Ng(e,t,n,r){if(t&&n)throw new l(qC,d.USAGE);if(n){let i=BC(e,n);if(i<e)throw new l(Og,d.USAGE);return i===e?void 0:i}if(!t)return;let o=ie(t,r,"event.end");if(o<e)throw new l(Og,d.USAGE);if(o!==e)return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8288d6e7-a027-5bfa-9b4a-3c8b581f31ce")}catch{}})();var VC=["at","date","text","title"],WC=["start","date","end","duration","title","description","location","timezone","all_day",...Cg],YC=["key","value"];function Lg(e,t){return t==="trimmed"?e?.trim():e}function JC(e,t){return t==="defined"?e!==void 0:!!e}function ga(e,t,n){return e.map(r=>{let o=me(r,"--reminder");Ye(o,"--reminder",VC);let i=Lg(o.at??o.date,n.valueMode),a=Lg(o.text??o.title,n.valueMode);if(!i||!a)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let s=a.trim();if(!s)throw new l("--reminder text must not be empty",d.USAGE);return{at:ie(i,t,"reminder.at"),text:s}})}function ya(e,t,n){return e.map(r=>{let o=me(r,"--event");Ye(o,"--event",WC);let i=(o.start??o.date)?.trim();if(!i)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let a=ie(i,t,"event.start"),s=o.end?.trim(),c=o.duration?.trim(),m=Ng(a,s,c,t),p=o.title,u=o.description,f=o.location,_=o.timezone,h=p?.trim(),g=u?.trim(),y=f?.trim(),w=_?.trim(),b=[["title",p,h],["description",u,g],["location",f,y],["timezone",_,w]];for(let[P,M,K]of b)if(M!==void 0&&!K)throw new l(`--event ${P} must not be empty`,d.USAGE);let S=o.all_day?.trim(),T=Ig(o,a,t,n.recurrenceEmptyNumericGuard),L=JC(S,n.allDayEmptyGuard)?Tg(S,"--event all_day"):void 0;return{start_at:a,end_at:m,title:h,description:g,location:y,all_day:L,timezone:w,recurrence:T}})}function wa(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new l("--type-option values must not be empty",d.USAGE);let o,i;if(r.includes(",")||r.includes(`
21
- `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=me(r,"--type-option");Ye(a,"--type-option",YC),o=a.key?.trim(),i=a.value?.trim()}else{let a=r.indexOf("="),s=r.indexOf(":"),c=a;if(a<=0&&s>0&&(c=s),c<=0||c===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);o=r.slice(0,c).trim(),i=r.slice(c+1).trim()}if(!o||!i)throw new l("--type-option requires key and value",d.USAGE);t[o]=i}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d979a65f-8e7c-511f-b683-8faa3e43e100")}catch{}})();var XC=["strict","progressive"],QC=["lightweight"],Dg=new Set(["Reminder","Meeting","Event"]),ZC=new Set(["author","created_at","text"]),nl=[...Eg,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...fa],e0=(()=>{let e=new Map;for(let t of nl)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),va=new Map(nl.map(e=>[e.optionKey,e.canonical])),t0=nl.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function n0(e,t){let n=ee(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function r0(e,t){let n=e.default_status;if(n!==void 0){let r=ee(n,t);if(r)return r}return t.open_status}function tl(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}var o0=ta();function Ug(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i};Je(t.template)&&(t.template=void 0);let r=new Set([...va.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!Je(i))continue;let a=o==="rank"?"order":va.get(o)??o;n(a),t[o]=void 0}return Ie(e,ra(t,o0))}function ve(e){if(e!==void 0)return e}function i0(e,t){return _a({raw:e,supportedFields:t0,resolveDefinition:n=>e0.get(n)??ha(n,"create",t)})}var $g=["id","kind","type","author","created_at","source_kind"],ba=["path","scope","note"];function a0(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let i=o.trim(),a=ka(i,$g);Dr(i,a);let s=a?me(o,"--dep"):{id:i,kind:"related"};a&&Ye(s,"--dep",$g);let c=ve(s.id),m=s0(ve(s.kind??s.type));if(!c||!m)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",d.USAGE);if(c.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=vr(ve(s.source_kind)),u=ve(s.author);return{id:br(c,n,p),kind:xe(m,Vt,"dependency kind","kind"),created_at:tl(s.created_at,t),author:u??r,source_kind:p??"cli:create:dep",author_source:u?"asserted":"detected"}}),explicitEmpty:!1})}function s0(e){return typeof e=="string"?mo(e)??e.trim():e}function ka(e,t){return di(e,t)?!0:ui(e)}function fn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Oe(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(o=>{let i=o.trim(),a=()=>{if(i.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:i}},s;try{s=me(o,e)}catch(m){if(e==="--comment"||e==="--note"||e==="--learning")return a();throw m}if(Object.keys(s).filter(m=>!ZC.has(m)).length>0)return{created_at:tl(s.created_at,n),author:ve(s.author)??r,text:i};let c=s.text??"";if(c==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:tl(s.created_at,n),author:ve(s.author)??r,text:c}}),explicitEmpty:!1})}function rl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--file","Use --clear-files to clear linked files."),{values:e.map(t=>{let n=t.trim(),r=ka(n,ba);Xs(n,"--file","file path",r);let o=r?me(t,"--file"):{path:n};if(r&&Ye(o,"--file",ba),!o.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:o.path,scope:xe(o.scope??"project",ct,"file scope"),note:ve(o.note)}}),explicitEmpty:!1})}function ol(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(t=>{let n=t.trim(),r=ka(n,vt);Xs(n,"--test","test command",r);let o=r?oa(me(t,"--test"),"--test"):{command:n},i=ve(o.command),a=ve(o.path);if(!i)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let s=ve(o.timeout_seconds),c=ve(o.timeout);if(s&&c&&s!==c)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let m=s??c;return{command:i,path:a,scope:xe(o.scope??"project",ct,"test scope"),timeout_seconds:m?fe(m,"timeout_seconds"):void 0,pm_context_mode:la(o.pm_context_mode,"--test"),workspace_context_mode:dn(o.workspace_context_mode,"--test"),env_set:Fr(o.env_set,"--test"),env_clear:Mr(o.env_clear,"--test"),shared_host_safe:ca(o.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:mn(o.assert_stdout_contains),assert_stdout_regex:Vn(o.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:mn(o.assert_stderr_contains),assert_stderr_regex:Vn(o.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:da(o.assert_stdout_min_lines,"--test"),assert_json_field_equals:ma(o.assert_json_field_equals,"--test"),assert_json_field_gte:pa(o.assert_json_field_gte,"--test"),note:ve(o.note)}}),explicitEmpty:!1})}function il(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(t=>{let n=t.trim(),r=ka(n,ba),o=r?me(t,"--doc"):{path:n};if(r&&Ye(o,"--doc",ba),!o.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:o.path,scope:xe(o.scope??"project",ct,"doc scope"),note:ve(o.note)}}),explicitEmpty:!1})}function c0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--reminder","Use --clear-reminders to clear reminders."),{values:ga(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function l0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--event","Use --clear-events to clear linked events."),{values:ya(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function d0(e,t,n,r=[]){let o=[...so.filter(i=>e[i]!==void 0),...r.filter(i=>e[i]!==void 0),...t.length>0?["body"]:[],...n.map(i=>`unset:${i}`)];return Array.from(new Set(o))}function m0(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Fg(e,t,n){let r=nr("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function p0(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function Gg(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function u0(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Fg(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Fg(r,e.name,"required_create_repeatables"));return n}function f0(e,t,n,r){for(let o of e)if(!(!Gg(t,o)&&!n.has(o)))throw new l(`Option ${Ae("create",o)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function _0(e,t,n){if(t!=="strict")return;let r=e.filter(i=>n.has(i)&&!Zc(i));if(r.length===0)return;let o=[...new Set(r.map(i=>Ae("create",i)))].sort((i,a)=>i.localeCompare(a));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function h0(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:wa(e),explicitEmpty:!1})}async function g0(e){return await fi(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function y0(e){return ft(e)?await g0(e):e}function w0(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${XC.join(", ")}`,d.USAGE)}function v0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new l("--schedule-preset must not be empty",d.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new l(`Invalid --schedule-preset value "${e}". Allowed: ${QC.join(", ")}`,d.USAGE)}function b0(e,t,n){let r=w0(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",d.USAGE);return"progressive"}function k0(e,t,n,r,o){let i=e.name,a=p0(t),s=u0(e,n),c=Tn(e,"create",s);if(c.errors.length>0)throw new l(c.errors.join("; "),d.CONFLICT);f0(c.disabled,a,r,i),_0(c.required,n,r);let m=u=>u==="author"&&o!=="unknown"||u==="status"&&e.default_status!==void 0||r.has(u)&&Zc(u)?!0:Gg(a,u),p=c.required.filter(u=>!m(u));return[...new Set(p.map(u=>Ae("create",u)))].sort((u,f)=>u.localeCompare(f))}var jg=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function S0(e,t){let n=[];for(let r of e){let o=r.match(jg);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function E0(e,t){return e.filter(n=>{let r=n.match(jg);return!r||r[2]!==t})}function A0(e,t,n,r){let o=E0(e,t);if(o.length===0)return;let i=qg(n,[],[],r.open_status);throw new l(o.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[i],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function T0(e,t){let n=e.options.find(r=>r.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function C0(e,t,n){let r=e.split("/")[0];switch(r){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[r,'"<value>"']}}function qg(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],i=["--status","--priority","--message"],a=[...new Set([...i,...t])],s=new Set(["--title","--description","--type"]);for(let c of a){if(s.has(c))continue;let m=zg[c];o.push(...m?[m]:C0(c,e.name,r)),s.add(c)}for(let c of n){let m=T0(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function al(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new l("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",d.USAGE):new l('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',d.USAGE):new l(`Missing required option ${t}`,d.USAGE);return n}function I0(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=Array.isArray(o)?[...o]:o;for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=Array.isArray(o)?[...o]:o);return n}function R0(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function O0(){let e=O();return e?e.commands.some(t=>t.action==="templates-show"||R0(t.command)==="templates show"):!1}function x0(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new l(`Templates package returned invalid payload for template "${t}". Expected an options object.`,d.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Templates package returned invalid options for template "${t}".`,d.GENERIC_FAILURE);let r={};for(let[o,i]of Object.entries(n)){if(typeof i=="string"||typeof i=="number"||typeof i=="boolean"){r[o]=i;continue}if(Array.isArray(i)&&i.every(a=>typeof a=="string")){r[o]=[...i];continue}throw new l(`Templates package returned unsupported option value for "${o}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function P0(e,t,n){if(!O0())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await Yo({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let o=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${o}`,d.USAGE)}return x0(r.result,e)}function V(e,t,n){return e.has(t)||n===void 0?void 0:ve(n)}function un(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var N0=new Set(["milestone","meeting","reminder","event"]);function Kg(e,t,n,r){let o=t!==void 0,i=n!==void 0&&n.length>0,a=r!==void 0&&r.length>0;return N0.has(e.toLowerCase())&&!o&&!i&&!a}function L0(e,t,n,r,o){let i=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&i.push(`event_without_schedule:${t}:no_time_set`),Kg(e,n,r,o)&&i.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),i}async function $0(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await ni(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function F0(e,t,n,r,o,i){let a=Ei(yi(o),t.id_prefix);if(Qo(a))return{parent:a,warnings:[]};if(vi(r,a,t.id_prefix),await z(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let s=ze(a,t.id_prefix);return{parent:a,warnings:wi(s,i).warnings}}async function M0(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await F0(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function D0(e){if(e.explicitId===void 0)return hr(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||Bu(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=ze(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",d.USAGE);return n}function Mg(e,t,n,r,o){let i=V(e,t,n);if(i===void 0)return{value:void 0,warnings:[]};let a=bi(r,i,o);return{value:a.value,warnings:a.warnings}}async function U0(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:i,status:a,statusExplicit:s,nowValue:c,author:m}=e,p=e.dependencyValues;if(i===void 0)return{dependencyValues:p,status:a};let u=ze(i,n.id_prefix),f=await z(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:p,status:a};if((p??[]).some(h=>h.id===f.id&&h.kind==="blocked_by")||(p=[...p??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),s)return{dependencyValues:p,status:a};let _=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((h,g)=>h.localeCompare(g))[0]??o.open_status;return{dependencyValues:p,status:_}}function G0(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let r=t.governance.create_default_type?.trim();if(r&&r.length>0&&ke(r,n)){e.type=r;return}ke("Task",n)&&(e.type="Task")}function j0(e,t){return e.options.filter(n=>nr("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function q0(e,t,n,r,o){let i=e,a=[];if(i.template!==void 0){let h=i.template.trim();if(h.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let g=await P0(h,t,n);i=Ug(I0(g,i))}if(i.type===void 0&&G0(i,r,o),i.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let s=ke(i.type,o);if(!s){let h=Wu(i.type),g=h?ke(h,o):void 0;if(g)a.push(`type_coercion:${i.type.trim()}:${g}`),i.type=g,s=g;else throw new l(Rt(i.type,o.types,Ot(n,r.schema)),d.USAGE)}let c=po(s,o);if(!c)throw new l(`Invalid type value "${i.type}"`,d.USAGE);let m=c.name,p=j0(c,i),u=p.map(h=>`${h.key}=${String(i[h.key])}`);if(u.length>0){i.typeOption=[...u,...i.typeOption??[]];for(let h of p)delete i[h.key]}let f=v0(i.schedulePreset);if(f!==void 0&&!Dg.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=b0(i.createMode,f,r.governance.create_mode_default);return{resolvedOptions:i,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:a}}function K0(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let i of o)if(i.enabled){if(i.values&&i.values.length>0)throw new l(`Cannot combine ${i.clearFlag} with ${i.valueFlag}`,d.USAGE);n.add(i.metadataKey),r.add(i.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function z0(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=va.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Ae("create",r)}`,d.USAGE)}}function H0(e){let t=(n,r)=>{let o=va.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;na(n,Ae("create",r),i)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function B0(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,d.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,d.USAGE)}var zg={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function V0(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:i,type:a,createMode:s,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(h=>{let g=h.type==="boolean"?"<true|false>":h.type==="array"?"<json-array>":h.type==="object"?"<json-object>":h.type==="number"?"<number>":h.type==="string_array"||h.repeatable?"<value>":"<string>";return{example:`--${h.cli_flag} ${g}`,description:`--${h.cli_flag} maps to ${h.metadata_key} (${h.type}${h.repeatable?", repeatable":""})`}}),p=[qg(n,r,o,i),...m.map(h=>h.example)].join(" "),u=[`Run "pm create --help --type ${a}" for type-aware required option guidance.`,...t.filter(h=>h==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+a+").")];s==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),Dg.has(a)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&u.push(`Required custom field formats: ${m.map(h=>h.description).join("; ")}.`);let f=[...new Set(t.flatMap(h=>{let g=h.split(" ",1)[0],y=zg[g];return y?[y]:[]}))];f.length>0&&u.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let _=t.length===1?`Missing required option ${t[0]} for type "${a}"`:`Missing required options ${t.join(", ")} for type "${a}"`;throw new l(_,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${a}" in one invocation.`,examples:[...f.map(h=>`pm create --type ${a} ${h} ...`),p],nextSteps:u,recovery:s==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function W0(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Pt(t.tags):[];return Ln(n,t.addTags)}function Y0(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new l("--order and --rank must match when both are provided",d.USAGE);let n=t.order??t.rank,r=un(e,"order",n,o=>fe(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function J0(e,t,n,r,o,i){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",d.USAGE);let a=e!==t.close_status?void 0:r.completedAt===void 0?i:ie(r.completedAt,new Date(i),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:a,warnings:[]};let s=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:Hc(s,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:a,warnings:[]}}async function X0(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:i,author:a,extensionFieldNames:s,afterDocument:c,beforeDocument:m,historyMessage:p,changedFields:u,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,g=dt(t,n,r,o.item_format,i.type_to_folder),y=tt(t,r),w=Mt(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(P=>w.resolve(P.kind)?.hierarchy),S=await Ji({pmRoot:t,author:a,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:b}),T=b,L=[];try{let P=await Te(t,r,o.locks.ttl_seconds,a,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let M=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await _e(t,o.item_format,i.type_to_folder,void 0,o.schema):void 0,K=await z(t,r,o.id_prefix,o.item_format,i.type_to_folder);if(K)throw new l(`Item "${r}" already exists`,d.CONFLICT,{code:"item_already_exists",id:K.id,path:K.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${K.id}.`]});if(M){let de=$(o.schema);Ai(M,[...M,c.metadata],r,qe=>re(qe,de),w)}let H=await yr({pmRoot:t,settings:o,operation:"create",author:a,before:null,after:c});await Wo({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:ki({pmRoot:t,settings:o,typeToFolder:i.type_to_folder})});let Z=await $t(t,a,{required:o.governance.duplicate_detection_mode==="strict"&&h!==!0}),le=[];try{o.governance.duplicate_detection_mode==="strict"&&h!==!0&&await qn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await te(g,Ve(c,{format:o.item_format,schema:o.schema,extensionFieldNames:s}));try{let de=$e({nowIso:f,author:a,op:"create",before:m,after:c,message:p,context:H.decisions.length===0?void 0:{workflow_policies:H.decisions}});await xt(y,de)}catch(de){throw await En(g),de}T&&(await S(),T=!1),le=await Ft({pmRoot:t,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:g,document:c})}finally{await Z()}L=[...H.warnings,...M?Gi(M,[...M,c.metadata],r):[],...le,...await Y({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:u}),...await Y({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:u})],In({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Qt(c.metadata,u),changed_fields:u})}finally{await P()}}finally{T&&await S()}return L}async function Gt(e,t){let n=Ug(await y0(e)),r=E(process.cwd(),t.path);await I(r);let o=await A(r),i=$(o.schema),a=nt(o.schema),s=x(o,O()),c=await q0(n,t,r,o,s);n=c.resolvedOptions;let{typeDefinition:m,type:p,createMode:u}=c,f=i0(n.unset,a),{explicitUnsets:_,clearOptionKeys:h}=K0(n,f);z0(n,f),H0(n);let g=C(ve(n.author),o.author_default),y=k0(m,n,u,h,g),w=k(),b=a0(n.dep,w,o.id_prefix,g),S=fn("--comment",n.comment,w,g),T=fn("--note",n.note,w,g),L=fn("--learning",n.learning,w,g),P=rl(n.file),M=ol(n.test);M.values=await zn(M.values,g,w);let K=il(n.doc),H=c0(n.reminder,w),Z=l0(n.event,w),le=h0(n.typeOption),de=rr(p,le.values,s),qe=O(),j=Tt(qe),ue=co(n.field,qe),Ze=yu(n,a,p),es=new Set(Ze.missing_required_flags),ts=a.definitions.filter(W=>es.has(`--${W.cli_flag}`));B0(ue,Ze,f);let tr=S0(de.errors,p),zt=tr.map(W=>`--type-option ${W}=<value>`),Zr=[...new Set([...y,...zt,...Ze.missing_required_flags])].sort((W,ls)=>W.localeCompare(ls));V0({combinedMissingFlags:Zr,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:tr,openStatus:i.open_status,type:p,createMode:u,missingRequiredRuntimeFields:ts}),A0(de.errors,p,m,i);let Ke=await D0({pmRoot:r,settings:o,typeRegistry:s,explicitId:n.id}),St=n.status!==void 0?n0(n.status,i):r0(m,i),eo=n.priority!==void 0?Fn(n.priority):2,R=f.metadataKeys,Ht=W0(R,n),bn=un(R,"deadline",n.deadline,W=>ie(W,new Date(w),"deadline")),Et=un(R,"estimated_minutes",n.estimatedMinutes,W=>$n(W,"estimated-minutes")),ns=V(R,"acceptance_criteria",n.acceptanceCriteria),et=V(R,"definition_of_ready",n.definitionOfReady),rs=Y0(R,n),to=V(R,"goal",n.goal),hb=V(R,"objective",n.objective),gb=V(R,"value",n.value),yb=V(R,"impact",n.impact),wb=V(R,"outcome",n.outcome),vb=V(R,"why_now",n.whyNow),bb=V(R,"assignee",n.assignee),kb=R.has("author")?void 0:ve(n.author)??g,Sb=V(R,"parent",n.parent),Id=await $0(Sb,n,R,r),os=Id.parent,Eb=Id.parentSource,Ab=V(R,"reviewer",n.reviewer),Tb=un(R,"risk",n.risk,W=>xe(Xi(W),kn,"risk")),Cb=un(R,"confidence",n.confidence,W=>Zi(W)),Ib=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Rd=o.validation.sprint_release_format,Bt=[...c.warnings,...L0(p,Ke,bn,H.values,Z.values)],Od=await M0({itemId:Ke,parent:os,pmRoot:r,settings:o,typeRegistry:s,policy:Ib});os=Od.parent,Bt.push(...Od.warnings);let xd=Mg(R,"sprint",n.sprint,"sprint",Rd),Rb=xd.value;Bt.push(...xd.warnings);let Pd=Mg(R,"release",n.release,"release",Rd),Ob=Pd.value;Bt.push(...Pd.warnings);let Nd=V(R,"blocked_by",n.blockedBy),Ld=await U0({pmRoot:r,settings:o,typeRegistry:s,statusRegistry:i,blockedBy:Nd,dependencyValues:b.values,status:St,statusExplicit:n.status!==void 0,nowValue:w,author:g}),is=Ld.dependencyValues;Ur(Ke,is),Bt.push(...await pn({pmRoot:r,dependencies:is,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:s.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ke,createdAt:w}],schema:o.schema})),St=Ld.status;let xb=V(R,"blocked_reason",n.blockedReason),Pb=V(R,"unblock_note",n.unblockNote),Nb=V(R,"reporter",n.reporter),Lb=un(R,"severity",n.severity,W=>xe(Qi(W),Sn,"severity")),$b=V(R,"environment",n.environment),Fb=V(R,"repro_steps",n.reproSteps),$d=V(R,"resolution",n.resolution),Mb=V(R,"expected_result",n.expectedResult),Db=V(R,"actual_result",n.actualResult),Ub=V(R,"affected_version",n.affectedVersion),Gb=V(R,"fixed_version",n.fixedVersion),jb=V(R,"component",n.component),qb=un(R,"regression",n.regression,W=>ea(W)),Kb=V(R,"customer_impact",n.customerImpact),as=al(n.title,"--title"),ss=n.description??"",no=n.body??"",Fd=await qn({title:as,description:ss,body:no},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Bt.push(...Pi(Fd));let cs=J0(St,i,o,n,$d,w),zb=cs.closeReason,Hb=St===i.close_status?w:void 0,Bb=cs.completedAt;Bt.push(...cs.warnings);let ro=Ks({id:Ke,title:as,description:ss,type:p,type_options:de.normalized,status:St,closed_at:Hb,completed_at:Bb,close_reason:zb,priority:eo,tags:Ht,created_at:w,updated_at:w,deadline:bn,assignee:bb,author:kb,estimated_minutes:Et,acceptance_criteria:ns,definition_of_ready:et,order:rs,goal:to,objective:hb,value:gb,impact:yb,outcome:wb,why_now:vb,parent:os,reviewer:Ab,risk:Tb,confidence:Cb,sprint:Rb,release:Ob,blocked_by:Nd,blocked_reason:xb,unblock_note:Pb,reporter:Nb,severity:Lb,environment:$b,repro_steps:Fb,resolution:$d,expected_result:Mb,actual_result:Db,affected_version:Ub,fixed_version:Gb,component:jb,regression:qb,customer_impact:Kb,dependencies:is,comments:S.values,notes:T.values,learnings:L.values,files:P.values,tests:M.values,docs:K.values,reminders:H.values,events:Z.values,...ue,...Ze.values});try{lo(ro,qe)}catch(W){throw new l(W instanceof Error?W.message:"Invalid extension item field values",d.USAGE)}let Vb=rt({metadata:ro,body:no},{schema:o.schema,extensionFieldNames:j}),Wb={metadata:{},body:""},Md=[..._].sort((W,ls)=>W.localeCompare(ls)),Yb=m0(n.message,Md),Dd=d0(ro,no,Md,[...Object.keys(ue),...Object.keys(Ze.values??{})]),Jb=await X0({pmRoot:r,type:p,id:Ke,settings:o,typeRegistry:s,author:g,extensionFieldNames:j,afterDocument:Vb,beforeDocument:Wb,historyMessage:Yb,changedFields:Dd,nowValue:w,similarityCandidate:{title:as,description:ss,body:no},allowDuplicate:n.allowDuplicate}),Ud=structuredClone(ro);u==="strict"&&_.has("dependencies")&&(Ud.dependencies=[]);let Xb=wg(Ke,p,St,i);return Kg(p,bn,H.values,Z.values)&&Qp(`[pm] warning: ${p} '${Ke}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ke} --deadline <ISO>' or 'pm update ${Ke} --event "start=<ISO>,end=<ISO>"'.`),{item:Ud,changed_fields:Dd,warnings:[...Bt,...Jb],...Object.fromEntries([["parent_source",Eb],["next_transition",Xb],["similarity_advisory",Fd]].filter(W=>W[1]!==void 0))}}import Sa from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d29ab3a3-319f-506f-8289-78d786b95255")}catch{}})();async function sl(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),i=C(t.author,o.author_default),a=await tf({pmRoot:r,settings:o,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),s=a.targetPath?Sa.relative(r,a.targetPath).split(Sa.sep).join("/"):void 0;return{item:a.item,changed_fields:a.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:a.item.status,...s?{target_path:s}:{},history_retained:Sa.relative(r,tt(r,a.item.id)).split(Sa.sep).join("/"),tombstone_retention:"retain_append_only",warnings:a.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c7047beb-5c3a-5d97-acb9-7ddd15a223ec")}catch{}})();async function Q0(e){await I(e)}async function cl(e,t,n){let r=E(process.cwd(),n.path);if(await Q0(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",d.USAGE);let p=await A(r),u=Pn(C(void 0,p.author_default));return await gu(r),await ji({pmRoot:r,settings:p,principal:u}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await ni(r);if(p===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let u=await Z0(r,p);return{action:"show",focused_item:p,title:u,message:`Focused on ${p}${u?` (${u})`:""}. New items default --parent to it.`}}let o=await A(r),i=x(o,O()),a=await z(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await _t(r,e,o.id_prefix,i.type_to_folder);let s=ze(a.id,o.id_prefix),c=await ae(a,{schema:o.schema}),m=Hg(c.document.metadata.title);return await hu(r,s),await ji({pmRoot:r,settings:o,principal:Pn(C(void 0,o.author_default)),itemId:s}),{action:"set",focused_item:s,title:m,message:`Focused on ${s}${m?` (${m})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function Z0(e,t){let n=await A(e),r=x(n,O()),o=await z(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let i=await ae(o,{schema:n.schema});return Hg(i.document.metadata.title)}function Hg(e){return e.trim().length>0?e:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="961c1918-75f9-5e5d-bbae-b333ca29534f")}catch{}})();function Ea(e){return Ho("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9ee587b5-5aa8-5d10-89d7-acc4a5edb53f")}catch{}})();var pl=[...Jc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Xc,...fa],eI=(()=>{let e=new Map;for(let t of pl)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Aa=new Map(pl.map(e=>[e.optionKey,e.canonical])),tI=pl.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),nI=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),rI=ta({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Zg(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i},r=new Set([...Aa.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!Je(i))continue;let a=o==="rank"?"order":Aa.get(o)??o;n(a),t[o]=void 0}return Ie(e,ra(t,rI))}function ey(e,t,n=[]){return _a({raw:e,supportedFields:tI,resolveDefinition:r=>{let o=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return eI.get(r)??ha(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var Bg=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function Vg(e){let t=e.disallowedFlags.flatMap(r=>{let o=Bg.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=Bg.get(r);return o?[`Replace ${r} with: ${o(e.id)}`]:[]});return new l(e.message,d.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function oI(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let i=(c,m,p)=>{c&&p.push(m)};if(o){let c=[];if(i(t.title!==void 0,"--title",c),i(t.description!==void 0,"--description",c),i(t.body!==void 0,"--body",c),i(t.status!==void 0,"--status",c),i(t.closeReason!==void 0,"--close-reason",c),i(t.priority!==void 0,"--priority",c),i(t.type!==void 0,"--type",c),i(t.tags!==void 0,"--tags",c),i(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),i(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),i(t.deadline!==void 0,"--deadline",c),i(t.estimatedMinutes!==void 0,"--estimate",c),i(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),i(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),i(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),i(t.definitionOfReady!==void 0,"--definition-of-ready",c),i(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),i(t.goal!==void 0,"--goal",c),i(t.objective!==void 0,"--objective",c),i(t.value!==void 0,"--value",c),i(t.impact!==void 0,"--impact",c),i(t.outcome!==void 0,"--outcome",c),i(t.whyNow!==void 0,"--why-now",c),i(t.assignee!==void 0,"--assignee",c),i(t.parent!==void 0,"--parent",c),i(t.reviewer!==void 0,"--reviewer",c),i(t.risk!==void 0,"--risk",c),i(t.confidence!==void 0,"--confidence",c),i(t.sprint!==void 0,"--sprint",c),i(t.release!==void 0,"--release",c),i(t.blockedBy!==void 0,"--blocked-by",c),i(t.blockedReason!==void 0,"--blocked-reason",c),i(t.unblockNote!==void 0,"--unblock-note",c),i(t.reporter!==void 0,"--reporter",c),i(t.severity!==void 0,"--severity",c),i(t.environment!==void 0,"--environment",c),i(t.reproSteps!==void 0,"--repro-steps",c),i(t.resolution!==void 0,"--resolution",c),i(t.expectedResult!==void 0,"--expected-result",c),i(t.actualResult!==void 0,"--actual-result",c),i(t.affectedVersion!==void 0,"--affected-version",c),i(t.fixedVersion!==void 0,"--fixed-version",c),i(t.component!==void 0,"--component",c),i(t.regression!==void 0,"--regression",c),i(t.customerImpact!==void 0,"--customer-impact",c),i(t.depRemove!==void 0,"--dep-remove",c),i(t.replaceDeps===!0,"--replace-deps",c),i(t.replaceTests===!0,"--replace-tests",c),i(t.replaceFiles===!0,"--replace-files",c),i(t.replaceDocs===!0,"--replace-docs",c),i(t.comment!==void 0,"--comment",c),i(t.note!==void 0,"--note",c),i(t.learning!==void 0,"--learning",c),i(t.file!==void 0,"--file",c),i(t.test!==void 0,"--test",c),i(t.doc!==void 0,"--doc",c),i(t.reminder!==void 0,"--reminder",c),i(t.event!==void 0,"--event",c),i(t.typeOption!==void 0,"--type-option",c),i(t.clearDeps===!0,"--clear-deps",c),i(t.clearComments===!0,"--clear-comments",c),i(t.clearNotes===!0,"--clear-notes",c),i(t.clearLearnings===!0,"--clear-learnings",c),i(t.clearFiles===!0,"--clear-files",c),i(t.clearTests===!0,"--clear-tests",c),i(t.clearDocs===!0,"--clear-docs",c),i(t.clearReminders===!0,"--clear-reminders",c),i(t.clearEvents===!0,"--clear-events",c),i(t.clearTypeOptions===!0,"--clear-type-options",c),i(t.force===!0,"--force",c),i(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw Vg({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let a=[];i(t.status!==void 0,"--status",a),i(t.closeReason!==void 0,"--close-reason",a),i(t.assignee!==void 0,"--assignee",a),i(t.parent!==void 0,"--parent",a),i(t.blockedBy!==void 0,"--blocked-by",a),i(t.blockedReason!==void 0,"--blocked-reason",a),i(t.unblockNote!==void 0,"--unblock-note",a),i(t.dep!==void 0,"--dep",a),i(t.depRemove!==void 0,"--dep-remove",a),i(t.replaceDeps===!0,"--replace-deps",a),i(t.replaceTests===!0,"--replace-tests",a),i(t.replaceFiles===!0,"--replace-files",a),i(t.replaceDocs===!0,"--replace-docs",a),i(t.note!==void 0,"--note",a),i(t.learning!==void 0,"--learning",a),i(t.test!==void 0,"--test",a),i(t.reminder!==void 0,"--reminder",a),i(t.event!==void 0,"--event",a),i(t.clearDeps===!0,"--clear-deps",a),i(t.clearComments===!0,"--clear-comments",a),i(t.clearNotes===!0,"--clear-notes",a),i(t.clearLearnings===!0,"--clear-learnings",a),i(t.clearFiles===!0,"--clear-files",a),i(t.clearTests===!0,"--clear-tests",a),i(t.clearDocs===!0,"--clear-docs",a),i(t.clearReminders===!0,"--clear-reminders",a),i(t.clearEvents===!0,"--clear-events",a);let s=[...n].filter(c=>nI.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(a.push(...s),a.length>0)throw Vg({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${a.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:a})}function iI(e,t){let n=ee(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function aI(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Rp({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=ee(e.fromStatus,e.statusRegistry)??e.fromStatus,r=ee(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Op(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,d.USAGE);return`workflow_transition_not_allowed: ${o}`}function sI(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:ty(e)}function ty(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(t).toISOString()}function Wn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var cI=["id","kind","type","author","created_at","source_kind"],lI=["id","kind","type","author","created_at","source_kind"];function ny(e){return e.startsWith("```")||e.includes(`
22
- `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:ui(e)}function ry(e){return typeof e=="string"?mo(e)??e.trim():e}function Ca(e,t,n,r){return e?(Oe(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=ny(i);Dr(i,a);let s=a?me(o,"--dep"):{id:i,kind:"related"};a&&Ye(s,"--dep",cI);let c=s.id?.trim(),m=ry((s.kind??s.type)?.trim());if(!c||!m)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",d.USAGE);if(c.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=vr(Wn(s.source_kind)),u=Wn(s.author);return{id:br(c,t,p),kind:xe(m,Vt,"dependency kind","kind"),created_at:sI(s.created_at,n),author:u??r,source_kind:p??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function dI(e,t){return e?(Oe(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new l("--dep-remove requires id or key/value selectors",d.USAGE);let o=ny(r);if(Dr(r,o,"--dep-remove"),o){let i=me(r,"--dep-remove");Ye(i,"--dep-remove",lI);let a=i.id?.trim();if(!a)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(a.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${a}"`,d.USAGE);let s=ry(Wn(i.kind??i.type)),c=vr(Wn(i.source_kind)),m=Wn(i.author),p=Wn(i.created_at);return{id:br(a,t,c),kind:s?xe(s,Vt,"dependency kind","kind"):void 0,source_kind:c,author:m,created_at:p?ty(p):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:ze(r,t)}})):[]}function Ta(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function mI(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),i=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,i].join("\0")}function pI(e,t,n,r){let o=[...e??[]],i=!1;if(t===void 0){let a=o.filter(s=>s.kind!=="blocked_by");return a.length!==o.length&&(o=a,i=!0),i?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(a=>a.kind==="blocked_by"&&a.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),i=!0),i?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function uI(e,t,n,r,o,i){if(e===void 0||t)return{};let a=e.trim();if(a.length===0)return{};let s=await z(n,ze(a,r),r,o,i);return s?{id:s.id}:{unresolved:a}}function fI(e,t,n,r,o){let i=pI(e.dependencies,t,n,r);i.changed&&(i.dependencies===void 0?delete e.dependencies:e.dependencies=i.dependencies,o.includes("dependencies")||o.push("dependencies"))}function _I(e){return`${e.path}::${e.scope}`}function hI(e){return`${e.path}::${e.scope}`}function gI(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function oy(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function Wg(e,t){let n=nr("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function yI(e,t,n){let r=new Set,o=(i,a)=>{a&&r.add(i)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let i=ey(e.unset,t,n);for(let a of i.optionKeys)o(a,!0)}return r}function wI(e,t,n,r,o){let i=po(e,n);if(!i)throw new l(`Invalid type value "${e}"`,d.USAGE);let a=Tn(i,"update",[]);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);let s=yI(t,r,o);for(let c of a.disabled)if(s.has(Wg(c,e)))throw new l(`Option ${Ae("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of a.required)if(!s.has(Wg(c,e)))throw new l(`Missing required option ${Ae("update",c)} for type "${e}"`,d.USAGE)}var vI=new Set(["order","rank"]),bI=vs.filter(e=>!vI.has(e)),iy=["tags","closeReason",...bI],kI=["title","description","body","status","closeReason","completedAt","priority","type",...vs,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],SI=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>ie(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>$n(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],EI=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>xe(Xi(e),kn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Zi(e)}],AI=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>xe(Qi(e),Sn,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>ea(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function ml(e,t,n){for(let r of e){let o=t[r.optionKey],i=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!i)){if(i){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new l(`${Ae("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function TI(e){return Zg(await fi(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function ul(e){return ft(e)?await TI(e):Zg(e)}function CI(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function ll(e){if(e.enabled&&(!e.values||e.values.length===0))throw new l(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,d.USAGE);if(e.enabled&&e.clearEnabled)throw new l(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,d.USAGE)}function fl(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new l("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",d.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new l("--replace-deps requires at least one --dep entry",d.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new l("--replace-deps cannot be combined with --dep-remove",d.USAGE);ll({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),ll({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),ll({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function II(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new l(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,d.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function RI(e){let t={};for(let n of iy)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function OI(e,t){let n=RI(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=Aa.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Ae("update",r)}`,d.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --add-ac",d.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --remove-ac",d.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new l("Cannot combine --unset tags with --remove-tags",d.USAGE)}}function xI(e){let t=(n,r)=>{let o=Aa.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;na(n,Ae("update",r),i)};for(let n of iy)t(e[n],String(n));t(e.order??e.rank,"order"),Oe(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Oe(e.event,"--event","Use --clear-events to clear linked events.")}function PI(e,t){let n={};for(let r of kI)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function NI(e){let t=await z(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ae(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function LI(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return _e(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function $I(e){e.before&&Ai(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>re(t,e.statusRegistry),Mt())}function FI(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new l("--order and --rank must match when both are provided",d.USAGE)}async function MI(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Ei(yi(e.options.parent),e.settings.id_prefix);if(Qo(t))return{resolvedParentValue:t,warnings:[]};if(vi(e.id,t,e.settings.id_prefix),await z(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let n=ze(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:wi(n,e.parentReferencePolicy).warnings}}function DI(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function UI(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await z(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ae(t,{schema:e.settings.schema}),r=e.options.type!==void 0?ke(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=aI({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function GI(e){if(!e.fieldFlags.status||ee(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let t=Object.entries(e.fieldFlags).filter(([a,s])=>s&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),n=[],r=[];if(t.length>0){let a=Ie(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),s=await at(e.id,a,e.global);r=s.changed_fields,n.push(...s.warnings)}let o=await wt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...e.workflowTransitionWarnings,...n,...o.warnings,"auto_routed_from_update_to_close"];return{item:o.item,changed_fields:[...r,...o.changed_fields],warnings:i}}function jI(e,t,n,r){return t.title!==void 0&&(e.metadata.title=al(t.title,"--title"),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),ee(e.metadata.status,n)??e.metadata.status}var qI=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function KI(e,t){for(let n of qI)e[n]!==void 0&&(delete e[n],t.push(n))}function zI(e,t,n,r,o){let i=iI(n,t.statusRegistry);if(e.metadata.status=i,o.push("status"),i===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!re(i,t.statusRegistry)&&re(r,t.statusRegistry)&&KI(e.metadata,o)}function HI(e,t,n,r){if(t.options.status!==void 0&&zI(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!re(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=ie(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function BI(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&re(n,t.statusRegistry)&&!re(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function VI(e,t,n,r){HI(e,t,n,r),BI(e,t,n,r)}function WI(e,t,n){let r=ke(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=Fn(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=ke(t.options.type,t.typeRegistry);if(!o)throw new l(Rt(t.options.type,t.typeRegistry.types,Ot(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=o,r=o,n.push("type")}return wI(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),YI(e,t,r,n),r}function YI(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let i=wa(t.options.typeOption??[]),a=rr(n,i,t.typeRegistry);if(a.errors.length>0)throw new l(a.errors.join("; "),d.USAGE);e.metadata.type_options=a.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let o=rr(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=o.normalized}function JI(e,t){let n=new Set(t.map(o=>Ta(o))),r=new Set;return e.filter(o=>{if(!n.has(Ta(o)))return!0;let i=mI(o);return r.has(i)?!1:(r.add(i),!0)})}function XI(e,t,n){let r=t.filter(o=>!e.some(i=>oy(i,o)));if(r.length!==0)throw new l(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,d.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function QI(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=JI(r,t.dependencyUpdates.additions);let o=new Set(r.map(i=>Ta(i)));for(let i of t.dependencyUpdates.additions){let a=Ta(i);o.has(a)||(r.push(i),o.add(a))}}t.dependencyRemovals.length>0&&(XI(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(i=>oy(o,i)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function ZI(e,t,n){dl(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),dl(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),dl(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function dl(e,t,n,r,o,i){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],i.push(t))}function eR(e,t,n){Yg(e,"files",t.options.file,t.fileUpdates.values,_I,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),tR(e,t,n),Yg(e,"docs",t.options.doc,t.docUpdates.values,hI,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Yg(e,t,n,r,o,i,a,s){if(!(n===void 0&&!a.has(t))){if(i)e.metadata[t]=r;else if(a.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(p=>o(p)));for(let p of r){let u=o(p);m.has(u)||(c.push(p),m.add(u))}e.metadata[t]=c}s.push(t)}}function tR(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Jg(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Jg([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Jg(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=gI(r);n.has(o)||(t.push(r),n.add(o))}return t}function nR(e,t,n){let r=t.options.addTags,o=t.options.removeTags,i=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||i){let a=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Pt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=pi(Ln(a,r),o),n.changedFields.push("tags")}ml(SI,t.options,n),oR(e,t,n.changedFields)}function rR(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let i=mi(Nn(e.metadata.acceptance_criteria),r,o);if(i.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${i.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:i.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let a=i.criteria.join("; ");e.metadata.acceptance_criteria!==a&&(a===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=a,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function oR(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=fe(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function iR(e,t,n,r){aR(e,t,n.changedFields),sR(e,t,n.changedFields),ml(EI,t.options,n),Xg(e,t,"sprint",r,n.changedFields),Xg(e,t,"release",r,n.changedFields),cR(e,t,n.changedFields),ml(AI,t.options,n)}function aR(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new l("--assignee must not be empty. Use --unset assignee to clear it.",d.USAGE);e.metadata.assignee=r}n.push("assignee")}}function sR(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function Xg(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let i=bi(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=i.value,r.push(...i.warnings)}o.push(n)}}function cR(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&fI(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function lR(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=ga(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=ya(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function dR(e,t,n){Qg(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),Qg(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,i]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let a=o.replaceAll("_","-"),s=t.runtimeFieldRegistry.definitions.find(c=>c.metadata_key===o)?.cli_flag??a;throw new l(`Cannot combine --unset ${a} with --${s}`,d.USAGE)}Le(e[o],i)||(e[o]=i,n.push(o))}let r=co(t.options.field,t.extensionRegistrations);for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new l(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,d.USAGE);for(let[o,i]of Object.entries(r))Le(e[o],i)||(e[o]=i,n.push(o))}function Qg(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function mR(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(o=>{let i=t[o];return i!==void 0&&(!Array.isArray(i)||!Le(i,n[o]??[]))});if(r!==void 0)throw new l(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,d.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${r}_requires_annotation_command`,required:`Use pm ${r} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${r} with pm ${r} ${e.metadata.id}.`,`Apply the correction with pm ${r} ${e.metadata.id} --edit <index> --add <text>.`]})}function pR(e,t){mR(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,o=[],i=[],a=jI(e,t.options,t.statusRegistry,o),s=e.metadata,c={metadataRecord:s,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};VI(e,t,a,o),WI(e,t,o),QI(e,t,o),ZI(e,t,o),eR(e,t,o),nR(e,t,c),rR(e,t,c),iR(e,t,c,i),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&Ur(e.metadata.id,e.metadata.dependencies),ee(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),lR(e,t,o),dR(s,t,o);try{lo(s,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(u){throw new l(u instanceof Error?u.message:"Invalid extension item field values",d.USAGE)}let m=e.metadata,p=[...new Set(o)].filter(u=>u==="body"?e.body!==r:!Le(n[u],m[u]));return t.options.acceptanceCriteria!==void 0&&p.includes("acceptance_criteria")&&i.push(`acceptance_criteria_replaced:${Nn(n.acceptance_criteria).length}:${Nn(m.acceptance_criteria).length}`),{changedFields:p,warnings:i}}async function ay(e,t,n,r={}){t=await ul(t);let o=E(process.cwd(),n.path);await I(o);let i=await A(o),a=$(i.schema),s=nt(i.schema),c=O(),m=Tt(c),p=x(i,c),u=i.governance.workflow_enforcement??"off",f=u==="off"?[]:Ip(i.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][i.validation.parent_reference],h=ey(t.unset,s,m),g=new Set(h.optionKeys),y=new Set(h.metadataKeys);fl(t),II({definitions:CI(t),options:t,clearOptionKeys:g,clearItemMetadataKeys:y}),oI(e,t,y),OI(t,h),xI(t);let w=C(t.author,i.author_default),b=new Date,S=b.toISOString(),T=Ca(t.dep,i.id_prefix,S,w);Ur(e,T.additions);let L=await pn({pmRoot:o,dependencies:T.additions,idPrefix:i.id_prefix,itemFormat:i.item_format,typeToFolder:p.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:i.schema}),P=dI(t.depRemove,i.id_prefix),M=fn("--comment",t.comment,S,w),K=t.ownershipMetadataBypass===!0&&M.values?{...M,values:M.values.map(R=>({...R,author:w}))}:M,H=fn("--note",t.note,S,w),Z=fn("--learning",t.learning,S,w),le=rl(t.file),de=ol(t.test);de.values=await zn(de.values,w,S);let qe=il(t.doc),j=[],ue=await MI({id:e,options:t,unsetTargets:h,pmRoot:o,settings:i,typeRegistry:p,parentReferencePolicy:_}),Ze=await uI(t.blockedBy,y.has("blocked_by"),o,i.id_prefix,i.item_format,p.type_to_folder),es=Ze.id,ts=[...ue.warnings,...DI(Ze)],tr=oi(t,s,t.runtimeFieldCommands),zt=PI(t,tr);if(!Object.values(zt).some(Boolean))return NI({pmRoot:o,id:e,settings:i,typeRegistry:p});j.push(...await UI({options:t,fieldFlags:zt,workflowEnforcement:u,typeWorkflows:f,statusRegistry:a,typeRegistry:p,pmRoot:o,id:e,settings:i}));let Zr=await GI({options:t,fieldFlags:zt,statusRegistry:a,workflowTransitionWarnings:j,global:n,id:e});if(Zr)return Zr;FI(t);let Ke=Mt(),St=zt.parent&&!y.has("parent")||T.additions.some(R=>Ke.resolve(R.kind)?.hierarchy),eo=await Ji({pmRoot:o,author:w,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:St});try{let R=await LI({fieldFlags:zt,clearedMetadataKeys:y,pmRoot:o,settings:i,typeToFolder:p.type_to_folder}),Ht,bn,Et=await ef({pmRoot:o,settings:i,typeToFolder:p.type_to_folder,id:e,op:uR(t,r),author:w,message:t.message,resolveHistoryContext:()=>bn,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(et){Ht=fR({document:et,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:a}),bn=Ht?{recurrence:Ht}:void 0,R=R?.map(to=>to.id===et.metadata.id?structuredClone(et.metadata):to);let rs=pR(et,{options:t,settings:i,typeRegistry:p,statusRegistry:a,runtimeFieldRegistry:s,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:y,dependencyUpdates:T,dependencyRemovals:P,commentUpdates:K,noteUpdates:H,learningUpdates:Z,fileUpdates:le,testUpdates:de,docUpdates:qe,resolvedParentValue:ue.resolvedParentValue,resolvedBlockedByDependencyId:es,runtimeFieldUpdates:tr,nowValue:b,nowIso:S,author:w,pmRoot:o});return $I({before:R,document:et,statusRegistry:a}),rs}});await eo();let ns=R?Gi(R,R.map(et=>et.id===Et.item.id?Et.item:et),Et.item.id):[];return{item:Et.item,changed_fields:Et.changedFields,warnings:[...j,...ts,...L,...ns,...Et.warnings],...Ht===void 0?{}:{lifecycle_transition:Ht}}}finally{await eo()}}function uR(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function fR(e){if(e.recurrenceReason===void 0)return;let t=ee(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!re(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,d.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=ee(n,e.statusRegistry)??n,o=e.document.metadata,i=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(a=>{let s=o[a];return typeof s=="string"?[[a,s]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:i}}async function at(e,t,n){return ay(e,t,n)}async function sy(e,t,n,r){let o=await ay(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,d.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="90a2e91a-50cf-5ad9-87ef-fa95cabf125d")}catch{}})();async function _l(e,t,n,r){let o=t.trim();if(o.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",d.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let i=E(process.cwd(),r.path),a=$((await A(i)).schema),s=a.open_status,c=Ea(a),m=n.status??s,p=ee(m,a)??m;if(p!==s&&p!==c)throw new l(`Reopen target status must be ${s} or ${c}; received ${m}.`,d.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([s,c])],suggested_retry:`pm item reopen ${e} "${o}" --status ${s}`,suggested_retry_args:["item","reopen",e,o,"--status",s]}});let u=await sy(e,{status:p,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:u.item,changed_fields:u.changed_fields,warnings:u.warnings,recurrence:u.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="56177893-3ccb-5b3f-aa82-9365c26c5d34")}catch{}})();async function cy(e,t,n){return[...await Promise.resolve().then(()=>Tu(tt(e,t),t)).catch(()=>[])].reverse().find(r=>r.patch.some(o=>o.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ce03100c-3a4f-5ce4-a216-a3fabcfc655e")}catch{}})();var ly="no_available_next_item";function dy(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function Gr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let i=await A(o),a=$(i.schema),s=C(r.author,i.author_default),c=Pn(s),m=null,p=!1,u=[],f=await se({pmRoot:o,settings:i,id:e,op:"claim",author:s,message:r.message,force:t,skipNoop:!0,async mutate(_){let h=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||h;if(m=h.trim().length>0?h:null,Sp(_.metadata.status,a)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&g!==c){if(r.ifAvailable===!0)return p=!0,u.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let b=await cy(o,_.metadata.id,h);throw new l(`Item ${_.metadata.id} is already ${b}. Use --force to take over, or --if-available to skip without failing.`,d.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."]})}u.push(`claim_takeover:${m}->${s}`)}let y={assignee:s,claim_principal:c},w=["assignee","claim_principal"].filter(b=>_.metadata[b]!==y[b]);return Object.assign(_.metadata,y),{changedFields:w,warnings:u}}});return p||await yc({pmRoot:o,settings:i,principal:c,itemId:f.item.id}),{item:f.item,changed_fields:f.changedFields,claimed_by:p&&m!==null?m:s,previous_assignee:m,forced:t,...p?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function my(e,t,n={},r={}){let o=_R(n.maxAttempts),i=await A(E(process.cwd(),t.path)),a={...n,author:C(n.author,i.author_default)},s=await Ir({...r,callerAuthor:a.author,limit:String(o)},t),c=[s.recommended,...s.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return hR(c.slice(0,o),e,t,a)}function _R(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new l("--max-attempts must be an integer from 1 to 100",d.USAGE);return t}async function hR(e,t,n,r={},o=Gr){let i=0;for(let s of e){i+=1;try{let c=await o(s.id,t,n,r),m={...c,recommendation:s,attempts:i,available:!0};if(!c.skipped)return m}catch(c){if(!dy(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:C(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:i,warnings:[ly]};let a=i===0;throw new l(a?"No actionable items matched the selection filters":"No actionable item remained available to claim",a?d.NOT_FOUND:d.CONFLICT,{code:ly,why:a?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[a?"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 jr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let i=await A(o),a=C(r.author,i.author_default),s=Pn(a),c=r.ownershipReleaseBypass===!0,m=null,p;try{p=await se({pmRoot:o,settings:i,id:e,op:"release",author:a,message:r.message,force:t,bypassAssigneeConflict:c,mutate(_){return m=_.metadata.assignee??null,!m&&!_.metadata.claim_principal?{changedFields:[]}:(delete _.metadata.assignee,delete _.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(_){Nr(_,{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 wc({pmRoot:o,principal:s,itemId:p.item.id});let u=$(i.schema),f=qs(p.item.status,u)===qs(u.in_progress_status,u);return{item:p.item,released_by:a,changed_fields:p.changedFields,previous_assignee:m,forced:t,...f?{warnings:["released_unclaimed_in_progress"],suggestions:[`${p.item.id} remains ${p.item.status} and unclaimed. If work is paused, run pm release ${p.item.id} --pause to move it to ${u.open_status}.`]}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69182e8d-b8c7-5b70-8650-185a8f07f6ee")}catch{}})();async function hl(e,t,n){try{return await n()}catch(r){let o=r instanceof l?r.context:{},i=new l(r instanceof Error?r.message:String(r),r instanceof l?r.exitCode:d.GENERIC_FAILURE,{...o,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${o.why?` ${o.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...o.nextSteps??[]]});throw i.cause=r,i}}async function gl(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new l("--start cannot be combined with --next or --if-available for an explicit item",d.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let r=await A(E(process.cwd(),n.path)),o=Ea($(r.schema)),i=await Gr(e,t.force===!0,n,t),a=i.item.id,s=await hl(a,"claim",()=>at(a,Dt(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:a,action:"start_task",claim:i,update:s}}async function yl(e,t,n){let r=await A(E(process.cwd(),n.path)),o=$(r.schema).open_status,i=await at(e,Dt(t,{status:o},["assignee","pause"]),n),a=i.item.id,s=await hl(a,"update",()=>jr(a,t.force===!0,n,t));return{id:a,action:"pause_task",update:i,release:s}}async function wl(e,t,n,r){let o=await wt(e,t,n,r),i=o.item.id,a=await hl(i,"close",()=>jr(i,n.force===!0,r,n));return{id:i,action:"close_task",close:o,release:a}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="140b50c9-b0b3-5446-8ef9-5993bf4d830c")}catch{}})();async function py(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options),o=e.force===!0||r.force===!0,i={...e.args,...r};if(i.start===!0)return _n(e,"start_task");let a=e.args.next===!0||r.next===!0?await my(o,e.global,i,i):await Gr(qr(e,r),o,e.global,i);return Ee(a,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function qr(e,t){let n=e.id??v(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function vl(e,t){return v(e.args,"reason")??v(e.args,"text")??v(t,"reason")??v(t,"text")}async function uy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return r.releaseAssignment===!0?_n(e,"close_task"):Ee(await wt(qr(e,r),vl(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function _n(e,t){let{changedFields:n,idOnly:r,runnerOptions:o}=he(e.args,e.options),i=qr(e,o),a=Dt(o,{force:e.force===!0||o.force===!0}),s=t==="start_task"?await gl(i,a,e.global):t==="pause_task"?await yl(i,a,e.global):await wl(i,vl(e,o),a,e.global);return Ee(s,{changedFields:n,idOnly:r,compactEnvelope:n==="compact"&&!r})}async function fy(e){if(e.options.pause===!0)return _n(e,"pause_task");let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options),o=await jr(qr(e,r),e.force===!0,e.global,r);return Ee(o,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function _y(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return Ee(await _l(qr(e,r),vl(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a610a47-2af8-51b7-a8ab-2557eaf611e2")}catch{}})();function Ia(e,t){let n=Zt(["plan","show",e.plan.id,"--depth","deep",...t===void 0?[]:["--pm-path",t]]);return{kind:"plan_mutation",action:e.action,id:e.plan.id,status:e.plan.status,mode:e.plan.mode,steps_summary:e.plan.steps_summary,...e.step===void 0?{}:{step:{id:e.step.id,order:e.step.order,status:e.step.status}},materialized_count:e.materialized?.length??0,skipped_count:e.materialize_skipped?.length??0,warning_count:e.warnings.length,warnings:e.warnings.slice(0,3).map(r=>r.slice(0,160)),warnings_truncated:e.warnings.length>3||e.warnings.some(r=>r.length>160),next_action:e.next_actions?.[0]===void 0?n:t===void 0?e.next_actions[0]:`${e.next_actions[0]} --pm-path ${Kp(t)}`,inspection_command:n,omission_receipt:{has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"plan_detail",restore_with:n}]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1e5721e-92fd-5c2e-989f-d63892ed9d90")}catch{}})();var gR=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],hy=["brief","standard","deep"],wy="plan-step-",Tl="draft",Al=["bug-investigation","feature-implementation","refactoring-sprint"],gy={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function yR(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(gy,t)?gy[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${Al.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Al[0]}`]});return n.map(r=>({...r}))}function wR(e,t){return t>0?Math.round(e/t*100):0}function vy(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(t=>t!=null).map(t=>(typeof t=="string"?t:String(t)).trim()).filter(t=>t.length>0)}function He(e){return Array.isArray(e)?e.flatMap(t=>Un(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Un(e,{unique:!1}):[]}function Pe(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function by(e,t=Tl){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ps.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${ps.join(", ")}`,d.USAGE);return r}function Cl(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=us.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${us.join(", ")}`,d.USAGE);return r}function ky(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=_s.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${_s.join(", ")}`,d.USAGE);return r}function vR(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=fs.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${fs.join(", ")}`,d.USAGE);return n}function bR(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=hy.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${hy.join(", ")}`,d.USAGE);return n}function kR(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new l("Plan --fields requires a comma-separated list of plan field names",d.USAGE);return t}var bl=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function SR(e,t){let n=e,r={},o=[];for(let i of t){let a=i.startsWith("plan.")?i.slice(5):i;if(a.length!==0){if(!bl.has(a)){o.push(i);continue}Object.prototype.hasOwnProperty.call(n,a)&&(r[a]=n[a])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...bl].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...bl].join(",")}`}});return r}function Il(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let i=o.indexOf("=");if(i<=0)throw new l(`Invalid ${t} entry "${o}"; expected key=value`,d.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[o.slice(0,i).trim().toLowerCase()]=o.slice(i+1).trim()}return n}function Rl(e){let t=Il(e,"--file");if(!t.path)throw new l("--file requires path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function Ol(e){let t=Il(e,"--test");if(!t.command&&!t.path)throw new l("--test requires at least command=<value> or path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function xl(e){let t=Il(e,"--doc");if(!t.path)throw new l("--doc requires path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function ER(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=wR(t.completed,t.total),t}function AR(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${wy}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new l("Could not allocate step id (limit reached)",d.GENERIC_FAILURE)}function Yn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),i=e.find(a=>a.order===o);if(i)return i}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function yy(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function TR(e,t){let n=t.filter(a=>a.trim().toLowerCase()==="all"),r=[],o=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",d.USAGE);for(let a of e.slice().sort((s,c)=>s.order-c.order)){let s=yy(a);if(s){o.push({from_step:a.id,...s});continue}r.push(a)}return{targets:r,skipped:o}}let i=new Set;for(let a of t){let s=Yn(e,a);if(i.has(s.id))continue;i.add(s.id);let c=yy(s);if(c){o.push({from_step:s.id,...c});continue}r.push(s)}return{targets:r,skipped:o}}function CR(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function IR(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function RR(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function Ue(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((a,s)=>a.order-s.order),r=ER(n),o=IR(n),i={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Tl,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:RR(n),linked_items:(e.dependencies??[]).map(a=>({id:a.id,kind:a.kind}))};return(t==="standard"||t==="deep")&&(i.steps=n),t==="deep"&&(i.decisions=e.plan_decisions??[],i.discoveries=e.plan_discoveries??[],i.validation=e.plan_validation??[]),i}function Ge(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!tc(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function Sy(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new l(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,d.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function OR(e){let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n}}async function Ey(e,t){let n=x(e.settings,O()),r=await z(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,d.NOT_FOUND);let o=await ae(r,{schema:e.settings.schema});return Sy(o.document.metadata),{document:o.document,itemId:r.id}}function xR(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of He(e.related))t.push(`id=${n},kind=related`);for(let n of He(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of He(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function PR(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function NR(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||He(e.dependsOn).length>0||He(e.link).length>0}function LR(e){let t=e.stepTitle?.trim()||void 0,n=vy(e.step),r=e.template?.trim()?yR(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function $R(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",d.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${Al[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",d.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function FR(e,t){let n=Cl(e.stepStatus,"pending"),r=Pl(e,"depends_on"),o=Pe(e.file).map(Rl),i=Pe(e.test).map(Ol),a=Pe(e.doc).map(xl),s=k();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:a.length>0?a:void 0,created_at:s,updated_at:s,completed_at:n==="completed"?s:void 0}}function MR(e){let t=LR(e),n=NR(e);if($R(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[FR(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((o,i)=>({id:`${wy}${String(i+1).padStart(3,"0")}`,order:i+1,title:o,body:t.templateSteps[i]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function Ay(e,t,n=[]){Ie(e,t),n.length>0&&qu(t,n)}async function DR(e,t,n){let r=e.title?.trim();if(!r)throw new l("pm plan create requires --title",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let o=by(e.mode,Tl),i=vR(e.harness),a=e.fromSearch?.trim(),s=PR(e),{steps:c,hasPerStepDetailOptions:m}=MR(e);if(c.length===0&&m)throw new l("pm plan create step options require --step-title (or a single --step)",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let p=e.description?.trim()??e.scope?.trim()??r,u=e.claim?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:p,type:"Plan",template:void 0,file:Pe(e.file),test:Pe(e.test),doc:Pe(e.doc),field:Pe(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:xR(e),message:e.message??(a?`plan create (search: ${a})`:"plan create")};Ay(e,f);let _=await Gt(f,t),h=await se({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(y){let w=["plan_mode"];y.metadata.plan_mode=o,i&&(y.metadata.plan_harness=i,w.push("plan_harness"));let b=e.scope?.trim();b&&(y.metadata.plan_scope=b,w.push("plan_scope"));let S=e.resumeContext?.trim();return S&&(y.metadata.plan_resume_context=S,w.push("plan_resume_context")),y.metadata.plan_steps=c,w.push("plan_steps"),s&&(y.metadata.plan_validation=[...y.metadata.plan_validation??[],s],w.push("plan_validation")),u&&(y.metadata.assignee=u,w.push("assignee")),{changedFields:w}}}),g=Ue(h.item,"brief");return{action:"create",plan:g,step:c[0],next_actions:Ge(_.item.id,g),warnings:[..._.warnings],generated_at:k()}}async function UR(e,t,n){let r=bR(t.depth),o=kR(t.fields),{document:i,itemId:a}=await Ey(n,e),s=Ue(i.metadata,o===null?r:"deep");return{action:"show",plan:o===null?s:SR(s,o),next_actions:Ge(a,s),warnings:[],generated_at:k()}}function GR(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function st(e){let t=C(e.options.author,e.ctx.settings.author_default),n,r=await se({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){Sy(o.metadata);let i=$(e.ctx.settings.schema);if(re(o.metadata.status,i)||tc(o.metadata.plan_mode))throw new l(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.metadata.plan_mode??"unset"}) and cannot be mutated.`,d.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let a=(o.metadata.plan_steps??[]).slice(),s=new Map(Object.entries(o.metadata).filter(([u])=>u.startsWith("plan_")).map(([u,f])=>[u,JSON.stringify(f)])),c=e.mutator(a,o);n=c.resultStep;let m=a.slice().sort((u,f)=>u.order-f.order).map((u,f)=>({...u,order:f+1}));o.metadata.plan_steps=m;let p=GR(s,o.metadata);return p.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:p.length>0?p:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function jR(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let o=Cl(t.stepStatus,"pending"),i=t.allowMultipleActive===!0,{document:a,resultStep:s,itemId:c}=await st({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(p){let u=p.length+1;Ty(p,void 0,o,i);let f=qR(p,t,{order:u,title:r,status:o});return p.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Ue(a.metadata,"standard");return{action:"add-step",plan:m,step:s,next_actions:Ge(c,m),warnings:[],generated_at:k()}}function Ty(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(i=>i.id!==t&&i.status==="in_progress");if(o)throw new l(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function qR(e,t,n){let r=Pl(t,"depends_on"),o=Pe(t.file).map(Rl),i=Pe(t.test).map(Ol),a=Pe(t.doc).map(xl),s=k();return{id:AR(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:a.length>0?a:void 0,created_at:s,updated_at:s,completed_at:n.status==="completed"?s:void 0}}function Pl(e,t){let n=He(e.dependsOn).map(p=>({id:p,kind:t})),r=He(e.related).map(p=>({id:p,kind:"related"})),o=He(e.blocks).map(p=>({id:p,kind:"blocks"})),i=He(e.blockedBy).map(p=>({id:p,kind:"blocked_by"})),a=He(e.link),s=ky(e.linkKind,t),c=e.linkNote?.trim(),m=a.map(p=>{let u={id:p,kind:s};return c&&(u.note=c),u});return[...n,...r,...o,...i,...m]}async function kl(e,t,n,r){let{document:o,resultStep:i,itemId:a}=await st({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let p=Yn(c,r.stepRef),u=k(),f=r.finalStatus??Cl(t.stepStatus,p.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return Ty(c,p.status==="in_progress"?p.id:void 0,f,_),KR(p,t,f,u),m.metadata.updated_at=u,{changedSteps:[p.id],resultStep:p}}}),s=Ue(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:s,step:i,next_actions:Ge(a,s),warnings:[],generated_at:k()}}function KR(e,t,n,r){zR(e,t,n),HR(e,t),e.status=n,e.updated_at=r,BR(e,n,r)}function zR(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new l("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",d.USAGE)}function HR(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=t.stepOwner.trim()||void 0),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let r=Pe(t.file).map(Rl),o=Pe(t.test).map(Ol),i=Pe(t.doc).map(xl);r.length>0&&(e.files=Sl(e.files,r)),o.length>0&&(e.tests=Sl(e.tests,o)),i.length>0&&(e.docs=Sl(e.docs,i))}function Sl(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let i=JSON.stringify(o);r.has(i)||(r.add(i),n.push(o))}return n}function BR(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function VR(e,t,n,r,o){let{document:i,itemId:a,resultStep:s}=await st({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(m){let p=Yn(m,r),u=m.filter(_=>_.id!==p.id),f=Math.max(1,Math.min(o,u.length+1));return u.splice(f-1,0,p),u.forEach((_,h)=>{_.order=h+1,_.updated_at=k()}),m.length=0,m.push(...u),{changedSteps:[p.id],resultStep:p}}}),c=Ue(i.metadata,"standard");return{action:"reorder-step",plan:c,step:s,next_actions:Ge(a,c),warnings:[],generated_at:k()}}async function WR(e,t,n,r){let{document:o,itemId:i,resultStep:a}=await st({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(c){let m=Yn(c,r),p=c.filter(u=>u.id!==m.id);return p.forEach((u,f)=>{u.order=f+1}),c.length=0,c.push(...p),{changedSteps:[m.id],resultStep:m}}}),s=Ue(o.metadata,"standard");return{action:"remove-step",plan:s,step:a,next_actions:Ge(i,s),warnings:[],generated_at:k()}}async function YR(e,t,n,r){let o=Pl(t,ky(t.linkKind,"related"));if(o.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let i=t.promoteToItemDep===!0,{document:a,itemId:s,resultStep:c}=await st({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(p,u){let f=Yn(p,r),_=f.linked_items??[],h=y=>`${y.kind}:${y.id}`,g=new Set(_.map(h));for(let y of o){let w=h(y);g.has(w)||(_.push(y),g.add(w))}if(f.linked_items=_,f.updated_at=k(),i){let y=u.metadata.dependencies??[],w=S=>`${S.kind}:${S.id}`,b=new Set(y.map(w));for(let S of o){let T=S.kind==="depends_on"?"blocked_by":S.kind,L={id:S.id,kind:T,created_at:k(),author:C(t.author,n.settings.author_default)};b.has(w(L))||(y.push(L),b.add(w(L)))}u.metadata.dependencies=y}return{changedSteps:[f.id],resultStep:f}}}),m=Ue(a.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ge(s,m),warnings:[],generated_at:k()}}async function JR(e,t,n,r){let o=He(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:i,itemId:a,resultStep:s}=await st({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let p=Yn(m,r),u=(p.linked_items??[]).filter(f=>!o.includes(f.id));return p.linked_items=u.length>0?u:void 0,p.updated_at=k(),{changedSteps:[p.id],resultStep:p}}}),c=Ue(i.metadata,"standard");return{action:"unlink",plan:c,step:s,next_actions:Ge(a,c),warnings:[],generated_at:k()}}async function El(e,t,n,r){let o=CR(r,t);if(!o){let m=`--${r}-text`,p=`--${r}`;throw new l(`pm plan ${r} requires ${m}`,d.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${m} "..."`,`pm plan ${r} <plan-id> ${p} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${m} <value>`}})}let i=C(t.author,n.settings.author_default),{document:a,itemId:s}=await st({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,p){let u=k();if(r==="decision"){let _=p.metadata.plan_decisions??[];return _.push({ts:u,author:i,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),p.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=p.metadata.plan_discoveries??[];return _.push({ts:u,author:i,text:o}),p.metadata.plan_discoveries=_,{changedSteps:[]}}let f=p.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),p.metadata.plan_validation=f,{changedSteps:[]}}}),c=Ue(a.metadata,"deep");return{action:r,plan:c,next_actions:Ge(s,c),warnings:[],generated_at:k()}}async function XR(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:o,itemId:i}=await st({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(s,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),a=Ue(o.metadata,"brief");return{action:"resume",plan:a,next_actions:Ge(i,a),warnings:[],generated_at:k()}}async function QR(e,t,n){let r=by(t.mode??"approved","approved"),{document:o,itemId:i}=await st({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(s,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),a=Ue(o.metadata,"brief");return{action:"approve",plan:a,next_actions:Ge(i,a),warnings:[],generated_at:k()}}function Cy(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function ZR(e,t){let n=Ue(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ge(e.itemId,n),warnings:Cy(t),generated_at:k()}}function eO(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let i=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${i}`)}return r}async function tO(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Pe(e.options.field)){let i=o.indexOf("=");if(i<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let c=a.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let[m,...p]=c,u=`${m}${p.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(u))throw new l(`Invalid --field entry "${o}"; "${u}" is reserved by materialize and cannot be overridden`,d.USAGE);n[u]=s}for(let o of e.targets){let i={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:eO(e.parent,e.planItemId,o)};Ay(e.options,i,["description",...Object.keys(n)]);let a=await Gt(i,{path:e.pmRoot});t.push({id:a.item.id,title:a.item.title,type:e.resolvedTypeName,parent:a.item.parent,tags:a.item.tags??[],from_step:o.id})}return t}function nO(e,t,n){for(let r of t){let o=n.find(s=>s.from_step===r.id);if(!o)continue;let i=e.find(s=>s.id===r.id);if(!i)continue;let a=i.linked_items??[];a.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),i.linked_items=a,i.updated_at=k()}}async function rO(e,t,n){let r=He(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let o=t.materializeType?.trim()||"Task",i=x(n.settings,O()),a=ke(o,i);if(!a)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let s=t.materializeParent?.trim()||e,c=t.materializeTags,m=await Ey(n,e),p=(m.document.metadata.plan_steps??[]).slice(),{targets:u,skipped:f}=TR(p,r);if(u.length===0){if(f.length>0)return ZR(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await tO({targets:u,parent:s,planItemId:m.itemId,resolvedTypeName:a,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:g}=await st({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(w){return nO(w,u,_),{changedSteps:u.map(b=>b.id)}}}),y=Ue(h.metadata,"standard");return{action:"materialize",plan:y,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ge(g,y),warnings:Cy(f),generated_at:k()}}function oO(e){if(e.subcommand==="create")return e;let t=vy(e.options.step);if(t.length>1)throw new l(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,d.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:Ie(e.options,{...e.options,stepTitle:t[0]})}:e}function bt(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function hn(e,t){let n=bt(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function iO(e){let t=hn(e,"reorder-step");if(e.reorderTo===void 0)throw new l("pm plan reorder-step requires <plan-id> <step> <new-order>",d.USAGE);return{...t,reorderTo:e.reorderTo}}var aO={create:(e,t)=>DR(e.options,e.global,t),show:(e,t)=>UR(bt(e,"show"),e.options,t),"add-step":(e,t)=>jR(bt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=hn(e,"update-step");return kl(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=hn(e,"complete-step");return kl(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=hn(e,"block-step");return kl(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=iO(e);return VR(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=hn(e,"remove-step");return WR(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=hn(e,"link");return YR(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=hn(e,"unlink");return JR(n.id,e.options,t,n.stepRef)},decision:(e,t)=>El(bt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>El(bt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>El(bt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>XR(bt(e,"resume"),e.options,t),approve:(e,t)=>QR(bt(e,"approve"),e.options,t),materialize:(e,t)=>rO(bt(e,"materialize"),e.options,t)};function sO(e){let t=aO[e];if(!t)throw Ce({command_path:"plan",token:e,allowed:gR});return t}async function Iy(e){let t=await OR(e.global),n=oO(e),r=await sO(n.subcommand)(n,t);return r.action==="show"?r:{...r,mutation_receipt:Ia(r,t.pmRoot)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a59a772-3e2a-5ae2-88c1-a96bc36f9f85")}catch{}})();var Oy=1,Ll="update-many",cO=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),lO=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),dO={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},mO=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],pO={close_reason:"close_reason","close-reason":"close_reason",deadline:"deadline",estimate:"estimated_minutes",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",ac:"acceptance_criteria",definition_of_ready:"definition_of_ready","definition-of-ready":"definition_of_ready",order:"order",rank:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",why_now:"why_now","why-now":"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blocked_by:"blocked_by","blocked-by":"blocked_by",blocked_reason:"blocked_reason","blocked-reason":"blocked_reason",unblock_note:"unblock_note","unblock-note":"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",repro_steps:"repro_steps","repro-steps":"repro_steps",resolution:"resolution",expected_result:"expected_result","expected-result":"expected_result",actual_result:"actual_result","actual-result":"actual_result",affected_version:"affected_version","affected-version":"affected_version",fixed_version:"fixed_version","fixed-version":"fixed_version",component:"component",regression:"regression",customer_impact:"customer_impact","customer-impact":"customer_impact",type_options:"type_options","type-options":"type_options",tags:"tags"},xy=e=>{let t={};for(let[n,r]of Object.entries(e))cO.has(n)||r!==void 0&&(t[n]=r);return t},uO=e=>Object.keys(xy(e)).length>0,Py=e=>typeof e=="string"?e.trim():e,fO=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Nl=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},_O=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Py(e)},hO={priority:fO,estimatedMinutes:Nl,order:Nl,rank:Nl,regression:_O},gO=(e,t)=>{if(t!==void 0)return(hO[e]??Py)(t)},yO=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return pO[t]??t},Ra=(e,t)=>Le(e,t),wO=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],vO=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,bO=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",Ry=(e,t)=>t===void 0?void 0:e[t],Jn=e=>Array.isArray(e)?e.length:0,kO=(e,t,n)=>{let r=n[e.addKey],o=Ry(n,e.removeKey),i=Jn(r),a=Jn(o),s=n[e.clearKey]===!0,c=Ry(n,e.replaceKey)===!0;if(![s,c,i>0,a>0].includes(!0))return;let m=wO(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:bO({replace:c,clear:s,removeCount:a}),clear:s,replace:c,add_count:i,remove_count:a,before_count:vO(e.field,m)}}},SO=(e,t)=>{let n=[];for(let r of mO){let o=kO(r,e,t);o!==void 0&&n.push(o)}return n},EO=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],AO=(e,t)=>{if(![t.tags!==void 0,Jn(t.addTags)>0,Jn(t.removeTags)>0].includes(!0))return;let n=EO(e.tags),r=t.tags===void 0?n:Pt(t.tags),o=Ln(r,t.addTags),i=pi(o,t.removeTags).slice().sort((s,c)=>s.localeCompare(c)),a=n.slice().sort((s,c)=>s.localeCompare(c));if(!Ra(a,i))return{field:"tags",before:n,after:i}},TO=(e,t)=>{let n=e.acceptance_criteria,r=mi(Nn(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let o=r.criteria.join("; ");if(!Ra(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},CO=(e,t,n)=>{for(let[r,o]of Object.entries(dO)){let i=n[r];if(i===void 0)continue;let a=t[o],s=gO(r,i);Ra(a,s)||e.push({field:o,before:a,after:s})}},IO=(e,t,n,r)=>{let o=oi(n,r,["update_many"]);for(let[i,a]of Object.entries(o)){let s=t[i];Ra(s,a)||e.push({field:i,before:s,after:a})}},RO=(e,t,n)=>{for(let r of n??[]){let o=yO(r),i=t[o];i!==void 0&&e.push({field:o,before:i,after:null})}},OO=(e,t,n={})=>{let r=e,o=[],i=AO(r,n);if(i&&o.push(i),CO(o,r,n),Jn(n.addAc)>0||Jn(n.removeAc)>0){let a=TO(r,n);a!==void 0&&o.push(a)}return o.push(...SO(r,n)),IO(o,r,n,t),RO(o,r,n.unset),{id:e.id,changes:o}},xO=(e,t)=>Vu(e,t,{strict:!0,flagLabel:"--filter-status"}),PO=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)},NO=[({update:e})=>{e.priority!==void 0&&Fn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,O());if(!ke(e.type,r))throw new l(Rt(e.type,r.types,Ot(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!ee(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,d.USAGE)}},({update:e})=>{e.deadline!==void 0&&ie(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&$n(e.estimatedMinutes,"estimated-minutes")}],LO=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let i of NO)i(o)},$O=async e=>{let t=await ci(e.pmRoot,Ll,e.rollbackId,Oy),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await li(t.items,(o,i)=>an(o,i,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...en({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},FO=async e=>{let t={schema_version:Oy,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await si(e.pmRoot,Ll,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},MO=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},$l=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},DO=async e=>{let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:$(n.schema),runtimeFieldRegistry:nt(n.schema)}},UO=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Cr(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",d.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",d.USAGE);return $O({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},GO=async e=>{xO(e.options.status,e.runtime.statusRegistry);let t=await ht(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let i=OO(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?i:{...i,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await ht(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:MO(e.options.list?.ids,r)}},jO=e=>({outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...$l(e)}),qO=e=>({...en({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...$l(e)}),KO=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(i=>i.changes.length>0).map(i=>i.id));for(let i of e.items){if(!o.has(i.id)){t.push({id:i.id,status:"skipped"});continue}try{let a=Qs({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),s=await at(i.id,a,e.global);t.push({id:i.id,status:"updated",changed_fields:s.changed_fields,warnings:s.warnings}),n.push(i.id)}catch(a){t.push({id:i.id,status:"failed",error:An(a)})}}return{rows:t,updatedIds:n}},zO=async e=>{if(e.plan.actionable.length===0)return qO(e.plan);let t=k(),n=ai(Ll,t),r=new Set(e.plan.actionable.map(u=>u.id)),o=e.plan.listed.items.filter(u=>r.has(u.id)).map(u=>({id:u.id,target_updated_at:u.updated_at})),i=e.options.checkpoint===!1?void 0:await FO({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),a=await KO({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),s=u=>a.rows.filter(f=>f.status===u).length,c=s("updated"),m=s("skipped"),p=s("failed");return{...en({applied:c,skipped:m,failed:p,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...i?{checkpoint:i}:{},updated_count:c,skipped_count:m,failed_count:p,rows:a.rows,ids:a.updatedIds,...$l(e.plan)}},Ny=async(e,t)=>{let n=await DO(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:Qs(await ul(e.update))});let o=xy(e.update);if(PO(e.list),r!==void 0)return UO({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!uO(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${lO}), or pass --dry-run for a filter-only preview.`,d.USAGE);LO(e.update,n.settings,n.statusRegistry,n.pmRoot),fl(e.update);let i=await pn({pmRoot:n.pmRoot,dependencies:Ca(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,O()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),a=await GO({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:i});return await pn({pmRoot:n.pmRoot,dependencies:Ca(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,O()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:a.listed.items.map(s=>({id:s.id,createdAt:s.created_at})),schema:n.settings.schema}),e.dryRun===!0?jO(a):zO({runtime:n,options:e,global:t,plan:a})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6263346a-08ee-5eb9-81b9-47e933793c07")}catch{}})();function HO(e){if(e===void 0)return;if(e.trim().length===0)throw new l("--add-json must contain a JSON value",d.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new l("--add-json must be valid JSON",d.USAGE,{code:"structured_event_json_invalid"})}return t}function BO(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function VO(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new l("--since must be a valid ISO timestamp",d.USAGE,{code:"structured_event_since_invalid"});return t}async function Ly(e,t,n){let r=HO(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let i=r===void 0?void 0:Yt(r),a=[t.since,t.eventType].some(h=>h!==void 0),s=VO(t.since),c=gr(t.limit),m=await Bn(e,{...t,...a?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,a].includes(!0)},n,{input:await Wi(i===void 0?t:{add:i},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>Hn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:BO(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm notes --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}}),p=t.eventType?.trim(),u=m.notes.filter(h=>{let g=[h.format==="json",h.data!==void 0].every(Boolean),y=[s===void 0,Date.parse(h.created_at)>=(s??Number.POSITIVE_INFINITY)].includes(!0),w=[!p,h.event_type===p].includes(!0);return[!a,[g,y,w].every(Boolean)].includes(!0)}),f=a?Nc(u,c):u,_=f.filter(h=>h.format==="json").length;return{...m,notes:f,count:f.length,...a?{total_count:u.length,returned_count:f.length,has_more:f.length<u.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}import ax from"node:path";import WO from"node:fs/promises";import $y from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ac2020a4-78bf-5aa3-a5c4-88d3196dfb1f")}catch{}})();var YO="templates",JO=".json",XO=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,QO=Zo.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),ZO=new Set(QO);function ex(e){let t=e.trim();if(!XO.test(t))throw new l(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,d.USAGE);return t}function Fy(e){return $y.join(e,YO)}function My(e,t){return $y.join(Fy(e),`${t}${JO}`)}async function tx(e){await I(e)}function Dy(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function nx(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(ZO.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(i=>typeof i=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return Dy(t)}function rx(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new l(`Template "${t}" has invalid options payload.`,d.GENERIC_FAILURE);let n=e,r={};for(let[o,i]of Object.entries(n)){let a=o.trim();if(a.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof i=="string"){r[a]=i;continue}if(Array.isArray(i)&&i.every(s=>typeof s=="string")){r[a]=[...i];continue}throw new l(`Template "${t}" contains invalid value for option "${a}".`,d.GENERIC_FAILURE)}return Dy(r)}function ox(e,t){let n;try{n=JSON.parse(e)}catch{throw new l(`Template "${t}" contains invalid JSON.`,d.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Template "${t}" has invalid document shape.`,d.GENERIC_FAILURE);let r=n,o=rx(r.options,t),i=k();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:i,updated_at:typeof r.updated_at=="string"?r.updated_at:i,options:o}}async function ix(e,t){let n=await J(My(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return ox(n,t)}async function Fl(e,t,n){let r=E(process.cwd(),n.path);await tx(r);let o=ex(e),i=nx(t);if(Object.keys(i).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let a=k(),s=My(r,o),c=a;await q(s)&&(c=(await ix(r,o)).created_at);let m={name:o,created_at:c,updated_at:a,options:i},p=await A(r);return await WO.mkdir(Fy(r),{recursive:!0}),await We({pmRoot:r,filePath:s,raw:`${JSON.stringify(m,null,2)}
23
- `,op:"templates:save",author:C(void 0,p.author_default),lockTtlSeconds:p.locks.ttl_seconds,lockWaitMs:p.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:s,options:m.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aa4e2ff3-dc3b-5688-bf40-bdd71c65320b")}catch{}})();var qy=["list","show","apply","lint"],sx="schema-types",cx="schema-statuses",lx="schema-fields";function Oa(){let e=O();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Ky(){let{profiles:e,warnings:t}=vp(Oa());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:Ap(n.definition)})),warnings:t,generated_at:k()}}function zy(e){let t;try{t=Ko(e,Oa())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...Tp(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function Hy(e){let t;try{t=Ko(e,Oa())}catch(o){throw new l(o instanceof Error?o.message:String(o),d.USAGE)}let{resolved:n}=t,r=tu(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:k()}}function dx(e,t){return ax.join(e,"templates",`${t}.json`)}async function mx(e,t){let n=await J(dx(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function Uy(e,t,n,r){let o=new Map;for(let i of r.templates){let a=await mx(e,i.name);a!==void 0&&o.set(i.name,a)}return{typesRaw:await J(pt(e,t.files.types,mt.types)),statusesRaw:await J(pt(e,t.files.statuses,mt.statuses)),fieldsRaw:await J(pt(e,t.files.fields,mt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Xn(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function Gy(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Xn(t.types.changes),statuses:Xn(t.statuses.changes),fields:Xn(t.fields.changes),workflows:Xn(t.workflows.changes.map(i=>({key:i.type,status:i.status}))),config:Xn(t.config.changes),templates:Xn(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(o)].sort((i,a)=>i.localeCompare(a)),generated_at:k()}}async function px(e){await I(e)}function ux(e){try{let t=Ko(e,Oa());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function By(e,t,n){let r=E(process.cwd(),n.path);await px(r);let o=ux(e),i=o.profile,a=o.warnings,s=t.dryRun===!0,c=await A(r),m=zo(c.schema);if(s){let w=await Uy(r,m,c,i),b=jy(i,w);return Gy(i,b,!1,!0,[...a])}let p=C(t.author,c.author_default),u=Uu(c),f=!!t.force,_=[...a],h=[],g=async w=>{h.push(await Te(r,w,c.locks.ttl_seconds,p,f,u.force_required_for_stale_lock,c.locks.wait_ms))},y;try{await g(sx),await g(cx),await g(lx);let w=await Uy(r,m,c,i);if(y=jy(i,w),y.types.changed){let b=pt(r,m.files.types,mt.types);await We({pmRoot:r,filePath:b,raw:qo(y.types.file),op:"profile:apply-types",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(i.types.map(L=>fp(L).name)),T=y.types.file.definitions.filter(L=>S.has(L.name));await Cf(r,T,_,"profile:apply-type-folder"),_.push(...await Y({path:b,scope:"project",op:"profile:apply-types"}))}if(y.statuses.changed){let b=pt(r,m.files.statuses,mt.statuses);await We({pmRoot:r,filePath:b,raw:Ep(y.statuses.file),op:"profile:apply-statuses",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await Y({path:b,scope:"project",op:"profile:apply-statuses"}))}if(y.fields.changed){let b=pt(r,m.files.fields,mt.fields);await We({pmRoot:r,filePath:b,raw:bp(y.fields.file),op:"profile:apply-fields",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await Y({path:b,scope:"project",op:"profile:apply-fields"}))}if(y.config.changed||y.workflows.changed){for(let b of y.config.changes){if(b.status==="unchanged")continue;let S=Bo(b.key);S!==void 0&&Vo(c,S,b.value)}c.schema.type_workflows=y.workflows.result,await Fe(r,c,"profile:apply-config")}for(let b of y.templates.changes)b.status!=="unchanged"&&await Fl(b.name,{...b.options},n)}finally{for(let w of h.reverse())try{await w()}catch{}}return Gy(i,y,y.changed,!1,_)}function jy(e,t){try{return nu(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import vx from"node:fs/promises";import Ul from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c34cc860-67c7-548b-99ff-f4155ef44bb0")}catch{}})();var Wy=10,gn="https://schema.unbrained.dev/pm/eval-query-set/v1";var xa={schema:gn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Xe=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},fx=new Set(["keyword","semantic","hybrid"]);function Vy(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function _x(e,t,n){if(t.size===0)return 0;let r=e.map(s=>t.has(s)?1:0),o=Vy(r,n),i=Array.from({length:t.size},()=>1),a=Vy(i,n);return a===0?0:o/a}function hx(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function Ml(e,t,n){let r=Math.min(n,e.length),o=0;for(let i=0;i<r;i+=1)t.has(e[i])&&(o+=1);return o}function gx(e,t,n){return n<=0?0:Ml(e,t,n)/n}function yx(e,t,n){return t.size===0?0:Ml(e,t,n)/t.size}function Yy(e,t,n){return{ndcg:_x(e,t,n),mrr:hx(e,t,n),precision:gx(e,t,n),recall:yx(e,t,n),relevant_total:t.size,retrieved_relevant:Ml(e,t,n)}}function Jy(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function wx(e,t){if(typeof e!="object"||e===null)throw new Xe(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new Xe(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Xe(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(i=>typeof i!="string"))throw new Xe(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new Xe(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!fx.has(n.mode)))throw new Xe(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.minimum===void 0?{}:{minimum:G_(n.minimum)},...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Dl(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==gn)throw new Xe(`Unsupported eval query set schema; expected "${gn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new Xe('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Xe("Eval query set must contain at least one query");return{schema:gn,queries:n.map((r,o)=>wx(r,o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d26721c-719a-5c7e-8baf-72cbf1088988")}catch{}})();var bx=Ul.join("search","eval-queries.json"),Gl={schema:gn,examples:[JSON.stringify(xa)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},kx=new Set(["keyword","semantic","hybrid"]),Sx=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!kx.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},Ex=e=>{if(e===void 0||e==="")return Wy;let t=Qd(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},Ax=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new l("Eval --fail-under must be a number in the range [0, 1]",d.USAGE);return n},jt=e=>Math.round(e*1e4)/1e4,Tx=async e=>{try{return await vx.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Gl,examples:[`echo '${JSON.stringify(xa)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},Cx=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new l(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,d.USAGE,Gl)}},Ix=e=>{try{return Dl(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Gl)}},Rx=async e=>Ix(Cx(await Tx(e),e)),Ox=async(e,t,n,r)=>{let o=e.mode??t,i=(await Rr(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(s=>s.id).filter(s=>typeof s=="string"),a=Yy(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:j_(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:jt(a.ndcg),mrr:jt(a.mrr),precision:jt(a.precision),recall:jt(a.recall)}}},xx=(e,t,n,r)=>{let o=Jy(n);return{k:e,query_count:t.length,aggregate:{ndcg:jt(o.ndcg),mrr:jt(o.mrr),precision:jt(o.precision),recall:jt(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:(r===void 0||o.ndcg>=r)&&t.every(i=>(i.violations?.length??0)===0)}},Xy=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=Ex(e.k),o=Sx(e.mode),i=Ax(e.failUnder),a=e.queries?Ul.resolve(process.cwd(),e.queries):Ul.join(n,bx),s=await Rx(a),c=[],m=[];for(let p of s.queries){let{report:u,metrics:f}=await Ox(p,o,r,t);m.push(f),c.push(u)}return xx(r,c,m,i)};import{readFile as Px,writeFile as Nx}from"node:fs/promises";import Lx from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="932450d7-963b-566b-a5ad-1b577a895e8e")}catch{}})();var Qy=["item","history","relationship","json"];function $x(e){let t=e.trim().toLowerCase();if(Qy.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${Qy.join(", ")}.`,d.USAGE)}function Fx(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new l(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,d.USAGE)}async function jl(e,t){try{return await Px(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function Mx(e){let t=E(process.cwd(),e.path);return await q(ne(t))?A(t):null}function Dx(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Zy(e,t){let n=$x(e.artifact),r=Fx(e.prefer),o=Lx.resolve(e.outputPath??e.oursPath),[i,a,s]=await Promise.all([jl(e.basePath,"base"),jl(e.oursPath,"ours"),jl(e.theirsPath,"theirs")]),c,m,p=[],u={};if(n==="history"){let _=o_(i,a,s);c=_.merged,u.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=i_(i,a,s);c=_.merged,u.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await Mx(t),h=Dx(e.itemPath??o,_),g=Tt(O()),y=a_(i,a,s,{format:h,schema:_?.schema,extensionFieldNames:g,preferred:r,conflictResolution:"latest_document_update"});if(c=y.merged,p.push(...y.conflict_fields),u.item={fields_from_theirs:y.fields_from_theirs,union_fields:y.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let w=Eu(c,{format:h,schema:_?.schema,extensionFieldNames:g}),b=w.metadata,S=[...new Set([...y.fields_from_theirs,...y.union_fields,...y.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:y.fields_from_theirs,unionFields:y.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,r_(T==="body"?w.body:b[T])])),decisions:y.conflict_decisions,operation:await c_(process.cwd(),e.itemPath,a)}}}else{let _=s_(i,a,s,{preferred:r});c=_.merged,p.push(..._.conflict_paths),u.json={paths_from_theirs:_.paths_from_theirs}}if(await Nx(o,c,"utf8"),m!==void 0){let _=await d_(m);_!==null&&(u.receipt=nn(_))}let f=[];if(p.length>0){let _=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${p.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&u.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:p.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:p,...u,guidance:f,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3fe6f853-6742-5305-b722-0cc74547f367")}catch{}})();async function ew(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await l_(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Ut(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Ut(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:r,message:e.message??`Settle ${n.operation.kind} receipt after exact original Git state restoration`,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...nn(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await Li(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as Ux}from"node:fs/promises";import Gx from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9b07f6f1-2c84-583c-afb2-80f219d19863")}catch{}})();var jx=4;function tw(e){let t=e.checks.find(s=>s.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,a=Array.isArray(o)?o.flatMap(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return[];let c=s;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:i,coordinates:a}}async function qx(e,t){let n=[];for(let r of t){let o;try{o=await Ux(Gx.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let i=o.split(/\r?\n/)[r.history_line-1];if(i===void 0||i.trim().length===0)continue;let a;try{a=JSON.parse(i)}catch{continue}let s=__(a,r.item_id).find(c=>c.receiptId===r.receipt_id);s===void 0||!f_(s)||s.eventTimestamp===void 0||Xo(s.eventTimestamp,u_)>=0||n.push({...r,original_event_ts:s.eventTimestamp})}return n}async function Kx(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;let t=new Map;for(let n of e.candidates){let r=t.get(n.item_id)??[];r.push(n),t.set(n.item_id,r)}for(let[n,r]of t)await Ut(n,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:r.map(o=>({receipt_id:o.receipt_id,original_history_line:o.history_line,original_event_ts:o.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function zx(e){try{return{status:"fulfilled",value:await Ut(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function Hx(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function Bx(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>Li(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}async function nw(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await Ar(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=tw(o),a=await qx(r,i.coordinates),s=await Ci(r),c=s??r,m=await m_(c,{includeLossless:!0,pmRoot:r});if(m.invalid_evidence_count>0)throw new l(`Merge reconciliation refused ${m.invalid_evidence_count} invalid receipt evidence file(s).`,d.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let p=await Kx({candidates:a,options:e,global:t}),u=m.receipts,f=await ew({cwd:s,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),_=new Set(f),h=new Map;for(let j of u.filter(ue=>!_.has(ue.id))){let ue=h.get(j.item_id)??[];ue.push(j),h.set(j.item_id,ue)}let g=Object.fromEntries([...h].map(([j,ue])=>[j,{merge:{receipts:ue.map(nn)}}])),y=Object.fromEntries([...h].map(([j,ue])=>[j,{gitWorkspaceRoot:s,receipts:ue}])),w=await Fi({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:g,...u.length>0?{mergeReceiptProofById:y}:{}},t),b=new Set(w.streams.map(j=>j.id)),S=[...h.keys()].filter(j=>!b.has(j)),T=await Uf(S,jx,j=>zx({id:j,dryRun:n,options:e,global:t,auditContext:g[j],mergeReceiptProof:y[j]}));Hx({receiptOnlyIds:S,results:T,repair:w});let L=await Bx({dryRun:n,pendingReceipts:u,repair:w,receiptWorkspaceRoot:c}),P=await Ui({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),M=p===0?o:await Ar(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),K=tw(M),H=P.checks.every(j=>j.status==="ok"),Z=n?u.length===0:L+f.length===u.length,le=[w.totals.failed===0,H,Z,K.count===0,!K.truncated].every(Boolean),de=i.truncated||K.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,qe=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",de,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:le?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.",de,...a.length>0&&p===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(j=>j!==void 0);return{ok:le,dry_run:n,repair:w,receipts:{pending_before:u.length,reconciled:L,abandoned:f.length,summaries:u.map(nn),missing_history_references_before:i.count,legacy_disposition_eligible:a.length,legacy_disposition_recorded:p,missing_history_references_after:K.count},validation:P,guidance:qe,generated_at:P.generated_at}}import{createHash as Vx}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3483e997-6bee-52bf-a048-8fe5c2427d06")}catch{}})();var iw=1,aw=/^[A-Za-z0-9_-]+$/,Wx=100,rw=1e3;var $H=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function Qe(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function Yx(e){return Vx("sha256").update(Yt({type:Qe(e.type),author:Qe(e.author),item:Qe(e.item),harness:Qe(e.harness),agent_instance:Qe(e.agentInstance),provenance:Qe(e.provenanceFilter)})).digest("hex").slice(0,24)}function ow(e,t){let n={version:iw,fingerprint:t,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function Jx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===iw,n.fingerprint===t,typeof n.ts=="string",typeof n.stream_id=="string",typeof n.stream_offset=="number",Number.isSafeInteger(n.stream_offset),Number(n.stream_offset)>=0].every(Boolean)}function Xx(e,t){let n=e.trim();if(n.length===0||n.length>4096||!aw.test(n))throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"})}if(!Jx(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function Qx(e){let t=e??Wx;if(!Number.isSafeInteger(t)||t<0||t>rw)throw new l(`Mutation event limit must be an integer from 0 to ${rw}.`,d.USAGE,{code:"invalid_event_limit"});return t}function Zx(e,t){let n=e?.trim();if(!n)return{};if(aw.test(n))return{cursor:Xx(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new l("Mutation event --since must be an event cursor or ISO timestamp.",d.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function eP(e,t){let n=await zs(e,t);if(n===null){if(!await Cu(e))return{...await Iu(e,t),source:"authoritative_history"};n=await zs(e,t)}if(n===null)throw new l("Mutation event index could not be opened after rebuild.",d.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function tP(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Pa(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=Qx(e.limit),r=tP(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new l("Mutation event projections are mutually exclusive. Use --provenance or --full.",d.USAGE);let o=await A(t),i=o.agent_identity.identity_vocabulary,a=N_(o.agent_identity.harness_signals),s=L_({provenance:e.provenanceFilter},a),c=Qe(e.harness),m=Yx(e),{cursor:p,sinceTimestamp:u}=Zx(e.since,m),f={...p?{after_ts:p.ts,after_stream_id:p.stream_id,after_stream_offset:p.stream_offset}:u?{since_ts:u}:{},ops:Qe(e.type),authors:Qe(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,g])=>c.includes(g)).map(([g])=>g):void 0,agent_instances:Qe(e.agentInstance),provenance:[...s].map(([g,y])=>({dimension:g,values:[...y]})),stream_ids:Qe(e.item),limit:n},_=await eP(t,f),h=_.events.map(g=>({...r==="row"?{cursor:ow(g,m)}:{},item_id:g.stream_id,version:g.stream_offset+1,ts:g.entry.ts,author:g.entry.author,type:g.entry.op,...g.entry.message===void 0?{}:{message:g.entry.message},patch_count:g.entry.patch.length,...e.full===!0?{entry:g.entry}:{},...e.provenance===!0?{provenance:$_(g.entry,i,{itemId:g.stream_id,version:g.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:ow(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:F_(_.events.map(g=>g.entry),i,a)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="015a3a52-f631-5ab7-b5c5-10a54a0b750c")}catch{}})();var nP="1h",rP="now",oP="+1d";function qt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function sw(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return Ie(n,r)}async function cw(e,t,n,r){let o=sw(e,t,n),i=[];return qt(i,"start",n.start??rP),n.end!==void 0?qt(i,"end",n.end):qt(i,"duration",n.duration??nP),qt(i,"location",n.location),qt(i,"timezone",n.timezone),n.allDay===!0&&qt(i,"all_day","true"),o.event=[i.join(",")],Gt(o,r)}function lw(e,t,n){return cw("Meeting",e,t,n)}function dw(e,t,n){return cw("Event",e,t,n)}function mw(e,t,n){let r=sw("Reminder",e,t),o=[];return qt(o,"at",t.at??oP),qt(o,"text",t.text??e),r.reminder=[o.join(",")],Gt(r,n)}import zr from"node:crypto";import{cp as pw,lstat as iP,mkdir as yn,readFile as Qn,readdir as Kl,rename as _w,rm as Hl,writeFile as Na}from"node:fs/promises";import F from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3b4a5521-a665-5f60-8d01-16033b078916")}catch{}})();var hw="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var gw=F.join("runtime","workspace-snapshots"),aP=new Set(["checkpoints","locks","runtime","search","transactions"]),sP=/^[a-z0-9][a-z0-9._-]*$/,Kr="sdk-workspace-transaction",ql={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},yw={renameEntry:_w,removeEntry:async e=>{await Hl(e,{recursive:!0,force:!0})}},zl=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await Qn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==Kr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await te(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
24
- `)}};async function ww(e,t=""){let n=await Kl(F.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((i,a)=>i.name.localeCompare(a.name))){if(t.length===0&&aP.has(o.name))continue;let i=F.posix.join(t.replaceAll(F.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${i}`);if(o.isDirectory())r.push(...await ww(e,i));else if(o.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function vw(e){let t=await ww(e),n=zr.createHash("sha256"),r=[],o=0;for(let a of t){let s=await Qn(F.join(e,a));r.push(s),o+=s.byteLength,n.update(a),n.update("\0"),n.update(String(s.byteLength)),n.update("\0"),n.update(s)}let i=n.digest("hex");return{manifest:{schema:hw,fingerprint:i,files:t,bytes:o},contents:r}}function uw(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
25
- `).filter(t=>t.trim().length>0).length}async function cP(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),i=await Promise.all(o.map(async a=>[a,await Qn(F.join(e,a))]));for(let[a,s]of i)n.set(a,s)}return n}function Bl(e){if(!sP.test(e))throw new l("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",d.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function bw(e,t){return or(`workspace_snapshot_${e}`,t,{codes:{capacity:ql.capacity.code,permission:ql.permission.code,resource:ql.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function wn(e){return F.join(e,gw)}function kw(e){return new l(`Unknown workspace snapshot: ${e}`,d.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Sw(e,t){try{return JSON.parse(await Qn(e,"utf8"))}catch(n){throw Be(n)?kw(t):n}}async function fw(e,t,n){try{await Hl(e,{recursive:n})}catch(r){throw Be(r)?kw(t):r}}async function lP(e,t,n=yw){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function dP(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(i){throw await r.renameEntry(n,t),await r.removeEntry(e),i}await r.removeEntry(n)}async function mP(e,t){return Bl(t),/^[a-f0-9]{64}$/.test(t)?t:(await Sw(F.join(wn(e),"refs",`${t}.json`),t)).fingerprint}async function Vl(e,t={}){if(t.name!==void 0&&(Bl(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new l("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",d.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await vw(e),o=wn(e),i=F.join(o,"objects",n.fingerprint),a=!1;try{a=(await iP(i)).isDirectory()}catch(s){if(!(s instanceof Error&&"code"in s&&Be(s)))throw s}if(!a){let s=F.join(o,"objects",`.create-${process.pid}-${zr.randomUUID()}`);await bw("create_object",async()=>{await yn(F.join(s,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let p=F.join(s,"files",m);await yn(F.dirname(p),{recursive:!0}),await Na(p,r[c])}await Na(F.join(s,"manifest.json"),`${JSON.stringify(n,null,2)}
26
- `,"utf8"),await yn(F.dirname(i),{recursive:!0})}),a=await lP(s,i)}if(t.name!==void 0){let s={name:t.name,fingerprint:n.fingerprint},c=F.join(o,"refs");await yn(c,{recursive:!0});let m=F.join(c,`.ref-${process.pid}-${zr.randomUUID()}`);await Na(m,`${JSON.stringify(s,null,2)}
27
- `,"utf8"),await _w(m,F.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:a}}async function Hr(e,t){let n=await mP(e,t),r=await Sw(F.join(wn(e),"objects",n,"manifest.json"),t);if(r.schema!==hw||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,d.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function Wl(e){let t=wn(e),n=await Kl(F.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&Be(o))return[];throw o}),r=await Kl(F.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&Be(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Hr(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await Qn(F.join(t,"refs",o),"utf8"))))}}async function Yl(e,t){let n=await Hr(e,t),{manifest:r,contents:o}=await vw(e),i=new Map(r.files.map((u,f)=>[u,o[f]])),a=await cP(F.join(wn(e),"objects",n.fingerprint,"files"),n.files),s=new Set(r.files),c=new Set(n.files),m=new Set([...s,...c]);for(let u of m){let f=i.get(u),_=a.get(u);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(u)}let p=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let f=uw(i.get(u)),_=uw(a.get(u));return{path:u,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(u=>u.removed_entries>0).sort((u,f)=>u.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:m.size,removed_file_count:[...s].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!s.has(u)).length,removed_item_count:[...s].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:p.length,removed_history_entry_count:p.reduce((u,f)=>u+f.removed_entries,0),affected_history_streams:p,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function Ew(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",d.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",o=n.lockTtlSeconds??60,i=n.lockWaitMs??5e3,a=await Te(e,Kr,o,r,!1,!1,i),s=new zl(uo(e,Kr),r,o);s.start(),await s.refreshNow();let c,m=!1,p=!1;try{let u=await Yl(e,t),f=await Hr(e,t),_=await Vl(e),h=f.fingerprint,g=wn(e),y=F.join(g,"objects",h,"files"),w=F.dirname(e),b=F.basename(e);c=F.join(w,`.${b}.restore-${zr.randomUUID()}`);let S=F.join(w,`.${b}.backup-${zr.randomUUID()}`);await bw("restore_stage",async()=>{await yn(c,{recursive:!0}),await pw(y,c,{recursive:!0,force:!1}),await yn(F.join(c,"runtime"),{recursive:!0}),await pw(g,F.join(c,gw),{recursive:!0,force:!1})});let T=await Fu({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:u.changed_file_count,removed_file_count:u.removed_file_count,removed_item_count:u.removed_item_count,affected_history_stream_count:u.affected_history_stream_count,removed_history_entry_count:u.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:i}),L=F.relative(c,T.historyPath).replaceAll("\\","/");await s.stop(),p=!0;let P=uo(c,Kr);return await yn(F.dirname(P),{recursive:!0}),await Na(P,await Qn(uo(e,Kr)),{flag:"wx"}),m=!0,await dP(c,e,S,yw,async()=>{s.start(),p=!1,await s.refreshNow()}),await s.stop(),p=!0,{manifest:f,plan:u,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:L,audit_operation:"workspace_snapshot_restore"}}catch(u){throw c!==void 0&&!m&&await Promise.allSettled([Hl(c,{recursive:!0,force:!0})]),u}finally{try{p||await s.stop()}catch{}finally{await a()}}}async function Aw(e,t){Bl(t);let n=wn(e);if(!/^[a-f0-9]{64}$/.test(t))return await fw(F.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Wl(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await fw(F.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01f25e4f-09a1-554f-9e0b-a999fcce5c55")}catch{}})();function Br(e){let t={...e.args,...e.options};return Ie(e.options,t)}function kt(e,t){let n=v(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Zn(e){return typeof e=="string"?[e]:ye(e)}function Tw(e){return Xy(Br(e),e.global)}function Cw(e){let t=Br(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Pa({cwd:v(t,"cwd"),pmRoot:v(t,"path"),since:v(t,"since"),type:Zn(t.type),author:Zn(t.author),item:Zn(t.item),limit:t.limit===void 0?void 0:Me(t.limit,"limit"),full:t.full===!0,cursorMode:r,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Zn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Zn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Zn(t.provenanceFilter)}})}function Iw(e){let t=Br(e),n=kt(t,"subcommand");if(n==="install")return vf({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return nw({dryRun:t.dryRun===!0,author:v(t,"author"),message:v(t,"message"),force:t.force===!0},e.global);if(n==="report")return p_({includeReconciled:t.includeReconciled===!0,cwd:v(t,"cwd")});if(n==="driver")return Zy({artifact:kt(t,"artifact"),basePath:kt(t,"basePath"),oursPath:kt(t,"oursPath"),theirsPath:kt(t,"theirsPath"),outputPath:v(t,"outputPath")??v(t,"output"),itemPath:v(t,"itemPath"),prefer:v(t,"prefer")},e.global);throw Ce({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Rw(e){let t=Br(e),n=kt(t,"subcommand");if(n==="position")return q_(e.global);if(n!=="snapshot")throw Ce({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=v(t,"snapshotAction")??kt(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return Vl(o,{name:v(t,"name")});if(r==="list")return Wl(o);let i=kt(t,"target");if(r==="inspect")return Hr(o,i);if(r==="delete")return Aw(o,i);if(r==="restore")return t.dryRun===!0?Yl(o,i):Ew(o,i,{force:t.force===!0,author:v(t,"author"),message:v(t,"message"),lockTtlSeconds:Me(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Me(t.lockWaitMs,"lockWaitMs")});throw Ce({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function La(e){let t=Br(e),n=kt(t,"title");return e.action==="meet"?lw(n,t,e.global):e.action==="event"?dw(n,t,e.global):mw(n,t,e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27bbfaed-a594-5b3b-84ba-431be02e002e")}catch{}})();function Ow(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:v(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ye(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:v(e,"measurementSource"),measurementItem:v(e,"measurementItem"),measurementRevision:v(e,"measurementRevision"),author:v(e,"author"),message:v(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:v(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import WP from"node:fs/promises";import Ww from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function $a(e,t,n,r,o,i="min"){let a=o==="min"?e-t:t-e,s=i==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return a<0||a===0&&r!==null&&s<0}function pP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,i=null,a=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let p;try{p=JSON.parse(m)}catch{continue}if(p===null||typeof p!="object"||!("ts"in p)||typeof p.ts!="string")continue;let u=p.ts,f=Date.parse(u);Number.isNaN(f)||($a(f,a,u,o,"min")&&(a=f,o=u),$a(f,s,u,i,"max","max")&&(s=f,i=u))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:i}}function xw(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:h})=>pP(_,h)),i=0,a=0,s=null,c=null,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY;for(let _ of o){if(i+=_.lines,a+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);$a(h,m,_.id,s?.id??null,"min")&&(m=h,s={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);$a(h,p,_.id,c?.id??null,"max")&&(p=h,c={id:_.id,ts:_.newest_ts})}}let u=r===0?[]:[...o].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...o].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:i,total_bytes:a,largest_by_bytes:u,deepest_by_lines:f,oldest_entry:s,newest_entry:c}}import{createHash as fP}from"node:crypto";import{execFile as _P}from"node:child_process";import Lw from"node:path";import{promisify as hP}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed03b6c8-6275-55a6-8e5f-4f27a23d6696")}catch{}})();var Pw=1;function uP(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Jl(e){if(e===null)return{format_version:Pw,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Pw||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!uP(r))throw new l("Improvement ledger contains an invalid observation.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7ad59ce-5111-5649-9025-340183539b4a")}catch{}})();var gP=hP(_P),yP=50,Nw=1e3,wP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function $w(e){let t=e.trim().toLowerCase();if(!wP.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function vP(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function Vr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return n}}function bP(e){let t=e??yP;if(!Number.isSafeInteger(t)||t<0||t>Nw)throw new l(`Improvement observation limit must be an integer from 0 to ${Nw}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Fw(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function kP(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});let r=$w(n.metric),o=vP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let i=await EP(e,n.revision),a=Vr(n.source,"source"),s=Vr(n.itemId,"itemId"),c=Vr(n.unit,"unit"),m=Vr(n.idempotencyKey,"idempotencyKey")??(i.revision_source==="unversioned"?void 0:[i.revision,r,a??"manual",s??"workspace"].join(":")),p={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Fw(n.observedAt??k(),"observedAt"),...i,author:C(n.author,t.author_default),...s===void 0?{}:{item_id:s},...a===void 0?{}:{source:a},...m===void 0?{}:{idempotency_key:m}};return{id:fP("sha256").update(Yt(p)).digest("hex").slice(0,24),...p}}function SP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function EP(e,t){let n=Vr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await gP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:em(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function AP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function Mw(e,t={}){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await kP(n,r,e),i=Lw.join(n,"improvement-ledger.json"),a=await ii({pmRoot:n,filePath:i,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:s=>{let c=Jl(s),m=SP(c,o);return m?{raw:s,result:m}:(c.observations.push(o),c.observations.sort((p,u)=>p.observed_at.localeCompare(u.observed_at)||p.metric.localeCompare(u.metric)||p.id.localeCompare(u.id)),{raw:`${Yt(c)}
28
- `,result:o})}});return{changed:a.changed,observation:a.result,ledger_path:"improvement-ledger.json"}}async function Dw(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=e.metric===void 0?void 0:$w(e.metric),r=e.since===void 0?void 0:Fw(e.since,"since"),o=bP(e.limit),i=Jl(await J(Lw.join(t,"improvement-ledger.json"))).observations.filter(s=>(n===void 0||s.metric===n)&&(e.itemId===void 0||s.item_id===e.itemId)&&(r===void 0||s.observed_at>=r)),a=new Map;for(let s of i){let c=a.get(s.metric)??[];c.push(s),a.set(s.metric,c)}return{observations:[...i].reverse().slice(0,o),total:i.length,truncated:i.length>o,trends:[...a].map(([,s])=>AP(s)).sort((s,c)=>s.metric.localeCompare(c.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function Uw(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function TP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function CP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function Xl(e=pr,t=xn){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function IP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function Ql(e,t=xn,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let i of t){let a=`${o.agent_harness}\0${i}`,s=r.get(a)??{harness:o.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1;let c=o.agent_provenance?.[i];c!=null&&c.value.length>0?s.observed+=1:c===null?s.unavailable+=1:s.legacy_missing+=1,r.set(a,s)}return[...r.values()].map(o=>{let i=o.observed+o.unavailable;return{...o,coverage:i===0?null:o.observed/i,inert:i>=n&&o.observed===0}}).sort((o,i)=>o.harness.localeCompare(i.harness)||o.dimension.localeCompare(i.dimension))}function RP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let p=`${c.agent_harness}\0${m}`,u=o.get(p)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(u.observed+=1,u.by_source[f.source]=(u.by_source[f.source]??0)+1),o.set(p,u)}let i=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[p])=>m.localeCompare(p)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),a=i.filter(c=>c.entries>=r),s=a.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:a.length>0&&s.length===0,minimum_coverage:n,minimum_entries:r,rows:i,failures:s}}function OP(e){let t=[...e].sort((i,a)=>i.ts.localeCompare(a.ts)||i.author.localeCompare(a.author)||i.op.localeCompare(a.op)||i.before_hash.localeCompare(a.before_hash)||i.after_hash.localeCompare(a.after_hash)),n=new Map,r=new Map;for(let i of t){let a=i.agent_episode,s=Uw(i),c=`${s.source}:${s.id}`,m=n.get(c);if(m){m.entries.push(i);continue}let p={id:s.id,...a?.label===void 0?{}:{label:a.label},...a?.parent_id===void 0?{}:{parent_id:a.parent_id},source:s.source,entries:[i],children:[]};n.set(c,p),a!==void 0&&r.set(s.id,p)}let o=[];for(let i of n.values()){let a=i.parent_id?r.get(i.parent_id):void 0;a&&TP(i,a,r)?a.children.push(i):o.push(i)}return CP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();var xP=1e4,Gw=1e5,PP=1e3,NP=30,LP=["append","comment","docs","file","learning","note","test_run"];function $P(e){let t=e??xP;if(!Number.isSafeInteger(t)||t<1||t>Gw)throw new l(`History analytics event limit must be an integer from 1 to ${Gw}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function jw(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",d.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function FP(e){let t=e?.trim();if(!t)return new Date(Date.now()-NP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),i=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*i).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function qw(e,t){let n=$P(t.eventLimit),r=FP(t.since),o=[],i=r,a=!1;for(;o.length<n;){let s=await Pa({pmRoot:e,since:i,limit:Math.min(PP,n-o.length),full:!0}),c=s.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),a=s.has_more,i=s.next_cursor,!s.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:a,...a?{next_cursor:i}:{},source:"history_event_index"}}}function MP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function DP(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function UP(e){return LP.some(t=>e.startsWith(t))}function Kw(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function GP(e,t,n){let r=new Map,o=new Map,i=new Map;for(let a of t){let s=MP(a.entry,e),c=DP(a.entry),m=o.get(a.item_id)===!0,p=c===void 0?m:n.has(c);if(c!==void 0&&o.set(a.item_id,p),!s)continue;let u=Kw(r,s);u.events+=1,UP(a.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!m&&p?(u.closes+=1,i.set(a.item_id,s)):c!==void 0&&m&&!p&&(u.reopens+=1)}return{buckets:r,lastCloseValue:i}}function jP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(i=>i.kind==="discovered_from").map(i=>i.id));for(let i of o){let a=t.get(i);a&&(Kw(e,a).defectEscapes+=1)}}}function qP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function KP(e,t,n,r,o,i){let{buckets:a,lastCloseValue:s}=GP(e,t,r);return jP(a,s,n),{dimension:e,status:a.size===0?"unavailable":"available",rows:[...a].map(([c,m])=>qP(c,m,o,i)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function zP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),i=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(i)?1:Math.max(1,(i-o)/864e5)}function HP(e,t,n){let r=Xl(t),o=Ql(e,xn,n),i=o.filter(s=>s.inert).map(s=>({harness:s.harness,dimension:s.dimension,explicit_samples:s.observed+s.unavailable})),a=r.filter(s=>!s.covered).map(s=>s.dimension);return{descriptors:r,observations:o,inert:i,undeclared:a,warnings:[...i.map(s=>`provenance_dimension_inert:${s.harness}:${s.dimension}:${String(s.explicit_samples)}`),...a.map(s=>`provenance_dimension_undeclared:${s}`)]}}function zw(e,t=pr,n={}){let r=jw(n.minimumSample);return{...HP(e.events.map(o=>o.entry),t,r),window:e.receipt}}function Hw(e,t,n,r={}){let o=jw(r.minimumSample),i=zP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(a=>KP(a,e.events,t,n,o,i)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3e70310d-fc4f-5ea9-b9fb-7c519035301b")}catch{}})();var BP=32;function VP(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let i=o.slice(0,o.indexOf("=")).trim();r.length>0&&i!=="unit"&&i!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Wr(e,t){let n=VP(e).map(r=>{let[o,...i]=r.split(","),a=o.indexOf("="),s=o.slice(0,a).trim(),c=o.slice(a+1).trim(),m=Number(c);if(a<=0||s.length===0||c.length===0||!Number.isFinite(m))throw new l(`Invalid --measure "${r}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,u;for(let f of i){let _=f.indexOf("="),h=f.slice(0,_).trim(),g=f.slice(_+1).trim();if(h==="unit"&&g.length>0)p=g;else if(h==="threshold"&&g.length>0&&Number.isFinite(Number(g)))u=Number(g);else throw new l(`Invalid --measure attribute "${f}"`,d.USAGE)}return{name:s,value:m,unit:p,threshold:u,recorded_at:t}});return[...new Map(n.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,BP)}function Bw(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function Vw(e,t){let n=e.flatMap(i=>i.measurements??[]).filter(i=>i.name===t).sort((i,a)=>a.recorded_at.localeCompare(i.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9d089ef-bca9-547f-a860-4002ec181cd0")}catch{}})();function YP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function JP(e,t,n,r,o){let i=wr(e,"type",r),a=new Set(i.rows.map(u=>u.key)),s=t.filter(u=>!a.has(u)),c=(o?[...i.rows,...s.map(u=>({label:u,key:u,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:i.rows).map(u=>({type:u.key??u.label,total:u.total,open:u.buckets.open,in_progress:u.buckets.in_progress,blocked:u.buckets.blocked,draft:u.buckets.draft,closed:u.buckets.closed,canceled:u.buckets.canceled,other:u.buckets.other})),m=YP([...n]);for(let u of e)m[u.status]+=1;let p=Object.fromEntries(Object.entries(m).filter(([,u])=>o||u>0));return{byType:c,byStatus:p,omitted:o?0:s.length+Object.values(m).filter(u=>u===0).length}}function XP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function QP(e){let t=Ww.join(e,"history");if(!await q(t))return[];await Rn({path:t,scope:"project"});let n=(await WP.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,i)=>o.localeCompare(i)),r=[];for(let o of n){let i=Ww.join(t,o),a=await J(i);a!==null&&(await Rn({path:i,scope:"project"}),r.push({id:o.slice(0,-6),raw:a}))}return r}async function ZP(e,t){let n=[],r=k();for(let o of Wr(t.observe,r))n.push(await Mw({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function eN(e,t,n){let r={};return t.byAssignee&&(r.assignee=wr(e,"assignee",n)),t.byTag&&(r.tag=wr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=wr(e,"priority",n)),r}async function tN(e,t,n,r,o){let i={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},a=o.provenanceCoverage||o.fleetAttribution?await qw(e,i):void 0;return{provenanceCoverage:o.provenanceCoverage&&a?zw(a,n.agent_identity?.harness_signals,i):void 0,fleetAttribution:o.fleetAttribution&&a?Hw(a,t,r,i):void 0}}function nN(e,t,n,r,o){let i=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...i?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:k()}}async function Zl(e,t={}){let n=E(process.cwd(),e.path);await I(n);let r=await A(n),o=await ZP(e,t),i=x(r,O()),a=$(r.schema),s=t.fieldUtilization?await Zu(n,r.item_format,i.type_to_folder,void 0,r.schema):await _e(n,r.item_format,i.type_to_folder,void 0,r.schema);await Hu({pmRoot:n,settings:r,itemIds:s.map(S=>S.id),commandLabel:"stats"});let c=Si(a),m=JP(s,i.types,a.definitions.map(S=>S.id),c,t.includeEmpty===!0),p=await QP(n),u=0;for(let S of p)u+=XP(S.raw);let f=t.storage?xw(p):void 0,_=t.metadataCoverage?cf(s,c):void 0,h=eN(s,t,c),g=t.fieldUtilization?lf(s):void 0,y=t.measurements===!0||o.length>0?await Dw({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:b}=await tN(n,s,r,a.terminal_statuses,t);return nN({items:s.length,history_streams:p.length,history_entries:u},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:g,improvementLedger:y,recordedObservations:o,provenanceCoverage:w,fleetAttribution:b})}import rN from"node:fs/promises";import Kt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a41eaff2-6a15-5e82-b3aa-03ca48fc3eb5")}catch{}})();var ev=Kt.join("runtime","telemetry","events.jsonl"),tv=Kt.join("runtime","telemetry","state.json"),oN=Kt.join("runtime","telemetry"),iN=20,nv=Jt.filter(e=>e.lifecycle==="deprecated"),Yw=["status","flush","stats","clear"],Jw=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},ed=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Xw=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},aN=e=>({command:ed(e.event.command,"<unknown>"),eventType:ed(e.event.event_type,"unknown"),eventSchemaVersion:Xw(e.event.schema_version),clientSchemaVersion:Xw(e.client_schema_version)}),sN=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),cN=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},lN=e=>{let t=e?.command_resolution;return ed(t,"")||void 0},rv=(e,t)=>{e[t]=(e[t]??0)+1},dN=(e,t)=>{let n=cN(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=lN(t);r!==void 0&&rv(e.resolution_counts,r)},mN=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Qw=(e,t)=>{t!==void 0&&e.add(t)},pN=(e,t)=>{let n=aN(t),r=e.get(n.command)??sN();r.count+=1,r.max_attempts=Math.max(r.max_attempts,mN(t.attempts)),rv(r.event_type_counts,n.eventType),Qw(r.event_schema_versions,n.eventSchemaVersion),Qw(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&dN(r,t.event.payload),e.set(n.command,r)},uN=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((i,a)=>i-a),o=Object.entries(t.resolution_counts).sort((i,a)=>i[0].localeCompare(a[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((i,a)=>i[0].localeCompare(a[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((i,a)=>i-a),client_schema_versions:[...t.client_schema_versions].sort((i,a)=>i-a),...r.length>0?{duration_p50_ms:Jw(r,.5),duration_p95_ms:Jw(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},fN=e=>{let t=(e??"status").trim().toLowerCase();if(Yw.includes(t))return t;throw Ce({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Yw,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},nd=()=>{throw new l("--limit must be a positive integer",d.USAGE)},ov=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?nd():e,_N=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?nd():ov(Number.parseInt(t,10))},hN=e=>e===void 0?iN:typeof e=="number"?ov(e):typeof e=="string"?_N(e):nd(),gN=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},yN=e=>{try{let t=JSON.parse(e);return gN(t)?t:void 0}catch{return}},wN=e=>e===null?[]:e.split(`
29
- `).map(t=>t.trim()).filter(t=>t.length>0),iv=e=>{let t=wN(e),n=[],r=0;for(let o of t){let i=yN(o);i===void 0?r+=1:n.push(i)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},vN=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bN=e=>{try{let t=JSON.parse(e);return vN(t)?t:{}}catch{return{}}},td=async e=>{let t=await J(e);return t===null||t.trim().length===0?{}:bN(t)};function kN(e){let t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-Math.max(1,Math.trunc(e))+1)).toISOString().slice(0,10)}function SN(e,t,n){let r=Object.create(null);for(let[o,i]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(o)||o<t||o>n||typeof i!="object"||i===null||Array.isArray(i))continue;let a=i;!Number.isSafeInteger(a.count)||a.count<1||typeof a.last_seen!="string"||!a.last_seen.startsWith(o)||(r[o]={count:a.count,last_seen:a.last_seen})}return r}function Zw(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,o=new Date().toISOString().slice(0,10);for(let i of nv){let a=r[i.alias];if(typeof a!="object"||a===null||Array.isArray(a))continue;let s=a;if(s.canonical!==i.canonical||typeof s.days!="object"||s.days===null||Array.isArray(s.days))continue;let c=SN(s.days,t,o);Object.keys(c).length>0&&(n[i.alias]={canonical:i.canonical,days:c})}return n}async function EN(e,t,n){let r=kN(n),o=await td(t),i=Zw(o.alias_usage,r);if(JSON.stringify(o.alias_usage??{})===JSON.stringify(i))return i;try{await nc(async()=>{let a=await td(t);if(a.alias_usage===void 0)return;let s=Zw(a.alias_usage,r);JSON.stringify(a.alias_usage)!==JSON.stringify(s)&&await te(t,`${JSON.stringify({...a,alias_usage:s},null,2)}
30
- `)},e,250)}catch{}return i}var Fa=e=>e??null,Ma=async e=>{let t=await A(e),n=Kt.join(e,ev),r=Kt.join(e,tv),o=await J(n),i=iv(o),a=await td(r),s=nf();return{enabled:t.telemetry.enabled&&!s.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:s,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:i.rows_total,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:Fa(a.last_attempted_flush_at),last_successful_flush_at:Fa(a.last_successful_flush_at),last_failed_flush_at:Fa(a.last_failed_flush_at),last_failed_flush_error:Fa(a.last_failed_flush_error)}},AN=e=>{let t=new Map;for(let n of e)pN(t,n);return[...t.entries()].map(([n,r])=>uN(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},TN=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Ma(t.globalPmRoot),generated_at:k()}),CN=async(e,t)=>{let n=await Ma(t.globalPmRoot);await af(t.globalPmRoot);let r=await Ma(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),i=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:i,queue_drained:i,status:r,generated_at:k()}},IN=async(e,t)=>{let n=hN(e.limit),r=await J(t.queuePath),o=iv(r),i=AN(o.entries),a=i.slice(0,n),s=await A(t.globalPmRoot),c=await EN(t.globalPmRoot,t.statePath,s.telemetry.retention_days),m=Object.entries(c).map(([p,u])=>{let f=Object.values(u.days);return{alias:p,canonical:u.canonical,count:f.reduce((_,h)=>Math.min(Number.MAX_SAFE_INTEGER,_+h.count),0),last_seen:f.map(_=>_.last_seen).sort().at(-1)}}).sort((p,u)=>u.count-p.count||p.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:i.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:i.length>a.length,stats:a,alias_usage:m,zero_use_aliases:nv.map(p=>p.alias).filter(p=>c[p]===void 0),alias_usage_retention_days:s.telemetry.retention_days,generated_at:k()}},RN=async(e,t)=>nc(async()=>{let n=await A(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await Fe(t.globalPmRoot,n,"telemetry:clear");let o=Kt.join(t.globalPmRoot,oN),i=await q(o);return await rN.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:i&&!await q(o),queue_exists_after:await q(t.queuePath),state_exists_after:await q(t.statePath),status:await Ma(t.globalPmRoot),generated_at:k()}},t.globalPmRoot),ON={status:TN,flush:CN,stats:IN,clear:RN};async function av(e,t){let n=fN(e.subcommand),r=lt(process.cwd());return ON[n](e,{globalPmRoot:r,queuePath:Kt.join(r,ev),statePath:Kt.join(r,tv)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b74444c7-c283-52b2-b65f-b0a086ff2b53")}catch{}})();var sv=20;function xN(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return sv;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?sv:t}function rd(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let i=Xo(r.recorded_at,o.recorded_at);if(i!==0)return i;let a=r.run_id.localeCompare(o.run_id);return a!==0?a:r.kind.localeCompare(o.kind)}),n=xN();return t.length>n?t.slice(t.length-n):t}async function Da(e){await se({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=rd([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="92f73d30-eac7-5c84-a7be-133323d1f549")}catch{}})();function cv(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(o))return[];t.push(o);continue}t.push(r)}return t}function od(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=cv(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let i of r){if(typeof o!="object"||o===null)return{found:!1,value:void 0};if(typeof i=="number"&&(!Array.isArray(o)||i>=o.length))return{found:!1,value:void 0};let a=Object.getOwnPropertyDescriptor(o,i);if(!a||!Object.hasOwn(a,"value"))return{found:!1,value:void 0};o=a.value}return{found:!0,value:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8316bbdc-b0f7-59b2-8875-1e0ad77eb8c0")}catch{}})();var PN=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],NN=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function lv(e,t){let n=`${e}
31
- ${t}`;for(let r of PN)if(r.regex.test(n))return{code:r.code};return null}function dv(e,t){for(let[n,r]of[["stdout",e],["stderr",t]]){let o=NN.find(i=>i.regex.test(r));if(o)return{code:o.receiptCode,stream:n}}}import{cp as LN,lstat as $N,mkdir as FN,readlink as MN,realpath as ad,stat as DN,symlink as mv}from"node:fs/promises";import{execFile as UN}from"node:child_process";import G from"node:path";import{promisify as GN}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="26cfff37-1b7e-556f-8656-2e5c7c9d616f")}catch{}})();var jN=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),pv=GN(UN);async function qN(e,t){let n=await Ua(G.join(e,".git"));if(!n||n.isDirectory()&&!await Ua(G.join(e,".git/HEAD")))return;let r=Object.fromEntries(Object.entries(process.env).filter(([o])=>!o.toUpperCase().startsWith("GIT_")));await pv("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:r,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await pv("git",["-C",t,"remote","remove","origin"],{env:r,timeout:1e4,windowsHide:!0})}function id(e){return e.split(G.sep).some(t=>jN.has(t.toLowerCase()))}function Yr(e){return e===".."||e.startsWith(`..${G.sep}`)||G.isAbsolute(e)}async function Ua(e){try{return await DN(e)}catch(t){if(!Be(t))throw t;return}}async function Ga(e){let t=[],n=e;for(;G.dirname(n)!==n;)try{return G.join(await ad(n),...t)}catch(r){if(!Be(r))throw r;t.unshift(G.basename(n)),n=G.dirname(n)}return G.join(await ad(n),...t)}async function KN(e,t,n){let r=G.relative(t,await Ga(e));if(!Yr(r))return r;let o=[],i=e;for(;G.dirname(i)!==i;){let a=await Ga(i),s=n.find(([,c])=>c===a);if(s)return G.join(s[0],...o);o.unshift(G.basename(i)),i=G.dirname(i)}return r}async function uv(e,t){let n=[],r=[],o=await ad(e),i=await Ga(G.resolve(t));if(![G.relative(o,i),G.relative(i,o)].every(Yr))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await FN(G.dirname(t),{recursive:!0}),await qN(o,t),await LN(o,t,{recursive:!0,force:!0,async filter(a){let s=G.relative(o,a);if(!s)return!0;if(id(s))return!1;if(G.basename(a).toLowerCase()==="node_modules"){if((await Ua(a))?.isDirectory()){let c=await Ga(a),m=G.relative(o,c);if(!Yr(G.relative(c,o))||!Yr(m)&&(id(m)||!m.split(G.sep).some(p=>p.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${s}`);n.push([s,c])}return!1}return(await $N(a)).isSymbolicLink()?(r.push([s,G.resolve(G.dirname(a),await MN(a)),(await Ua(a))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[a]of n)await mv(G.resolve(o,a),G.join(t,a),"junction");for(let[a,s,c]of r){let m=await KN(s,o,n);if(Yr(m)||id(m))throw new Error(`Source symlink must target included workspace source: ${a}`);await mv(G.resolve(t,m),G.join(t,a),c)}}import{spawn as Pv}from"node:child_process";import{cp as gv,mkdir as pd,mkdtemp as Nv,open as ld,readdir as dd,rm as Xr,symlink as VN}from"node:fs/promises";import{tmpdir as Lv}from"node:os";import oe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2661c74e-3e73-50f5-80a2-f103ff0cf2d4")}catch{}})();var fv=100;function sd(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,d.USAGE);return n}function zN(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=fv?t:`${t.slice(0,fv-3)}...`}function _v(e){return e.map((t,n)=>`${n+1}. ${zN(t)}`).join("; ")}function HN(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function BN(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function hv(e,t){let n=HN(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,i)=>i+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,d.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,d.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let i=[],a=[];for(let s=0;s<e.length;s+=1)BN(e[s],o)&&(a.push(e[s]),i.push(s+1));if(a.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${_v(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:a,selected_indexes:i,selected_count:a.length,skipped_count:e.length-a.length}}if(r==="only-index"){let o=sd(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${_v(e)}`,d.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5c2500e-ac89-5307-bfb3-073671fa4843")}catch{}})();var Ka=20*1024*1024,WN=3e3,YN=1e4,JN=5e3,yv=120,XN=new Set(["locks","extensions","runtime"]),QN=new Set(["history","index","search","extensions","locks","runtime"]),ZN=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],eL=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,tL=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,nL=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function ud(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function rL(){return ud("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",WN)}function oL(){return ud("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",YN)}function iL(){return ud("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",JN)}function aL(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function sL(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function fd(e){let t=0,n=0,r=0,o=0;for(let i of e){let a=i.execution_context;!a||a.is_pm_command!==!0||(t+=1,a.is_pm_tracker_read_command===!0&&(n+=1),a.mismatch_detected===!0&&(r+=1),a.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function cL(e){let t=e??"project";if(!ct.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function za(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(cn.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${cn.join(", ")}`,d.USAGE)}function lL(e){return dn(e??"source","--workspace-context")}function $v(e,t,n){return n?t:dn(e.workspace_context_mode,"linked test")??t}function Fv(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:za(e.pm_context_mode)}function Mv(e,t){return e==="auto"?t?"tracker":"schema":e}function dL(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function mL(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function pL(e,t){let n={};if(!e)return n;for(let r of e){let o=Fr(r,t);if(o)for(let[i,a]of Object.entries(o))n[i]=a}return n}function uL(e,t){if(!e)return[];let n=[];for(let r of e){let o=Mr(r,t);o&&n.push(...o)}return[...new Set(n)]}function fL(e){let t=Ha(e);return Tr(t).some(n=>mc(n)!==null)}function Dv(e){let t=Ha(e);return Tr(t).some(n=>{let r=mc(n);if(!r)return!1;let o=A_(r);return o?nL.has(o.subcommand):!1})}function ja(e){if(e)return k_.has(e.subcommand)?Kn(e.args,S_)?.subcommand:e.subcommand}function wv(e,t){if(e==="npx"||e==="bunx")return Di(t)?.command;if(e==="pnpm")return ja(Kn(t,y_));if(e==="npm")return ja(Kn(t,w_));if(e==="yarn")return ja(Kn(t,v_));if(e==="bun")return ja(Kn(t,b_))}function qa(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function cd(e){return!e||!uc(e.command)&&!E_(e.command)?!1:Mi(e.args)==="test-all"}var Uv=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),_L=new Set(["npx","bunx"]);function Gv(e){let t=e.split(" ").filter(a=>a.length>0),n=pc(t);if(n.length===0)return!1;let[r,...o]=n,i=Uv.get(r);if(i){let a=o.findIndex(s=>i.test(s));return a>=0?Gv(o.slice(a+1).join(" ")):!1}return uc(r)||fc(r)?Mi(o)==="test-all":r==="node"&&o.length>0&&fc(o[0])?Mi(o.slice(1))==="test-all":_L.has(r)?cd(Di(o)):r==="pnpm"?cd(_c(o)):r==="npm"?cd(hc(o)):!1}function jv(e){let t=Ha(e);return Tr(t).some(n=>Gv(n))}function qv(e){if(jv(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function Ha(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function Kv(e){let t=e.split(" ").filter(a=>a.length>0),n=pc(t);if(n.length===0)return!1;let[r,...o]=n,i=Uv.get(r);if(i){let a=o.findIndex(s=>i.test(s));return a>=0&&Kv(o.slice(a+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?hL(o):gL(r,o)}function hL(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function gL(e,t){return e==="npx"||e==="bunx"?qa(Di(t)?.command):e==="pnpm"||e==="npm"?qa((e==="pnpm"?_c(t):hc(t))?.command)||qa(wv(e,t)):(e==="yarn"||e==="bun")&&qa(wv(e,t))}function yL(e){if(jv(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function wL(e){return e?e.map(vL):[]}function vL(e){let t=e.trim(),n=vg(t)?oa(me(e,"--add"),"--add"):{command:t},r=ge(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return qv(r),{command:r,path:ge(n.path),scope:cL(n.scope),timeout_seconds:bL(ge(n.timeout_seconds),ge(n.timeout)),pm_context_mode:la(ge(n.pm_context_mode),"--add"),workspace_context_mode:dn(ge(n.workspace_context_mode),"--add"),env_set:Fr(ge(n.env_set),"--add"),env_clear:Mr(ge(n.env_clear),"--add"),shared_host_safe:ca(ge(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:mn(ge(n.assert_stdout_contains)),assert_stdout_regex:Vn(ge(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:mn(ge(n.assert_stderr_contains)),assert_stderr_regex:Vn(ge(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:da(ge(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:ma(ge(n.assert_json_field_equals),"--add"),assert_json_field_gte:pa(ge(n.assert_json_field_gte),"--add"),note:ge(n.note)}}function ge(e){let t=e?.trim();return t&&t.length>0?t:void 0}function bL(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",d.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(fe(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function kL(e){return e?e.flatMap(t=>{let n=Sg(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",d.USAGE);qv(o)}return n}):[]}function SL(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",d.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=me(n,"--remove"),i=o.path!==void 0?"path":"command",a=o.path??o.command;if(!a?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:i,value:a.trim()}}return{kind:"either",value:n}}):[]}function EL(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function AL(e){try{e.stdin?.end()}catch{}}function zv(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=yv?t:`${t.slice(0,yv-3)}...`}function Hv(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function md(e){try{process.stderr.write(`${e}
32
- `)}catch{}}function TL(e,t){if(!Hv(t))return null;let n=zv(e.command),r=Date.now();md(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let i=Date.now()-r;md(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${i} command="${n}"`)},oL());return o.unref?.(),o}function CL(e,t,n,r){if(!Hv(r))return;let o=zv(e.command),i=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",s=[];t.timedOut&&s.push("reason=timeout"),t.maxBufferExceeded&&s.push("reason=max_buffer"),t.outputTruncated&&s.push("output=truncated"),t.signal&&s.push(`signal=${t.signal}`);let c=t.exitCode===null?"null":String(t.exitCode),m=s.length>0?` ${s.join(" ")}`:"";md(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${c} elapsed_ms=${i}${m} command="${o}"`)}async function vv(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Pv("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function IL(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function RL(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await vv(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{vv(r)},rL()),t.forceKillTimer.unref?.()}}function OL(e){return new Promise(t=>{let n=!1,r=null,o=(i,a=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),a&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(i))};e.on("exit",(i,a)=>{n||(r=setTimeout(()=>{o({code:i,signal:a},!0)},iL()),r.unref?.())}),e.on("close",(i,a)=>{o({code:i,signal:a})})})}function xL(e,t,n,r,o){return Pv(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function bv(e){let t=await ld(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,Ka),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>Ka}}finally{await t.close()}}async function PL(e,t,n,r,o,i=process.cwd()){let a=Date.now(),s=await Nv(oe.join(Lv(),"pm-linked-test-output-"));try{let c=oe.join(s,"stdout.log"),m=oe.join(s,"stderr.log"),[p,u]=await Promise.all([ld(c,"w"),ld(m,"w")]),f;try{f=xL(e,n,p.fd,u.fd,i)}catch(H){throw await Promise.all([p.close(),u.close()]),H}let _=OL(f),h;f.on("error",H=>{h=H.message}),await Promise.all([p.close(),u.close()]),AL(f);let g={heartbeat:TL(r,o),forceKillTimer:null,timedOutTimer:null},y=RL(f,g),w=!1;g.timedOutTimer=setTimeout(()=>{w=!0,y()},t),g.timedOutTimer.unref?.();let{code:b,signal:S}=await _;IL(g);let[T,L]=await Promise.all([bv(c),bv(m)]),P=T.truncated||L.truncated,M=P?`
33
- [pm linked-test output truncated at ${Ka} bytes per stream; the child process continued to completion]
34
- `:"",K={stdout:`${T.text}${M}`,stderr:L.text,exitCode:b,signal:S,timedOut:w,maxBufferExceeded:!1,outputTruncated:P,spawnError:h};return CL(r,K,a,o),K}finally{await Xr(s,{recursive:!0,force:!0})}}function NL(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Ka} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function LL(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
35
- `);return ZN.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>eL.test(n)&&tL.test(n))}function $L(e){return LL(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function FL(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function Ba(e){let t=FL();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function kv(e,t){for(let[n,r]of Object.entries(t.env_set))ln.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)ln.has(n.toUpperCase())||delete e[n]}function ML(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function DL(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function UL(e,t,n){return{env_set:pL(e,"--env-set"),env_clear:uL(t,"--env-clear"),shared_host_safe:n===!0}}async function Jr(e,t,n=!1,r=pd){if(await q(e))try{await or("seed_linked_test",async()=>{if(await r(oe.dirname(t),{recursive:!0}),n){await gv(e,t,{recursive:!0,force:!0});return}await gv(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&Be(o))return;throw o}}async function Sv(e,t,n,r=!1){for(let[o,i]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let a=await J(ne(o));if(a!==null){let s=await A(i);await We({pmRoot:i,filePath:ne(i),raw:a,op:"settings:write",author:C(void 0,s.author_default),lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Jr(ne(o),ne(i));await Jr(oe.join(n.projectPmRoot,"extensions"),oe.join(e,"extensions"),!0),await Jr(oe.join(n.globalPmRoot,"extensions"),oe.join(t,"extensions"),!0)}async function Ev(e,t){if(!await q(e))return;let n=await dd(e,{withFileTypes:!0});for(let r of n){if(XN.has(r.name))continue;let o=oe.join(e,r.name),i=oe.join(t,r.name);if(r.isDirectory()){await Jr(o,i,!0);continue}r.isFile()&&await Jr(o,i)}}async function Av(e,t){let n=await J(ne(e));if(n===null||await q(Ws(e)))return;let r=await A(t);await Xr(Ws(t),{force:!0}),await Xr(ne(t),{force:!0}),await We({pmRoot:t,filePath:ne(t),raw:n,op:"settings:write",author:C(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function er(e){if(!await q(e))return 0;let t=0,n=await dd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||QN.has(r.name))continue;let o=oe.join(e,r.name),i;try{i=await dd(o,{withFileTypes:!0})}catch{continue}for(let a of i)a.isFile()&&Zd.some(s=>a.name.toLowerCase().endsWith(s))&&(t+=1)}return t}function GL(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function jL(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function qL(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?Le(e,t):Object.is(e,t)}function KL(e,t,n){let r=[];r.push(...Tv("stdout",t,e.assert_stdout_contains)),r.push(...Cv("stdout",t,e.assert_stdout_regex)),r.push(...Tv("stderr",n,e.assert_stderr_contains)),r.push(...Cv("stderr",n,e.assert_stderr_regex)),r.push(...zL(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},i=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(i).length>0))return r;let a;try{a=JSON.parse(t)}catch(s){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${s instanceof Error?s.message:String(s)}`),r}for(let[s,c]of Object.entries(o)){let m=od(a,s);if(!m.found){r.push(`assert_json_field_equals missing path "${s}"`);continue}let p=jL(c);qL(m.value,p)||r.push(`assert_json_field_equals mismatch at "${s}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(m.value)})`)}for(let[s,c]of Object.entries(i)){let m=od(a,s);if(!m.found){r.push(`assert_json_field_gte missing path "${s}"`);continue}if(typeof m.value!="number"||!Number.isFinite(m.value)){r.push(`assert_json_field_gte path "${s}" resolved to non-numeric value`);continue}m.value<c&&r.push(`assert_json_field_gte failed at "${s}" (expected >= ${c}, actual ${m.value})`)}return r}function Tv(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function Cv(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(i){r.push(`${e} regex assertion is invalid: /${o}/ (${i instanceof Error?i.message:String(i)})`)}return r}function zL(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function Iv(e){let t=Ha(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Tr(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&Kv(n))}function HL(e){return{root:e,schemaProjectPmPath:oe.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:oe.join(e,"schema","global"),trackerProjectPmPath:oe.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:oe.join(e,"tracker","global"),workspaceSnapshotRoot:oe.join(e,"workspace","project"),workspaceIsolatedRoot:oe.join(e,"workspace","isolated")}}function BL(e,t,n){return e.some(r=>$v(r,t,n)==="snapshot")}async function VL(e,t){let n=oe.join(e,".agents"),r=oe.join(n,"pm");await pd(n,{recursive:!0}),await Xr(r,{recursive:!0,force:!0}),await VN(t,r,process.platform==="win32"?"junction":"dir")}async function WL(e,t=Pr,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function YL(e,t,n){t&&(await Sv(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await Sv(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Ev(t.projectPmRoot,e.trackerProjectPmPath),await Ev(t.globalPmRoot,e.trackerGlobalPmPath),await Av(t.projectPmRoot,e.trackerProjectPmPath),await Av(t.globalPmRoot,e.trackerGlobalPmPath)))}function JL(e,t,n){return e.some(r=>{let o=r.command??"",i=o.length>0&&Dv(o),a=n?.autoPmContext===!0&&i?"auto":Fv(r,t,n?.overrideLinkedPmContext===!0);return Mv(a,i)==="tracker"})}async function XL(e,t){return{sourceProjectItemCount:t?await er(t.projectPmRoot):0,sourceGlobalItemCount:t?await er(t.globalPmRoot):0,schemaProjectItemCount:await er(e.schemaProjectPmPath),schemaGlobalItemCount:await er(e.schemaGlobalPmPath),trackerProjectItemCount:await er(e.trackerProjectPmPath),trackerGlobalItemCount:await er(e.trackerGlobalPmPath)}}function QL(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,i=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,a=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,s=e.workspaceContextMode==="isolated"?"":a;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:i,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==i),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:a,source_workspace_root:s,trust:e.trust}}async function ZL(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?za(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?fL(n):!1,o=r&&n?Dv(n):!1,i=e.options?.autoPmContext===!0&&o,a=i?"auto":Fv(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),s=Mv(a,o),c=s==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await VL(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await gc(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await gc(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:QL({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:a,effectivePmContextMode:s,autoPmContextApplied:i,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function Rv(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Qr(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function e$(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function t$(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return e$(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function n$(e){if(!e.linkedTest.command)return Rv(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=yL(e.linkedTest.command);return t?Rv(e.linkedTest,e.executionContext,t):null}function r$(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Qr(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?Qr(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function o$(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=mL({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Qr(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function i$(e){return n$(e)||t$(e)||r$(e)||o$(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!dL(e.linkedTest)?Qr(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function a$(e){let t=DL(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return kv(n,e.runtimeDirectives),kv(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&ML(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Sr]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Sr]="read_only"),n}function s$(e,t,n,r){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...r?{execution_receipt:r}:{}}}function Ov(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function c$(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:GL(e.execution),failure_category:$L(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:NL(e.execution,e.timeoutMs)}}function l$(e){let t=dv(e.execution.stdout,e.execution.stderr);if(e.options?.failOnEmptyTestRun===!0||Iv(e.linkedTest.command??"")){let r=lv(e.execution.stdout,e.execution.stderr);if(r)return Ov({...e,emptyRunSignal:r});if(Iv(e.linkedTest.command??"")&&!t)return Ov({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let n=KL(e.linkedTest,e.execution.stdout,e.execution.stderr);return n.length>0?Qr(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${n.join("; ")}`,e.execution):s$(e.linkedTest,e.executionContext,e.execution,t)}async function d$(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await PL(t,n,a$(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?l$({...e,execution:r}):c$({...e,execution:r,timeoutMs:n})}async function _d(e,t,n){let r=[],o=await Nv(oe.join(Lv(),"pm-linked-test-")),i=HL(o),a=za(n?.pmContext),s=lL(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=UL(n?.envSet,n?.envClear,n?.sharedHostSafe),p=n?.sourceRoots,u=C_(),f=JL(e,a,n),_=BL(e,s,n?.overrideLinkedWorkspaceContext===!0),h=await T_(u);try{await WL(i,Pr,f),await pd(i.workspaceIsolatedRoot,{recursive:!0}),await YL(i,p,f),_&&await uv(u,i.workspaceSnapshotRoot);let g=await XL(i,p);for(let y=0;y<e.length;y+=1){let w=e[y],b=$v(w,s,n?.overrideLinkedWorkspaceContext===!0),S=await ZL({linkedTest:w,layout:i,counts:g,sourceRoots:p,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:s,workspaceContextMode:b,currentSourceRef:h,sourceWorkspaceRoot:u}),T=i$({linkedTest:w,executionContext:S.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:S.linkedOverridePmContextMode,options:n});if(T){r.push(T);continue}r.push(await d$({linkedTest:w,index:y,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:S.executionContext,options:n}))}}finally{await Xr(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function m$(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,i=await z(n,t,r.id_prefix,r.item_format,o);if(!i)throw new l(`Item ${t} not found`,d.NOT_FOUND);let a=await ae(i,{schema:r.schema});return{itemId:i.id,tests:a.document.metadata.tests??[],testRuns:a.document.metadata.test_runs??[],changed:!1,removed:0}}function p$(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function u$(e,t){let n=[...e];for(let r of t)n.some(o=>p$(o,r))||n.push(r);return n}function f$(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((i,a)=>r.has(a+1)?!1:!t.some(s=>s.kind==="command"?i.command===s.value:s.kind==="path"?i.path===s.value:i.command===s.value||i.path===s.value));return{tests:o,removed:e.length-o.length}}function _$(e,t,n,r){return f$(u$(e,t),n,r)}function h$(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function g$(e){if(h$(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",d.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",d.USAGE)}async function y$(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:i,adds:a,removes:s,removeIndexes:c}=e;if(a.length===0&&s.length===0&&c.length===0)return m$({id:t,pmRoot:r,settings:o,typeToFolder:i});let m=0,p=await se({pmRoot:r,settings:o,id:t,op:a.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let f=u.metadata.tests??[],_=_$(f,a,s,c);if(m=_.removed,(s.length>0||c.length>0)&&m===0)throw new l("No linked tests matched the requested removal selector",d.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...s.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return u.metadata.tests=_.tests,{changedFields:Le(f,_.tests)?[]:["tests"]}}});return{itemId:p.item.id,tests:p.item.tests??[],testRuns:p.item.test_runs??[],changed:p.changedFields.length>0,removed:m}}function w$(e,t){g$(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:sd(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?hv(t,n):void 0,o=e.timeout===void 0?void 0:fe(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:za(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function v$(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await _d(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:lt(process.cwd())}})}function b$(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=fd(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function k$(e){let t=sL(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=k(),i=Wr(e.options.measure,o);return{run_id:aL("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:i.length>0?i:void 0,executions:e.runResults.filter(a=>a.command?.trim()).slice(0,32).map(a=>({command:a.command.trim(),requested_pm_context_mode:a.execution_context?.requested_pm_context_mode,pm_context_mode:a.execution_context?.pm_context_mode,workspace_context_mode:a.execution_context?.workspace_context_mode,trust_reason:a.execution_context?.trust.reason}))}}async function S$(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:i,runResults:a,failOnSkippedTriggered:s,warnings:c}=e;if(t.run!==!0||!i)return;let m=k$({options:t,runStartedAt:i,runResults:a,failOnSkippedTriggered:s});if(r.testing.record_results_to_items!==!0)return{entry:m,receipt:{recorded:!1,reason:"tracking_disabled",run_id:m.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Da({pmRoot:n,settings:r,itemId:o,author:C(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),{entry:m,receipt:{recorded:!0,reason:"recorded",run_id:m.run_id}}}catch(p){return c.push(`test_result_tracking_failed:${o}:${p instanceof Error?p.message:String(p)}`),{entry:m,receipt:{recorded:!1,reason:"write_failed",run_id:m.run_id}}}}function xv(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),i=e.metricBelow.slice(0,o).trim(),a=e.metricBelow.slice(o+1).trim(),s=Number(a);if(o<=0||i.length===0||a.length===0||!Number.isFinite(s))throw new l("--metric-below must use name=value",d.USAGE);r=Bw(t,i,s)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Vw(t,e.metricDiff)}}async function E$(e,t,n){if(e.acknowledgeLinkedTests===!0)return I_(t,n,k())}function A$(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:i,warnings:a,recording:s,measurementProjection:c}=e;return{ok:n.every(m=>m.status!=="failed")&&i!==!0,id:t.itemId,tests:t.tests,run_results:n,failure_categories:r,selection:o?{selector:o.selector,requested:o.requested,selected_indexes:o.selected_indexes,selected_count:o.selected_count,skipped_count:o.skipped_count}:void 0,fail_on_skipped_triggered:i?!0:void 0,warnings:a.length>0?a:void 0,changed:t.changed||s?.receipt.recorded===!0,...s?{evidence_recording:s.receipt}:{},count:t.tests.length,...t.removed>0?{removed:t.removed}:{},...c}}async function Va(e,t,n){let r=Nt(),o=E(process.cwd(),n.path);await I(o);let i=await A(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);Wr(t.measure,"validation"),xv(t,[],void 0);let a=x(i,O()),s=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),p=[...wL(s),...kL(c)],u=await zn(p,C(t.author,i.author_default),k())??[],f=SL(m),_=EL(t.removeIndex),h=await y$({id:e,options:t,pmRoot:o,settings:i,typeToFolder:a.type_to_folder,adds:u,removes:f,removeIndexes:_}),g=w$(t,h.tests),y=await E$(t,o,h.tests),w=t.run===!0?k():void 0,b=await v$({options:t,runOptions:g,pmRoot:o,untrustedLinkedTestsPolicyEnabled:i.testing.allow_untrusted_linked_tests}),S=Ba(b),T=t.run===!0&&t.failOnSkipped===!0&&b.some(H=>H.status==="skipped"),L=b$(t,g.runSelection,b);y&&L.push(`linked_test_trust_acknowledged:${y.acknowledged}`);let P=await S$({options:t,pmRoot:o,settings:i,itemId:h.itemId,runStartedAt:w,runResults:b,failOnSkippedTriggered:T,warnings:L}),M=P?.receipt.recorded?rd([...h.testRuns,P.entry]):h.testRuns,K=xv(t,M,P?.entry);return A$({item:h,runResults:b,failureCategories:S,runSelection:g.runSelection,failOnSkippedTriggered:T,warnings:L,recording:P,measurementProjection:K})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8371273e-fb3c-5615-bd0e-f7aeb2a0b303")}catch{}})();var T$=(e,t)=>{if(e===void 0)return;let n=ee(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},C$=e=>{if(e===void 0)return;let t=fe(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},Bv=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,d.USAGE);return n},I$=e=>e instanceof Error?e.message:String(e),R$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},O$=e=>e.trim().replaceAll(/\s+/g," "),x$=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),P$=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),N$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},L$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Wa=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Vv=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),$$=e=>typeof e=="number"?e:void 0,F$=e=>{let t={assert_stdout_contains:Wa(e.assert_stdout_contains),assert_stdout_regex:Wa(e.assert_stdout_regex),assert_stderr_contains:Wa(e.assert_stderr_contains),assert_stderr_regex:Wa(e.assert_stderr_regex),assert_stdout_min_lines:$$(e.assert_stdout_min_lines),assert_json_field_equals:Vv(e.assert_json_field_equals),assert_json_field_gte:Vv(e.assert_json_field_gte)};return JSON.stringify(t)},M$=e=>{let t=hd(e.command);return t!==void 0?`command:${e.scope}:${O$(t)}`:`path:${e.scope}:${hd(e.path)??""}`},Wv=e=>{let t=x$(e.env_set),n=P$(e.env_clear),r=N$(e.pm_context_mode),o=L$(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",a=F$(e);return`${M$(e)}:${t}:${n}:${r}:${o}:${i}:${a}`},D$=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,U$=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},G$=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Ya=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
36
- `)}catch{}},j$=async(e,t,n)=>{let r=[],o=0;for(let i of e){let a=await Va(i.id,{run:!1},{...t,path:n});o+=a.tests.length,r.push({item:i,tests:a.tests})}return{itemTests:r,linkedTests:o}},q$=async e=>{let t=$(e.settings.schema),n=x(e.settings,O()),r=T$(e.options.status,t),o=Bv(e.options.limit,"--limit"),i=Bv(e.options.offset,"--offset")??0,a=(await _e(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(s=>r?s.status===r:!0).sort((s,c)=>s.id.localeCompare(c.id));return{filteredItems:o===void 0?a.slice(i):a.slice(i,i+o),statusFilter:r,limitFilter:o,offsetFilter:i}},K$=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=Wv(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,D$(t.get(o),r.timeout_seconds))}return t},z$=async(e,t)=>{let n=[],r=e.tests.map(p=>{let u=Wv(p),f=t.seenTestKeys.has(u);if(!f){t.seenTestKeys.add(u);let _=t.effectiveTimeoutByKey.get(u);n.push(_===void 0?p:{...p,timeout_seconds:_})}return{test:p,key:u,duplicate:f}}),o=n.length>0?await _d(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],i=0,a=r.map(({test:p,key:u,duplicate:f})=>{if(!f){let _=o[i];return i+=1,_}return{command:p.command,path:p.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),s=U$(a),c=Ba(a),m=await V$(e,s,a,t);return{passed:s.passed,failed:s.failed,skipped:s.skipped,trackingWarnings:m,failureCategories:c,result:{ok:s.failed===0&&!(t.options.failOnSkipped===!0&&s.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:s.passed,failed:s.failed,skipped:s.skipped,run_results:a,failure_categories:c}}},H$=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),B$=e=>e?!0:void 0,V$=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=H$(t,r.options);await Da({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:k(),recorded_at:k(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:B$(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${I$(o)}`]}return[]},W$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},hd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},Y$=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:lt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:K$(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:R$(),trackingAttempt:W$(),trackingResumedFrom:hd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),J$=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:Ba([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},X$=async(e,t,n)=>{for(let[r,o]of e.entries()){Ya(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let i=await z$(o,t);G$(n.failureCategories,i.failureCategories),n.passed+=i.passed,n.failed+=i.failed,n.skipped+=i.skipped,n.trackingWarnings.push(...i.trackingWarnings),n.results.push(i.result),Ya(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${i.failed===0?"passed":"failed"} passed=${i.passed} failed=${i.failed} skipped=${i.skipped}`)}},Q$=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=fd(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},Z$=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),eF=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),tF=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await q$({pmRoot:n,settings:r,options:e}),i=C$(e.timeout),a=k(),s=await j$(o.filteredItems,t,n);return Ya(e,eF({...o,linkedTests:s.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:s.itemTests,linkedTests:s.linkedTests,defaultTimeoutSeconds:i,runStartedAt:a}},nF=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},Yv=async(e,t)=>{let n=await tF(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=J$(e,n.linkedTests,n.filteredItems),i=Y$({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await X$(n.itemTests,i,r),Q$(e,r);let a=nF({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Ya(e,`end status=${a.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),Z$({ok:a.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:a.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="920b5725-710a-5839-86e3-dbdbc8a602a8")}catch{}})();function Jv(e,t,n){let r;if(typeof e.lines=="string")r=Ni(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");r=Ni(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="09fa5b5c-d44a-55e4-9365-a08702d8a952")}catch{}})();function Ne(e,t){let n=v(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}function vn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9a4dbe8d-9341-55f1-8c4a-d476c2b338e5")}catch{}})();function rF(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:v(e.args,"name")??v(e.options,"name"),author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ye(n)}}function oF(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=vn({list:()=>Of(t.global),show:()=>xf(r,t.global),"show-status":()=>Pf(r,t.global),"list-fields":()=>$f(t.global),"show-field":()=>Ff(r,t.global),"remove-type":()=>Tf(r,{author:o,force:i},t.global),"remove-field":()=>Lf(r,{author:o,force:i},t.global),"remove-status":()=>Rf(r,{author:o,force:i},t.global),"apply-preset":()=>Mf(v(t.args,"typePreset")??v(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function iF(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,a=t.args.commands??t.options.commands,s=t.args.requiredTypes??t.options.requiredTypes;return Nf(n,{type:v(t.args,"fieldType")??v(t.options,"fieldType"),commands:a===void 0?void 0:ye(a),description:v(t.args,"description")??v(t.options,"description"),cliFlag:v(t.args,"cliFlag")??v(t.options,"cliFlag"),alias:i,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:s===void 0?void 0:ye(s),author:r,force:o},t.global)}function aF(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,a=t.args.role??t.options.role;return If(n,{role:a===void 0?void 0:ye(a),alias:i,description:v(t.args,"description")??v(t.options,"description"),order:Me(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function sF(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return Af(n,{description:v(t.args,"description")??v(t.options,"description"),defaultStatus:v(t.args,"defaultStatus")??v(t.args,"default_status")??v(t.options,"defaultStatus")??v(t.options,"default_status"),folder:v(t.args,"folder")??v(t.options,"folder"),alias:i,author:r,force:o},t.global)}function cF(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=v(t.args,"to")??Ne(t.options,"to"),s=v(t.args,"migrationId")??v(t.args,"migration_id")??v(t.options,"migrationId")??v(t.options,"migration_id"),c=v(t.args,"fieldTypeScope")??v(t.options,"fieldTypeScope")??v(t.args,"type")??v(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:a}:n==="rename-field"?{kind:"rename-field",from:r??"",to:a,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:a};return Sf(m,{migrationId:s,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function Xv(e){let t=rF(e);ju(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Cn.find(o=>o===t.subcommand);if(n)return kf(n,t.name,{definition:e.args.definition??e.options.definition,policy:v(e.args,"policy")??v(e.options,"policy"),message:v(e.args,"message")??v(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=oF(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return cF(t);if(t.subcommand==="add-field")return iF(t);if(t.subcommand==="add-status")return aF(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Df({minCount:Me(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):sF(t);throw Ce({command_path:"schema",token:t.subcommand,allowed:Ef,exit_code:64})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32f1d276-9fdd-5525-8c99-742d597f898a")}catch{}})();function Ja(e){return v(e.args,"target")??v(e.options,"target")}function be(e,t=e.options){return e.id??Ne(t,"id")}async function lF(e){let t=On("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),Pc(await ht(v(e.args,"status")??v(t,"status"),t,e.global),t)}async function dF(e){let t=Ne(e.args,"query"),n=On("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Pc(await Rr(t,n,e.global),n)}async function mF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return Ee(await Gt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function pF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Ee(await Yc(be(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function uF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return Ee(await at(be(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function fF(e){let t=Vi(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),Ch(be(e),t,e.global)}function Qv(e,t){return t_(Jv(e.options,t,Me),e.global)}function _F(e){let t=ye(e.options.lookupPath);if(t&&t.length>0)return Qv(e,t);let n=be(e);return e.options.discover===!0?dc(n,Ii(e.options),e.global):e_(n,Er(e.options),e.global)}function hF(e){return av({subcommand:v(e.args,"subcommand")??v(e.options,"subcommand"),limit:Hf(e.args,e.options)},e.global)}function gF(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Ar(e.global,t)}function yF(e){let t=v(e.args,"configAction")??v(e.options,"configAction")??v(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);let n=v(e.args,"value")??v(e.options,"value"),r=v(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return Yh(v(e.args,"scope")??v(e.options,"scope")??"project",t,v(e.args,"key")??v(e.options,"key"),r,e.global,v(e.options,"policy")===void 0?n:void 0)}function wF(e){let t=e.options;return D_(M_(t),e.global)}function vF(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}async function bF(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=he(e.args,e.options),i=await Iy({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:kF(e),reorderTo:vF(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&qf(e.args)&&(i.mutation_receipt=Ia(i,void 0)),t==="show"?i:Ee(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function kF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function SF(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=t.trim().toLowerCase(),r=v(e.args,"name")??v(e.options,"name"),o=vn({list:()=>Ky(),show:()=>zy(r),lint:()=>Hy(r),apply:()=>By(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!o)throw Ce({command_path:"profile",token:t,allowed:qy,exit_code:64});return o()}async function EF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return Ee(await cg(be(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function AF(e){let{changedFields:t,runnerOptions:n}=he(e.args,e.options);return Ee(await Ny(xi(n),e.global),{changedFields:t})}async function TF(e){let{changedFields:t,runnerOptions:n}=he(e.args,e.options),r=v(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Ee(await yg(Oi(o),e.global),{changedFields:t})}async function CF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options),o=v(r,"target")??Ne(e.args,"target");return Ee(await an(be(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function IF(e){let t={...e.args,...e.options};return n_(Ne(t,"subcommand"),v(t,"id")??e.id,v(t,"target"),Yf(t),e.global)}function RF(e){return Xf(E(process.cwd(),e.global.path),{...e.args,...e.options})}var Zv={init:e=>Pr(v(e.args,"prefix"),e.global,e.options),context:e=>vc(On("context",e.options),e.global),next:e=>Ir(On("next",e.options),e.global),eval:Tw,events:Cw,merge:Iw,workspace:Rw,meet:La,event:La,remind:La,list:lF,get:e=>{let t=be(e);return kc(t,e.global,On("get",e.options,[t]))},search:dF,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ye(e.options.status);return lc(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:v(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Me(e.options.limit,"limit")})},create:mF,copy:pF,focus:e=>cl(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:uF,"item-reopen":_y,restore:CF,claim:py,release:fy,"start-task":e=>_n(e,"start_task"),"pause-task":e=>_n(e,"pause_task"),"close-task":e=>_n(e,"close_task"),close:uy,comments:fF,notes:e=>Ly(be(e),Vi(e.options),e.global),learnings:e=>sg(be(e),Vi(e.options),e.global),files:_F,docs:e=>Zf(be(e),Er(e.options),e.global),test:e=>Va(be(e),e.options,e.global),"test-all":e=>Yv(e.options,e.global),telemetry:hF,validate:e=>Ui(e.options,e.global,{runUpdate:(t,n,r)=>at(t,n,r)}),health:gF,assurance:e=>R_(e.args,e.options,e.global),contracts:e=>Tc(e.options,e.global),config:yF,activity:wF,aggregate:e=>bc(e.options,e.global),extension:e=>Gn(Ja(e),e.options,e.global),package:e=>Gn(Ja(e),e.options,e.global),install:e=>Gn(Ja(e),{...e.options,install:!0},e.global),upgrade:e=>x_(Ja(e),e.options,e.global),delete:e=>sl(be(e),e.options,e.global),deps:e=>Qf(be(e),e.options,e.global),graph:IF,"files-discover":e=>dc(be(e),e.options,e.global),"files-lookup":e=>Qv(e,ye(e.options.paths)),history:e=>U_(be(e),e.options,e.global),"history-redact":e=>ag(be(e),e.options,e.global),"history-repair":tg,"history-compact":ng,"history-attest":e=>P_(e.options,e.global),"history-author-acknowledge":RF,plan:bF,schema:Xv,profile:SF,stats:e=>Zl(e.global,Ow(e.options)),append:EF,"update-many":AF,"close-many":TF,gc:e=>O_(e.global,e.options)};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96234a42-d25c-5221-a12b-a992925a13ba")}catch{}})();var OF=new Map;function gd(){OF.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69f9c792-7ee1-5e4b-9900-38e1c887c4d4")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5417c092-2e52-5b18-bcb6-da34f07f595f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ba66cac9-25d6-559e-95d1-71db5c404807")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f06f072-47a7-560e-9291-72e47225a73c")}catch{}})();function eb(){return{metadata:{},body:""}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f5ba86ac-336e-5fdb-a8fb-d8d7e7c1a504")}catch{}})();var nb=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:du().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],tb=new Map;for(let e of nb){tb.set(e.id,e);for(let t of e.aliases)tb.set(t,e)}function yd(){return nb.map(e=>e.id)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b11b0e04-bad1-5090-8df9-d922568db013")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c8b847c-770a-556f-a7ea-151c82629318")}catch{}})();var Y5=[...oo],J5=[...io],wd=new Set(Jt.filter(e=>e.hidden).map(e=>e.alias)),rb=lu("full").filter(e=>!e.includes(" ")&&!wd.has(e)),xF=N(ho),PF=N(go),NF=N(Eo),LF=N(Ro),ob=mr("restore",It("restore")),ib=mr("history-attest",It("history-attest")),$F=N(Oo),FF=N(Zm),MF=N(ep),DF=N(Io),UF=N(Lo),GF=N(xo),jF=N(Po),qF=N(So),vd=[...new Set(Se.map(e=>e.canonical_argv[0]))],ab=[...new Set(Se.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],X5=new Set(fo.filter(e=>e.disposition==="package_owned").map(e=>B(e.command))),sb=Se.filter(e=>e.canonical_argv[0]==="history"),KF=sb.map(e=>e.canonical_argv[1]).join(" ");var zF=sb.map(e=>({...e,flags:N(It(e.alias))})),HF=N(yo),BF=N(wo,!1),VF=N(No),WF=N(lr),YF=N(dr),JF=N(Do),XF=N(Fo),QF=N(To),ZF=N(Mo),eM=N($o),tM=N(Uo),nM=N(Ao),rM=N(Co),oM=N(bo),iM=N(Go),aM=N(vo),bd=`${Cn.join(" ")} list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status`;var sM=N(jo),cM=`${sM} bash zsh fish`,kd=Qa(yd()),Xa="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",Sd=`${Xa} upgrade`,lM=N(ko),dM=N(sr),mM=N(cr);var pM=N(It("close")),uM=N(It("close-task")),fM=N(It("release")),_M=N(It("claim"));var cb=_o.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),Ed=[...Jo].join("|"),Ad=[...Jo].map(e=>`${e}=*`).join("|"),Td=[...cb.split(" ").filter(e=>!Jo.has(e)),"-h","-V"].join("|");function Qa(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5cb75946-44c9-5e10-a39c-c981011b7efe")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b0fbba44-df4b-5cf3-968c-a0e86fd4afb5")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d548143c-24be-5420-8185-f52e3941cff3")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7cfbd72-3010-53e7-946b-e65842ee4ceb")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d5f2c177-4eed-5bc5-89b5-3c5d689f902a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e9a2374-d190-52e1-8afd-14e1954863f0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c3e80fb-2ae7-5d3b-98bd-eacdabd2be6d")}catch{}})();var fb=Symbol("pm.active-extension-host-context");function je(e){return{fullChangedFields:!0,options:e}}var U=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[fb]=!0,n}run(t,n={}){return _b({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return vh(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return ic(await this.list(oc(t)))}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}append(t,n,r={}){return this.runTyped("append",{id:t,...je(Dt(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,i={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,r={}){return this.runTyped("schema",{name:n,options:{...r,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...i===void 0?{}:{reorderTo:i},options:Dt(r,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",je(t))}update(t,n={}){return this.runTyped("update",{id:t,...je(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...je(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...je(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...je(t)})}release(t,n={}){return this.runTyped("release",{id:t,...je(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...je(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...je(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...je(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...je(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...je(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...je(r)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function EM(e={},t={}){return new U(t).context(e)}function AM(e={},t={}){return new U(t).list(e)}function TM(e={},t={}){return new U(t).listAllComplete(e)}function CM(e,t={},n={}){return new U(n).search(e,t)}function IM(e,t={},n={}){return new U(n).get(e,t)}function RM(e={},t={}){return new U(t).next(e)}function OM(e={},t={}){return new U(t).aggregate(e)}function xM(e,t={},n={}){return new U(n).comments(e,t)}function PM(e,t={},n={}){return new U(n).notes(e,t)}function NM(e,t={},n={}){return new U(n).learnings(e,t)}function LM(e,t={},n={}){return new U(n).files(e,t)}function $M(e,t={},n={}){return new U(n).filesDiscover(e,t)}function FM(e,t={},n={}){return new U(n).docs(e,t)}function MM(e,t={},n={}){return new U(n).deps(e,t)}function DM(e,t={},n={},r={}){return new U(r).graph(e,t,n)}function UM(e,t,n={},r={}){return new U(r).append(e,t,n)}function GM(e={},t={}){return new U(t).create(e)}function jM(e,t={},n={}){return new U(n).update(e,t)}function qM(e,t,n={},r={}){return new U(r).reopen(e,t,n)}function KM(e,t,n={},r={}){return new U(r).close(e,t,n)}function zM(e,t={},n={}){return new U(n).claim(e,t)}function HM(e={},t={}){return new U(t).claimNext(e)}function BM(e,t={},n={}){return new U(n).release(e,t)}function VM(e,t={},n={}){return new U(n).copy(e,t)}function WM(e,t={},n={}){return new U(n).delete(e,t)}function YM(e,t,n={},r={}){return new U(r).restore(e,t,n)}function JM(e,t={},n={}){return new U(n).focus(e,t)}var pb=jp(),XM=new SM;function Za(){Os(tm()),xs(nm()),Ps(rm()),Ns(om()),Ls(im()),$s(am()),Fs(sm())}async function QM(e,t,n,r){return qp(()=>t===void 0?pb.read(()=>ub(e,n,r)):pb.write(()=>eD(t,()=>ub(e,n,r))))}async function ub(e,t,n){let r=E(t,e.path);if(e.noExtensions)return Za(),Ic({pmRoot:r},()=>n(null));if(!await q(ne(r)))return Za(),n(null);let o=null,i;try{let a=await A(r),s=await ir({pmRoot:r,settings:a,cwd:t,noExtensions:!1}),c=await ar({...s,loaded:s.loaded});i={loadResult:s,activationResult:c},Os(c.hooks),xs(c.commands),Ps(c.parsers),Ns(c.preflight),Ls(c.services),$s(c.renderers),Fs(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:s.loaded}}catch(a){Za(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",a)}try{return await Ic({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Za(),i&&await bs(i.loadResult,i.activationResult).catch(()=>{})}}async function ZM(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let i=jn(e),a=o.registrations.commands.find(m=>jn(m.action)===i)?.command??o.commands.handlers.find(m=>jn(m.command)===i)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let s=typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension",c=await Yo({command:Ri(a),args:ye(n.args??t.args),options:cc(t,n),global:r,pm_root:o.pmRoot,sdk:_h(o.pmRoot,U.forActiveExtensionHost({pmRoot:o.pmRoot,author:s}),s,Ri(a))});if(!c.handled){let m=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${m}`,d.USAGE)}return c.result}async function eD(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function tD(e){let t=Ne(e,"action"),n=jn(t),r=vn(kh,n),o=r?.action??n,i={...e,action:o};return r?.options!==void 0&&(i.options={...r.options,...ws(e.options)}),o==="package"&&(i.options={...ws(i.options),vocabulary:"package"}),{action:o,args:i}}async function _b(e){let t=tD(e),n=ac(t.args),r=Vf(t.action),o=v(t.args,"cwd"),i=o??process.cwd();t.action==="init"&&(n[xc]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(i,n.path));try{return t.action==="history-attest"?await Cd(t.action,t.args,n,null):e[fb]===!0||XM.getStore()===!0?await Cd(t.action,t.args,n,null):await QM(n,o,i,a=>Cd(t.action,t.args,n,a))}finally{r&&gd()}}async function Cd(e,t,n,r){let o=sc(t,e);Gs(e,o),Vp(e,o);let i={action:e,args:t,options:o,id:v(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},a=vn(Zv,e),s=a?await a(i):await ZM(e,t,o,n,r);if(e==="history-attest")return s;{o.resolvedOutputFormat="json";let c=Xp(e,o,s);return await fh(E(process.cwd(),n.path),c),c}}var nD={closeManyOptionsFromFlat:Oi,extensionOptionsFromArgs:cc,globalOptions:ac,mutationListOptions:Wf,normalizeActionName:jn,normalizeCommandPath:Ri,normalizeMcpUpdateOptions:Jf,normalizeMcpOptionsArrays:Bf,optionsWithAuthor:sc,readRequiredString:Ne,readScalarString:Kf,readScalarStringAllowBlank:zf,readStringArray:ye,updateManyOptionsFromFlat:xi,withAddNoteOption:Er,withFilesDiscoveryOptions:Ii,withMutationCompaction:he};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=nD);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48d03e9b-14a4-545c-8e5d-5f5f2092a113")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38023567-8a5b-5e25-8d71-5112f74d1894")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b01ebcad-90b3-5f26-8a26-18b254a21be9")}catch{}})();export{xn as AGENT_PROVENANCE_DIMENSIONS,wu as BASELINE_ITEM_FORMAT_VERSION,hk as BUILTIN_AGENT_PROVENANCE_ADAPTERS,pr as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,oo as BUILTIN_ITEM_TYPE_VALUES,ao as CONFIDENCE_TEXT_VALUES,vu as CURRENT_ITEM_FORMAT_VERSION,Vt as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,Sn as ISSUE_SEVERITY_VALUES,Gd as ITEM_TYPE_VALUES,pf as PM_CLI_EXPECTED_ERROR_NAME,nk as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,ek as PM_READ_OUTPUT_DIMENSIONS,tk as PM_READ_OUTPUT_OPTION_FLAGS,Ds as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,U as PmClient,kn as RISK_VALUES,xk as SEMANTIC_ATTRIBUTION_LIMITS,io as STATUS_VALUES,_k as agentSessionEnvironment,OM as aggregate,Xl as analyzeAgentProvenanceDescriptorCoverage,mk as analyzeSdkCliParameterCompleteness,UM as append,ok as applyReadOutputDimensions,ck as applyReadOutputSessionReferences,lk as attachReadOutputSessionReceipt,pk as boundAgentEpisodeIdentity,rt as canonicalDocument,zM as claim,HM as claimNext,Su as classifyItemFormatVersion,KM as close,xM as comments,EM as context,VM as copy,GM as create,uf as createPmCliExpectedError,Zb as decodeReadOutputContinuationCursor,WM as deleteItem,MM as deps,Sk as detectAgentIdentity,Tk as detectHarnessIdentity,Ek as diagnoseAgentIdentity,FM as docs,bu as effectiveItemFormatVersion,eb as emptyImportedDocument,Qb as encodeReadOutputContinuationCursor,RP as evaluateSemanticAttributionCoverage,Rk as explainSourceTraceability,LM as files,$M as filesDiscover,JM as focus,IM as get,DM as graph,OP as groupHistoryByEpisode,dy as isAlreadyClaimedError,Ik as isItemAlreadyExistsError,Ti as isPmCliExpectedError,ik as isReadOutputBudgetExceeded,NM as learnings,AM as list,yk as listAgentProvenanceAdapters,TM as listAllComplete,RM as next,vk as normalizeAgentProvenanceAdapterValue,ku as normalizeItemFormatVersion,ze as normalizeItemId,ee as normalizeStatusInput,PM as notes,k as nowIso,sk as parseReadOutputSession,Ni as parseSourceLineRange,ri as readAuthorEnvironment,dk as readOutputSessionRemainingTokens,yc as recordClaimSemanticAttribution,ji as recordFocusSemanticAttribution,wc as recordReleaseSemanticAttribution,wk as registerAgentProvenanceAdapters,gk as registerHarnessSignalDescriptors,BM as release,qM as reopen,uk as resolveAgentSessionContextFromSignals,Ck as resolveAuthorIdentity,Uw as resolveHistoryEpisodeGroupIdentity,rk as resolveReadOutputDimensions,ak as resolveReadOutputEncoding,Us as resolveReadOutputSurface,Ok as resolveSemanticLineageIds,YM as restore,_b as runAction,fk as runWithAgentSessionContext,bk as runWithHarnessDetectionSignals,kk as runWithWorkspaceHarnessSignalDescriptors,CM as search,Pk as semanticAttributionAffinity,Ve as serializeItemDocument,IP as summarizeAgentModelProvenance,Ql as summarizeAgentProvenance,jM as update,Gs as validateReadOutputOptions,Ak as writeAuthorEnvironment};
20
+ `,{changedFields:["body"]}}});return{item:c.item,appended:s,changed_fields:c.changedFields}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8f7d8635-ea1c-5c87-9001-bfa1d1618478")}catch{}})();var HT=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function Eg(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function Xc(e,t){return Qc(e,t,{operation:"close"})}function Qc(e,t,n){let r=Eg(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",d.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function Zc(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],i=o.filter(m=>m.kind==="blocked_by"),a=e.blocked_reason!==void 0,s=[];if(r&&(delete e.blocked_by,s.push("blocked_by")),a&&(delete e.blocked_reason,s.push("blocked_reason")),t.orderingEdges==="remove"&&i.length>0){let m=new Set(i),p=o.filter(u=>!m.has(u));p.length>0?e.dependencies=p:delete e.dependencies,s.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:s,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...i.length>0?[`closed_removed_predecessors:${e.id}:${i.map(m=>m.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${i.length}`]:[]]};let c=[...new Set([...n?[n]:[],...i.map(m=>m.id)])];return c.length===0?{changedFields:s,warnings:[]}:{changedFields:s,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab15186d-b8bc-5740-bc16-d5af1eeeaa02")}catch{}})();var BT=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function VT(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new l(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,d.USAGE)}function Ag(e){let t=[];for(let n of BT){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function Tg(e,t,n={}){let r=Ag(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},i=r.map(s=>`--${s.key.replaceAll("_","-")}`),a=["--pm-path",t,"update",e.id,...r.flatMap((s,c)=>[i[c],o[s.key]?.trim()||"<value>"])];return{missing:i,suggested_retry:Te(a),suggested_retry_args:a}}async function WT(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let i=o.trim();if(i===n)return!0;if(r.has(i))return!1;r.add(i),o=(await e(i))?.duplicate_of}return!1}function YT(e){return typeof e!="string"||e.trim().length===0}async function JT(e,t,n,r){let o=n?.trim();if(!o)return;if(o===r)throw new l("An item cannot be closed as a duplicate of itself.",d.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let i=x(t,R()),a=new Map,s=async m=>{if(a.has(m))return a.get(m)??null;let p=await z(e,m,t.id_prefix,t.item_format,i.type_to_folder);if(!p)return a.set(m,null),null;let{document:u}=await ce(p,{schema:t.schema});return a.set(m,u.metadata),u.metadata},c=await s(o);if(!c)throw new l(`Duplicate target "${o}" was not found. Create or locate the canonical item first.`,d.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 ${r} "Duplicate of ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await WT(s,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${o}" points back to "${r}".`,d.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 c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new l(`Duplicate target "${o}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,d.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function XT(e,t,n){return e.filter(r=>r.parent===t&&!re(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function QT(e,t,n){let r=new Map(e.map(s=>[s.id.trim().toLowerCase(),s])),o=wf(e),i=t.trim().toLowerCase(),a=n.blocked_statuses;return e.filter(s=>a.has(s.status)).map(s=>({item:s,blockerIds:o.get(s.id.trim().toLowerCase())})).filter(({blockerIds:s})=>s.includes(i)).filter(({blockerIds:s})=>s.every(c=>{if(c===i)return!0;let m=r.get(c);return m!==void 0&&re(m.status,n)})).map(({item:s,blockerIds:c})=>({id:s.id,blocker_ids:c})).sort((s,c)=>s.id.localeCompare(c.id))}async function ZT(e,t,n,r,o,i){let a=QT(n,r,i),s=[];for(let c of a)try{let m=await le({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(p){let u=p.metadata.dependencies??[],f=u.filter(h=>{let g=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(g)});p.metadata.status=i.open_status,delete p.metadata.blocked_by,delete p.metadata.blocked_reason,p.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?p.metadata.dependencies=f:delete p.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==u.length&&_.push("dependencies"),{changedFields:_}}});s.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let p=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";s.push(`auto_unblock_failed:${c.id}:${p}`)}return s}function eC(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:i}of r){if(typeof o!="string")continue;let a=o.trim();a.length!==0&&(e[i]=a,n.push(i))}return n}function tC(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:i}of r)YT(e[o])&&(e[o]=i,n.push(o));return n}function nC(e,t,n,r){let o=[];if(t!=="off"){let i=Ag(e);if(i.length>0){let a=i.map(s=>s.label);if(t==="strict"){let s=i.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...s.flatMap(m=>[m,"<value>"])];throw new l(`Cannot close item ${e.id}: missing ${a.join(", ")}. Populate fields or use --validate-close warn.`,d.USAGE,{code:"close_validation_missing_fields",recovery:{missing:s,suggested_retry:Te(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}o.push(`close_validation_missing_fields:${e.id}:${a.join(",")}`)}if(n.length>0){if(t==="strict")throw new l(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,d.USAGE);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function rC(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function oC(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function iC(e,t){if(re(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,d.CONFLICT,{recovery:Tg(e,t.pmRoot,t.options)});let n=eC(e,t.options),r=tC(e,t.duplicateOf),o=nC(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let i=t.options.completedAt!==void 0||e.completed_at===void 0;i&&(e.completed_at=t.completedAt);let a=["status","closed_at",...i?["completed_at"]:[],...rC(e,t.closeReason),...n];if(gf(e)&&(e.plan_mode="completed",a.push("plan_mode")),t.duplicateOf!==void 0){a.push("duplicate_of");for(let c of r)a.includes(c)||a.push(c)}a.push(...oC(e));let s=Zc(e,t.lifecyclePolicy);return a.push(...s.changedFields),o.push(...s.warnings),{changedFields:a,...o.length>0?{warnings:o}:{}}}async function Cg(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let i=await A(o),a=F(i.schema),s=C(n.author,i.author_default),c=x(i,R()).type_to_folder,m=await z(o,e,i.id_prefix,i.item_format,c);if(!m)throw await gt(o,e,i.id_prefix,c);let p=await JT(o,i,n.duplicateOf,m.id),u={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??i.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Xc({explicit:t,duplicateOf:p,resolution:n.resolution,message:n.message},u.requireCloseReason).closeReason,_=VT(n.validateClose)??i.governance.close_validation_default,h=await _e(o,i.item_format,c,void 0,i.schema),g=XT(h,m.id,a),y=k(),w=n.completedAt===void 0?y:se(n.completedAt,new Date(y),"completed-at"),b=await le({pmRoot:o,settings:i,id:m.id,op:"close",author:s,message:n.message,force:n.force,mutate(T){return iC(T.metadata,{pmRoot:o,statusRegistry:a,force:n.force,options:n,duplicateOf:p,validateCloseMode:_,activeChildIds:g,closeReason:f,closedAt:y,completedAt:w,lifecyclePolicy:u})}}),S=_==="warn"?Tg(b.item,o):void 0;return{item:b.item,changed_fields:b.changedFields,...S?{recovery:S}:{},warnings:[...b.warnings,...await ZT(o,i,h,m.id,s,a)]}}function kt(e,t,n,r){return Cg(e,t,n,r)}import aC from"fast-json-patch";import el from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebfa0c5e-461b-5078-8272-69086e84b4dc")}catch{}})();async function Ig(e,t,n){let r=await pf(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:Rg(n),recovered:!0}}function sC(e,t){return lf(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Rg(e){let t=sc(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:it(at(t))}async function cC(e,t,n,r){let o=await en(e,t,n,r),i=o.located?await rf({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function lC(e,t){let n=hr(e),r=hr(t),o=aC.compare(n,r),i=new Set;for(let a of o){if(a.path==="/body"||a.path.startsWith("/body/")){i.add("body");continue}let s=a.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(s.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((a,s)=>a.localeCompare(s))}async function dC(e){let t=await R_({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>Ig(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function mC(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Rg(t),originalRaw:null}}function pC(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new l(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,d.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function uC(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await te(e.existingItemPath,e.resolvedOriginalRaw),await el.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await te(e.existingItemPath,e.resolvedOriginalRaw);return}await el.rm(e.restoredItemPath,{force:!0})}async function fC(e){return[...await Y({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await Y({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function on(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let i=await A(o),a=x(i,R()),s=await cC(o,e,i,a.type_to_folder),c=s.id,{raw:m,entries:p}=await Mu(s.historyPath,c);if(p.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let u=sC(t,p),f=df(sc(p,u.historyIndex),u),_=Bu(f,{schema:i.schema});if(_.metadata.id!==c)throw new l(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let h=(s.located?await Ig(s.located,i,p):null)?.raw??null,g=C(n.author,i.author_default),y=await Ie(o,c,i.locks.ttl_seconds,g,!!n.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let{loadedItemUnderLock:w,existingItemPath:b}=await dC({pmRoot:o,subject:s,settings:i,typeRegistry:a,historyRawBeforeLock:m,currentItemRawBeforeLock:h,history:p}),S="toon",T=mC(w,p),$=pC({document:T.document,author:g,force:n.force,enforcement:i.governance.ownership_enforcement,resolvedId:c}),P=lC(T.document,_),L=await wr({pmRoot:o,settings:i,operation:"restore",author:g,before:T.document,after:_});await Yo({pm_root:o,operation:"restore",before:T.document,after:_,changed_fields:P,sdk:ki({pmRoot:o,settings:i,typeToFolder:a.type_to_folder})});let q=We(_,{format:S,schema:i.schema}),H=pt(o,_.metadata.type,c,S,a.type_to_folder),J=await Mt(o,g),ie=[];try{await te(H,q),b&&H!==b&&await el.rm(b);let K=Fe({nowIso:k(),author:g,op:"restore",before:T.document,after:_,message:n.message,context:L.decisions.length===0?void 0:{workflow_policies:L.decisions}});try{await Nt(s.historyPath,K)}catch(ae){throw await uC({existingItemPath:b,resolvedOriginalRaw:T.originalRaw,restoredItemPath:H}),ae}ie=await Dt({pmRoot:o,preferredFormat:i.item_format,typeToFolder:a.type_to_folder,schema:i.schema,itemPath:H,previousItemPath:b??void 0,document:_})}finally{await J()}let me=await fC({restoredItemPath:H,historyPath:s.historyPath,before:T.document,after:_});Cn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:T.document.metadata.status,status:_.metadata.status,previous:Qt(T.document.metadata,P),current:Qt(_.metadata,P),changed_fields:P});let $e=p[u.historyIndex],Be=Fn(p,!0);return{item:_.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:Be===null?null:Be+u.historyIndex+1,entry_ts:$e.ts,entry_op:$e.op},changed_fields:P,warnings:[...L.warnings,...w?.recovered?["restore_unreadable_item_recovered"]:[],...s.historyPolicyWarnings,...$,...ie,...me]}}finally{await y()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6edfa77d-9b76-540b-a365-a3fef0450c53")}catch{}})();var xg=1,tl="close-many",_C=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function hC(e,t){return Ir(e,t,{includePagination:!1})}function gC(e,t){return Ir(e,t)}function yC(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)}function wC(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function vC(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new l("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",d.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function bC(e,t){let n=F(t.schema),r=x(t,R()),o=await _e(e,t.item_format,r.type_to_folder,void 0,t.schema),i=new Map,a=new Map;for(let s of o){if(typeof s.parent!="string"||s.parent.length===0||(a.set(s.id,s.parent),re(s.status,n)))continue;let c=i.get(s.parent);c?c.push(s.id):i.set(s.parent,[s.id])}for(let s of i.values())s.sort((c,m)=>c.localeCompare(m));return{childrenByParent:i,parentByChild:a}}function Og(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,i=t.get(e),a=[],s=new Set,c=!1;for(;i!==void 0&&!s.has(i);){let m=n?.get(i);if(m!==void 0){o+=m+1;break}s.add(i),a.push(i),o+=1,i=t.get(i)}if(i!==void 0&&s.has(i)&&(c=!0),!c){n?.set(e,o);for(let[m,p]of a.entries())n?.set(p,o-m-1)}return o}async function kC(e){let t=await li(e.pmRoot,tl,e.rollbackId,xg),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await di(t.items,(o,i)=>on(o,i,{author:e.options.author,message:n,force:!0},e.global));return{...Zt({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function SC(e,t,n,r,o){return e.map(i=>{let a=(t.get(i.id)??[]).filter(c=>!n.has(c)),s=!Pg(i,r,o);return{id:i.id,title:typeof i.title=="string"?i.title:"",status:i.status,action:s?"skip":"close",...s?{skip_reason:"already_terminal"}:{},...a.length>0?{active_child_ids:a}:{}}})}async function EC(e){let t=await ci(e.pmRoot,tl,e.checkpointId,{schema_version:xg,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function AC(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await kt(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){t.push({id:r.id,status:"failed",error:En(o)})}}return{rows:t,closedIds:n}}function TC(e){return typeof e.rollback=="string"?e.rollback:void 0}function CC(e,t){if(t.trim().length===0)throw new l("--rollback requires a checkpoint id",d.USAGE);if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(gC(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function IC(e){if(!hC(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${_C}). Refusing to match every item.`,d.USAGE)}function RC(e,t){let n=new Map;return[...e].sort((r,o)=>{let i=Og(o.id,t,n)-Og(r.id,t,n);return i!==0?i:r.id.localeCompare(o.id)})}function Pg(e,t,n){return n||!re(e.status,t)}function OC(e,t,n){return new Set(e.filter(r=>Pg(r,t,n)).map(r=>r.id))}async function xC(e){IC(e.options);let t=F(e.settings.schema),n=vC(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await yt(e.options.status,wC(e.options.list),e.global),{childrenByParent:i,parentByChild:a}=await bC(e.pmRoot,e.settings),s=RC(o.items,a),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],m=c.length===0?[]:(await yt(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,p=new Set(m.map(f=>f.id)),u=OC(s,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:s,unmatchedIds:c.length===0?void 0:c.filter(f=>!p.has(f)),planRows:SC(s,i,u,t,r)}}function PC(e){return{outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function NC(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return EC({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function Ng(e,t){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=e.dryRun===!0,i=TC(e);if(yC(e.list),i!==void 0)return CC(e,i),kC({pmRoot:n,rollbackId:i,options:e,global:t});let a=await xC({pmRoot:n,settings:r,options:e,global:t});if(o)return PC(a);let s=new Set(a.planRows.filter(w=>w.action==="close").map(w=>w.id)),c=k(),m=si(tl,c),p=await NC({context:a,options:e,closableIds:s,checkpointId:m,nowValue:c}),u={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:a.validateCloseMode,force:a.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await AC({matched:a.matched,closableIds:s,reason:a.reason,closeOptions:u,global:t}),h=f.filter(w=>w.status==="closed").length,g=f.filter(w=>w.status==="skipped").length,y=f.filter(w=>w.status==="failed").length;return{...Zt({applied:h,skipped:g,failed:y,unmatched:a.unmatchedIds?.length??0}),mode:"apply",matched_count:a.matched.length,dry_run:!1,...a.reason!==void 0?{reason:a.reason}:{},filters:a.listed.filters,...a.validateCloseMode?{validate_close:a.validateCloseMode}:{},...p?{checkpoint:p}:{},closed_count:h,skipped_count:g,failed_count:y,rows:f,ids:_,...a.unmatchedIds!==void 0?{unmatched_ids:a.unmatchedIds,unmatched_count:a.unmatchedIds.length}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="902e9f78-a2c1-59bb-aaa2-763576d5c68b")}catch{}})();function LC(e,t){return[...new Set([...lo.filter(n=>e[n]!==void 0),...Object.keys(e).filter(n=>e[n]!==void 0),...t.length>0?["body"]:[]])].sort((n,r)=>n.localeCompare(r))}function $C(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function nl(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),i=x(o,R()),a=await z(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await gt(r,e,o.id_prefix,i.type_to_folder);let s=await ce(a,{schema:o.schema}),c=s.document.metadata,m=k(),p=C(t.author,o.author_default),u=await gr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:i.type_to_folder,probeExisting:!1}),f=F(o.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let h={...c,id:u,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let g=It(R()),y=it({metadata:h,body:s.document.body},{schema:o.schema,extensionFieldNames:g}),w=await jn({title:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[a.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),b=LC(y.metadata,y.body),S=pt(r,y.metadata.type,u,o.item_format,i.type_to_folder),T=rt(r,u),$=await Ie(r,u,o.locks.ttl_seconds,p,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),P={metadata:{},body:""},L,q;try{let H=await Mt(r,p,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await jn({title:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[a.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let J=await z(r,u,o.id_prefix,o.item_format,i.type_to_folder);if(J)throw new l(`Cannot copy to ${u}: an item with that id already exists at ${J.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${u} already exists at ${J.itemPath}.`,recovery:{suggested_retry:`pm copy ${a.id}`}});await te(S,We(y,{format:o.item_format,schema:o.schema,extensionFieldNames:g}));try{let ie=Fe({nowIso:m,author:p,op:"create",before:P,after:y,message:$C(a.id,t.message)});await Nt(T,ie)}catch(ie){throw await Sn(S),ie}q=await Dt({pmRoot:r,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:S,document:y})}finally{await H()}L=[...await Y({path:S,scope:"project",op:"create",item_id:y.metadata.id,item_type:y.metadata.type,before:P,after:y,changed_fields:b}),...await Y({path:T,scope:"project",op:"create:history",item_id:y.metadata.id,item_type:y.metadata.type,before:P,after:y,changed_fields:b})],Cn({id:y.metadata.id,op:"create",item_type:y.metadata.type,status:y.metadata.status,current:Qt(y.metadata,b),changed_fields:b})}finally{await $()}return{source_id:a.id,item:structuredClone(y.metadata),changed_fields:b,warnings:[...Ni(w),...q,...L],...w===void 0?{}:{similarity_advisory:w}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e808776-dd0e-507f-9214-e3f5fa846874")}catch{}})();var FC="hierarchy-integrity";async function ea(e){let t=e.required?await Ie(e.pmRoot,FC,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01a312de-88fc-514f-b37b-2e717222a8ed")}catch{}})();function ta(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function na(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function ra(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(co.includes(t))return t;let n=fe(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new l("Confidence must be an integer 0..100 or one of low|med|medium|high",d.USAGE);return n}function oa(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new l("Regression must be one of true|false|1|0",d.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ccfe6c7-3911-5623-aa29-5eff0293f816")}catch{}})();var Lg=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2167160d-d7ba-5096-b0b5-7e9e795af0a6")}catch{}})();function ia(e){let t=Lg.find(([r])=>r===e)?.[1]??e.replaceAll(/_([a-z])/gu,(r,o)=>o.toUpperCase()),n=[["update",fu],["create",pu]].flatMap(([r,o])=>o.flatMap(i=>{if(i.target!==t)return[];let a=i.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:r,flag:a}]}));return{recovery:{provided_fields:[e],...n.length>0?{suggested_flags:[...new Set(n.map(r=>r.flag))]}:{}},nextSteps:n.length>0?n.map(({command:r,flag:o})=>`Use the declared core mutation: pm ${r}${r==="update"?" <id>":""} ${o} <value>; inspect its help for other required options.`):[`No dedicated create/update CLI mutation flag is declared for "${e}". Use its owning lifecycle, evidence, or importer API; --field cannot mutate core metadata.`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c22dc1f8-285a-5858-9087-17a8deed6db8")}catch{}})();var MC=new Set(["none","null"]);function aa(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function Qe(e){return e===void 0?!1:MC.has(e.trim().toLowerCase())}function sa(e,t,n){if(!Qe(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Pe(e,t,n){if(!e||e.length===0||!e.some(o=>Qe(o)))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function ca(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(i=>typeof i=="string"))throw new l(`${n.valueFlag} entries must be strings.`,d.USAGE);let o=r;if(o.some(i=>Qe(i))){if(o.filter(i=>!Qe(i)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daa816a5-05d4-5e0a-90aa-9d96afdb2117")}catch{}})();var DC=new Set(["event","meeting","reminder","milestone","decision","adr"]);function $g(e,t,n,r){if(DC.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=Bo("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm claim ${e} --start`,to_status:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1ce8c06c-cdc7-57bb-b4c3-477b2e07d71c")}catch{}})();var cn=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",Er,xf,"FORCE_COLOR"]),ma=/^[A-Za-z_][A-Za-z0-9_]*$/,sn=["schema","tracker","auto","none"],Fg=["source","isolated","snapshot"];function Mr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,d.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1);if(!ma.test(a))throw new l(`${t} env_set key "${a}" is invalid`,d.USAGE);if(cn.has(a.toUpperCase()))throw new l(`${t} env_set key "${a}" is reserved for sandbox safety`,d.USAGE);r[a]=s}return Object.keys(r).length>0?r:void 0}function Dr(e,t){if(!e)return;let n=Dn(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,d.USAGE);for(let r of n){if(!ma.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(cn.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function pa(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,d.USAGE)}function ua(e,t){if(!e)return;let n=e.trim().toLowerCase();if(sn.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${sn.join(", ")}`,d.USAGE)}function ln(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Fg.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${Fg.join(", ")}`,d.USAGE)}function dn(e){if(!e)return;let t=Dn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Bn(e,t,n){let r=dn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(i){throw new l(`${t} ${n} includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`,d.USAGE)}return r}}function fa(e,t){if(!e)return;let n=fe(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,d.USAGE);return n}function _a(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0||s.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[a]=s}return Object.keys(r).length>0?r:void 0}function ha(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0||s.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,d.USAGE);let c=Number(s);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${a}" must be numeric`,d.USAGE);r[a]=c}return Object.keys(r).length>0?r:void 0}var UC=new Set(wt);function ga(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function GC(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let a=o.toLowerCase();if(!UC.has(a)){r.push(o);continue}if(Object.hasOwn(n,a))throw t(`provides key "${o}" more than once after case normalization`);n[a]=i}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${wt.join(", ")}.`);return n}function an(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function la(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(a=>typeof a!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=o.filter(a=>a.length>0);return i.length>0?i:void 0}function Mg(e,t,n){let r=la(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(i){throw n(`field "${t}" includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`)}return r}}function da(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function jC(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:da(n,"timeout_seconds",t),i=r===void 0?void 0:da(r,"timeout",t);if(o!==void 0&&i!==void 0&&o!==i)throw t("timeout and timeout_seconds must match when both are provided");let a=o??i;if(!Number.isInteger(a)||a<=0)throw t("timeout_seconds must be a positive integer");return a}function qC(e,t){let n=an(e,"scope",t);if(n===void 0)return"project";if(!dt.includes(n))throw t(`field "scope" must be one of: ${dt.join(", ")}`);return n}function KC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!ga(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(typeof i!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!ma.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(cn.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=i}return Object.keys(r).length>0?r:void 0}function zC(e,t){let n=la(e,"env_clear",t);if(n){for(let r of n){if(!ma.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(cn.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function HC(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function BC(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=da(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function VC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!ga(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof i!="string"&&typeof i!="number"&&typeof i!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(i)}return Object.keys(r).length>0?r:void 0}function WC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!ga(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=da(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function YC(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!ga(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${wt.join(", ")}.`);let o=GC(e,r),i=an(o,"command",r),a=an(o,"cmd",r);if(i!==void 0&&a!==void 0&&i!==a)throw r("command and cmd must match when both are provided");let s=i??a;if(s===void 0||s.trim().length===0)throw r('requires a non-empty "command" string');let c=an(o,"path",r),m=an(o,"pm_context_mode",r);if(m!==void 0&&!sn.includes(m))throw r(`field "pm_context_mode" must be one of: ${sn.join(", ")}`);let p=ln(an(o,"workspace_context_mode",r),`${n} ${t}`),u=an(o,"note",r);return{command:s,path:c!==void 0&&c.length>0?c:void 0,scope:qC(o,r),timeout_seconds:jC(o,r),pm_context_mode:m,workspace_context_mode:p,env_set:KC(o,r),env_clear:zC(o,r),shared_host_safe:HC(o,"shared_host_safe",r),assert_stdout_contains:la(o,"assert_stdout_contains",r),assert_stdout_regex:Mg(o,"assert_stdout_regex",r),assert_stderr_contains:la(o,"assert_stderr_contains",r),assert_stderr_regex:Mg(o,"assert_stderr_regex",r),assert_stdout_min_lines:BC(o,r),assert_json_field_equals:VC(o,r),assert_json_field_gte:WC(o,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function ya(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,d.USAGE);let r;try{r=JSON.parse(n)}catch(i){throw new l(`${t} value is not valid JSON: ${i instanceof Error?i.message:String(i)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return o.map((i,a)=>YC(i,o.length>1?`entry ${a+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1ffee31a-c272-5494-a04a-01a17b78dd2d")}catch{}})();var rl=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],ol=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],Dg=[...rl,...ol],wa=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function va(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let o=r.trim().toLowerCase();if(!o)throw new l("--unset values must not be empty",d.USAGE);if(Qe(o))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let i=e.resolveDefinition(o);if(!i)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(i.metadataKey),n.add(i.optionKey)}return{metadataKeys:t,optionKeys:n}}function ba(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let i of o){if(i.allow_unset===!1)continue;let a=new Set;if(typeof i.key=="string"&&i.key.length>0&&a.add(i.key.toLowerCase()),typeof i.metadata_key=="string"&&i.metadata_key.length>0&&a.add(i.metadata_key.toLowerCase()),typeof i.cli_flag=="string"&&i.cli_flag.length>0&&(a.add(i.cli_flag.replaceAll("-","_").toLowerCase()),a.add(i.cli_flag.toLowerCase())),Array.isArray(i.cli_aliases))for(let s of i.cli_aliases)typeof s!="string"||s.length===0||(a.add(s.replaceAll("-","_").toLowerCase()),a.add(s.toLowerCase()));if(a.has(r))return{optionKey:i.key,metadataKey:i.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48975dc8-636f-51a1-858a-f97c7a037688")}catch{}})();function Gg(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,d.USAGE)}function il(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Ze(e,t,n,r=n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE,{field:r,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var jg=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function JC(e,t){return t==="defined"?e!==void 0:!!e}function Ug(e,t,n){if(!JC(e,n))return;let r=fe(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function XC(e,t,n){let r=e?se(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new l("--event recur_until must be at or after start",d.USAGE);return r}function QC(e){return Array.from(new Set(il(e).map(t=>Ze(t.toLowerCase(),em,"event weekday")))).sort((t,n)=>gs(t)-gs(n))}function ZC(e){return Array.from(new Set(il(e).map(t=>{let n=fe(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new l("--event recur_by_month_day values must be integers 1..31",d.USAGE);return n}))).sort((t,n)=>t-n)}function e0(e,t){return Array.from(new Set(il(e).map(n=>se(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function qg(e,t,n,r){let o=e.recur_freq?.trim(),i=e.recur_interval?.trim(),a=e.recur_count?.trim(),s=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),p=e.recur_exdates?.trim();if(![o,i,a,s,c,m,p].some(b=>b!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let u=Ze(o.toLowerCase(),Zd,"event recurrence frequency"),f=Ug(i,"recur_interval",r),_=Ug(a,"recur_count",r),h=XC(s,t,n),g=QC(c),y=ZC(m),w=e0(p,n);return{freq:u,interval:f,count:_,until:h,by_weekday:g.length>0?g:void 0,by_month_day:y.length>0?y:void 0,exdates:w.length>0?w:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="414326ff-8d4d-577d-b724-ab32b3f311ac")}catch{}})();function Ur(e,t=Xe()){let n=t.resolve(e);if(n)return n.kind;let r=new Set(nr),o=[...nr,...t.list().filter(({kind:i})=>!r.has(i)).flatMap(({kind:i,aliases:a})=>[i,...a])];throw new l(`Invalid dependency kind value "${e}". Allowed: ${o.join(", ")}`,d.USAGE,{field:"kind",value:e,recovery:{allowed_values:o},required:`dependency kind must be one of: ${o.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function Gr(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function jr(e,t,n=Xe()){for(let r of t??[])try{om(e,r.id,r.kind,n)}catch(o){throw new l(En(o),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Kg(e,t){return(await ce(e,{schema:t})).document.metadata.created_at}async function t0(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await z(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Kg(n,t.schema)}function n0(e){let t=e.registry.require(e.dependency.kind);return new l(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,d.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function r0(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:i})=>i===null?[]:[[o,i]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await Kg(n.get(o),e.context.schema)])));for(let o of e.holders){let i=await t0(o,e.context);if(i!==void 0)for(let a of t){let s=r.get(a.id),c=Date.parse(i),m=Date.parse(s);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw n0({holder:o,dependency:a,sourceCreatedAt:i,targetCreatedAt:s,registry:e.registry})}}}async function mn(e){let t=e.registry??Xe(),n=(e.dependencies??[]).filter(a=>!su(a.source_kind)),r=[...new Set(n.map(a=>a.id))],o=await Promise.all(r.map(async a=>({target:a,located:await z(e.pmRoot,a,e.idPrefix,e.itemFormat,e.typeToFolder)}))),i=o.filter(({located:a})=>a===null).map(({target:a})=>a).sort((a,s)=>a<s?-1:1);if(i.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${i.length===1?"":"s"} not found: ${i.join(", ")}`,d.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:i,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${i.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:i,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${i[0]}" --limit 10`}});return await r0({dependencies:n,missingTargets:i,resolutions:o,holders:e.holders??[],registry:t,context:e}),i.map(a=>`dependency_target_unresolved:${a}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var o0={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function i0(e){return o0[e]}function al(e){return i0(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3950ef46-cc2b-5b8e-97d6-34c739bd816e")}catch{}})();var zg="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",a0="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",s0=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,c0=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Bg=1e3,sl=60*Bg,l0=60*sl;function Hg(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new l(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,d.USAGE);return n.toISOString()}function d0(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new l(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,d.USAGE);let o=r.replace(/^([+-]?\d+)mo$/i,"$1m"),i=s0.exec(r);if(i){let c=i[1]==="-"?-1:1,m=Number.parseInt(i[2],10)*c;return Hg(n.getTime()+m*sl,r)}let a=c0.exec(r);if(a){let[,c,m,p,u]=a;if(m||p||u){let f=c==="-"?-1:1,_=Number.parseInt(m??"0",10),h=Number.parseInt(p??"0",10),g=Number.parseInt(u??"0",10),y=_*l0+h*sl+g*Bg;return Hg(n.getTime()+f*y,r)}}let s=o.startsWith("+")||o.startsWith("-")?o:`+${o}`;return se(s,n,"event.duration")}function Vg(e,t,n,r){if(t&&n)throw new l(a0,d.USAGE);if(n){let i=d0(e,n);if(i<e)throw new l(zg,d.USAGE);return i===e?void 0:i}if(!t)return;let o=se(t,r,"event.end");if(o<e)throw new l(zg,d.USAGE);if(o!==e)return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8288d6e7-a027-5bfa-9b4a-3c8b581f31ce")}catch{}})();var m0=["at","date","text","title"],p0=["start","date","end","duration","title","description","location","timezone","all_day",...jg],u0=["key","value"];function Wg(e,t){return t==="trimmed"?e?.trim():e}function f0(e,t){return t==="defined"?e!==void 0:!!e}function ka(e,t,n){return e.map(r=>{let o=pe(r,"--reminder");Je(o,"--reminder",m0);let i=Wg(o.at??o.date,n.valueMode),a=Wg(o.text??o.title,n.valueMode);if(!i||!a)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let s=a.trim();if(!s)throw new l("--reminder text must not be empty",d.USAGE);return{at:se(i,t,"reminder.at"),text:s}})}function Sa(e,t,n){return e.map(r=>{let o=pe(r,"--event");Je(o,"--event",p0);let i=(o.start??o.date)?.trim();if(!i)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let a=se(i,t,"event.start"),s=o.end?.trim(),c=o.duration?.trim(),m=Vg(a,s,c,t),p=o.title,u=o.description,f=o.location,_=o.timezone,h=p?.trim(),g=u?.trim(),y=f?.trim(),w=_?.trim(),b=[["title",p,h],["description",u,g],["location",f,y],["timezone",_,w]];for(let[P,L,q]of b)if(L!==void 0&&!q)throw new l(`--event ${P} must not be empty`,d.USAGE);let S=o.all_day?.trim(),T=qg(o,a,t,n.recurrenceEmptyNumericGuard),$=f0(S,n.allDayEmptyGuard)?Gg(S,"--event all_day"):void 0;return{start_at:a,end_at:m,title:h,description:g,location:y,all_day:$,timezone:w,recurrence:T}})}function Ea(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new l("--type-option values must not be empty",d.USAGE);let o,i;if(r.includes(",")||r.includes(`
21
+ `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=pe(r,"--type-option");Je(a,"--type-option",u0),o=a.key?.trim(),i=a.value?.trim()}else{let a=r.indexOf("="),s=r.indexOf(":"),c=a;if(a<=0&&s>0&&(c=s),c<=0||c===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);o=r.slice(0,c).trim(),i=r.slice(c+1).trim()}if(!o||!i)throw new l("--type-option requires key and value",d.USAGE);t[o]=i}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2eb7f7bc-c23a-5ea2-a050-c81c2fa88456")}catch{}})();var _0=["strict","progressive"],h0=["lightweight"],Qg=new Set(["Reminder","Meeting","Event"]),g0=new Set(["author","created_at","text"]),ll=[...Dg,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...wa],y0=(()=>{let e=new Map;for(let t of ll)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Aa=new Map(ll.map(e=>[e.optionKey,e.canonical])),w0=ll.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function v0(e,t){let n=ee(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function b0(e,t){let n=e.default_status;if(n!==void 0){let r=ee(n,t);if(r)return r}return t.open_status}function cl(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}var k0=aa();function Zg(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i};Qe(t.template)&&(t.template=void 0);let r=new Set([...Aa.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!Qe(i))continue;let a=o==="rank"?"order":Aa.get(o)??o;n(a),t[o]=void 0}return Oe(e,ca(t,k0))}function ve(e){if(e!==void 0)return e}function S0(e,t){return va({raw:e,supportedFields:w0,resolveDefinition:n=>y0.get(n)??ba(n,"create",t)})}var Yg=["id","kind","type","author","created_at","source_kind"],Ta=["path","scope","note"];function E0(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Pe(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let i=o.trim(),a=Ca(i,Yg);Gr(i,a);let s=a?pe(o,"--dep"):{id:i,kind:"related"};a&&Je(s,"--dep",Yg);let c=ve(s.id),m=A0(ve(s.kind??s.type));if(!c||!m)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",d.USAGE);if(c.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=br(ve(s.source_kind)),u=ve(s.author);return{id:kr(c,n,p),kind:Ur(m),created_at:cl(s.created_at,t),author:u??r,source_kind:p??"cli:create:dep",author_source:u?"asserted":"detected"}}),explicitEmpty:!1})}function A0(e){return typeof e=="string"?Xe().resolve(e)?.kind??e.trim():e}function Ca(e,t){return ef(e,t)?!0:ui(e)}function un(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Pe(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(o=>{let i=o.trim(),a=()=>{if(i.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:i}},s;try{s=pe(o,e)}catch(m){if(e==="--comment"||e==="--note"||e==="--learning")return a();throw m}if(Object.keys(s).filter(m=>!g0.has(m)).length>0)return{created_at:cl(s.created_at,n),author:ve(s.author)??r,text:i};let c=s.text??"";if(c==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:cl(s.created_at,n),author:ve(s.author)??r,text:c}}),explicitEmpty:!1})}function dl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Pe(e,"--file","Use --clear-files to clear linked files."),{values:e.map(t=>{let n=t.trim(),r=Ca(n,Ta);oc(n,"--file","file path",r);let o=r?pe(t,"--file"):{path:n};if(r&&Je(o,"--file",Ta),!o.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:o.path,scope:Ze(o.scope??"project",dt,"file scope"),note:ve(o.note)}}),explicitEmpty:!1})}function ml(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Pe(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(t=>{let n=t.trim(),r=Ca(n,wt);oc(n,"--test","test command",r);let o=r?Gi(pe(t,"--test"),"--test"):{command:n},i=ve(o.command),a=ve(o.path);if(!i)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let s=ve(o.timeout_seconds),c=ve(o.timeout);if(s&&c&&s!==c)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let m=s??c;return{command:i,path:a,scope:Ze(o.scope??"project",dt,"test scope"),timeout_seconds:m?fe(m,"timeout_seconds"):void 0,pm_context_mode:ua(o.pm_context_mode,"--test"),workspace_context_mode:ln(o.workspace_context_mode,"--test"),env_set:Mr(o.env_set,"--test"),env_clear:Dr(o.env_clear,"--test"),shared_host_safe:pa(o.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:dn(o.assert_stdout_contains),assert_stdout_regex:Bn(o.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:dn(o.assert_stderr_contains),assert_stderr_regex:Bn(o.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:fa(o.assert_stdout_min_lines,"--test"),assert_json_field_equals:_a(o.assert_json_field_equals,"--test"),assert_json_field_gte:ha(o.assert_json_field_gte,"--test"),note:ve(o.note)}}),explicitEmpty:!1})}function pl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Pe(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(t=>{let n=t.trim(),r=Ca(n,Ta),o=r?pe(t,"--doc"):{path:n};if(r&&Je(o,"--doc",Ta),!o.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:o.path,scope:Ze(o.scope??"project",dt,"doc scope"),note:ve(o.note)}}),explicitEmpty:!1})}function T0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Pe(e,"--reminder","Use --clear-reminders to clear reminders."),{values:ka(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function C0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Pe(e,"--event","Use --clear-events to clear linked events."),{values:Sa(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function I0(e,t,n,r=[]){let o=[...lo.filter(i=>e[i]!==void 0),...r.filter(i=>e[i]!==void 0),...t.length>0?["body"]:[],...n.map(i=>`unset:${i}`)];return Array.from(new Set(o))}function R0(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Jg(e,t,n){let r=rr("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function O0(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function ey(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function x0(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Jg(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Jg(r,e.name,"required_create_repeatables"));return n}function P0(e,t,n,r){for(let o of e)if(!(!ey(t,o)&&!n.has(o)))throw new l(`Option ${Ce("create",o)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function N0(e,t,n){if(t!=="strict")return;let r=e.filter(i=>n.has(i)&&!al(i));if(r.length===0)return;let o=[...new Set(r.map(i=>Ce("create",i)))].sort((i,a)=>i.localeCompare(a));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function L0(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Pe(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Ea(e),explicitEmpty:!1})}async function $0(e){return await fi(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function F0(e){return ht(e)?await $0(e):e}function M0(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${_0.join(", ")}`,d.USAGE)}function D0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new l("--schedule-preset must not be empty",d.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new l(`Invalid --schedule-preset value "${e}". Allowed: ${h0.join(", ")}`,d.USAGE)}function U0(e,t,n){let r=M0(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",d.USAGE);return"progressive"}function G0(e,t,n,r,o){let i=e.name,a=O0(t),s=x0(e,n),c=An(e,"create",s);if(c.errors.length>0)throw new l(c.errors.join("; "),d.CONFLICT);P0(c.disabled,a,r,i),N0(c.required,n,r);let m=u=>u==="author"&&o!=="unknown"||u==="status"&&e.default_status!==void 0||r.has(u)&&al(u)?!0:ey(a,u),p=c.required.filter(u=>!m(u));return[...new Set(p.map(u=>Ce("create",u)))].sort((u,f)=>u.localeCompare(f))}var ty=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function j0(e,t){let n=[];for(let r of e){let o=r.match(ty);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function q0(e,t){return e.filter(n=>{let r=n.match(ty);return!r||r[2]!==t})}function K0(e,t,n,r){let o=q0(e,t);if(o.length===0)return;let i=ny(n,[],[],r.open_status);throw new l(o.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[i],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function z0(e,t){let n=e.options.find(r=>r.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function H0(e,t,n){let r=e.split("/")[0];switch(r){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[r,'"<value>"']}}function ny(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],i=["--status","--priority","--message"],a=[...new Set([...i,...t])],s=new Set(["--title","--description","--type"]);for(let c of a){if(s.has(c))continue;let m=oy[c];o.push(...m?[m]:H0(c,e.name,r)),s.add(c)}for(let c of n){let m=z0(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function ul(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new l("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",d.USAGE):new l('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',d.USAGE):new l(`Missing required option ${t}`,d.USAGE);return n}function B0(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=Array.isArray(o)?[...o]:o;for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=Array.isArray(o)?[...o]:o);return n}function V0(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function W0(){let e=R();return e?e.commands.some(t=>t.action==="templates-show"||V0(t.command)==="templates show"):!1}function Y0(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new l(`Templates package returned invalid payload for template "${t}". Expected an options object.`,d.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Templates package returned invalid options for template "${t}".`,d.GENERIC_FAILURE);let r={};for(let[o,i]of Object.entries(n)){if(typeof i=="string"||typeof i=="number"||typeof i=="boolean"){r[o]=i;continue}if(Array.isArray(i)&&i.every(a=>typeof a=="string")){r[o]=[...i];continue}throw new l(`Templates package returned unsupported option value for "${o}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function J0(e,t,n){if(!W0())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await Jo({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let o=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${o}`,d.USAGE)}return Y0(r.result,e)}function V(e,t,n){return e.has(t)||n===void 0?void 0:ve(n)}function pn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var X0=new Set(["milestone","meeting","reminder","event"]);function ry(e,t,n,r){let o=t!==void 0,i=n!==void 0&&n.length>0,a=r!==void 0&&r.length>0;return X0.has(e.toLowerCase())&&!o&&!i&&!a}function Q0(e,t,n,r,o){let i=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&i.push(`event_without_schedule:${t}:no_time_set`),ry(e,n,r,o)&&i.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),i}async function Z0(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await ri(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function eI(e,t,n,r,o,i){let a=Ai(yi(o),t.id_prefix);if(Zo(a))return{parent:a,warnings:[]};if(vi(r,a,t.id_prefix),await z(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let s=ze(a,t.id_prefix);return{parent:a,warnings:wi(s,i).warnings}}async function tI(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await eI(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function nI(e){if(e.explicitId===void 0)return gr(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||af(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=ze(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",d.USAGE);return n}function Xg(e,t,n,r,o){let i=V(e,t,n);if(i===void 0)return{value:void 0,warnings:[]};let a=bi(r,i,o);return{value:a.value,warnings:a.warnings}}async function rI(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:i,status:a,statusExplicit:s,nowValue:c,author:m}=e,p=e.dependencyValues;if(i===void 0)return{dependencyValues:p,status:a};let u=ze(i,n.id_prefix),f=await z(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:p,status:a};if((p??[]).some(h=>h.id===f.id&&h.kind==="blocked_by")||(p=[...p??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),s)return{dependencyValues:p,status:a};let _=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((h,g)=>h.localeCompare(g))[0]??o.open_status;return{dependencyValues:p,status:_}}function oI(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let r=t.governance.create_default_type?.trim();if(r&&r.length>0&&ke(r,n)){e.type=r;return}ke("Task",n)&&(e.type="Task")}function iI(e,t){return e.options.filter(n=>rr("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function aI(e,t,n,r,o){let i=e,a=[];if(i.template!==void 0){let h=i.template.trim();if(h.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let g=await J0(h,t,n);i=Zg(B0(g,i))}if(i.type===void 0&&oI(i,r,o),i.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let s=ke(i.type,o);if(!s){let h=cf(i.type),g=h?ke(h,o):void 0;if(g)a.push(`type_coercion:${i.type.trim()}:${g}`),i.type=g,s=g;else throw new l(xt(i.type,o.types,Pt(n,r.schema)),d.USAGE)}let c=uo(s,o);if(!c)throw new l(`Invalid type value "${i.type}"`,d.USAGE);let m=c.name,p=iI(c,i),u=p.map(h=>`${h.key}=${String(i[h.key])}`);if(u.length>0){i.typeOption=[...u,...i.typeOption??[]];for(let h of p)delete i[h.key]}let f=D0(i.schedulePreset);if(f!==void 0&&!Qg.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=U0(i.createMode,f,r.governance.create_mode_default);return{resolvedOptions:i,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:a}}function sI(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let i of o)if(i.enabled){if(i.values&&i.values.length>0)throw new l(`Cannot combine ${i.clearFlag} with ${i.valueFlag}`,d.USAGE);n.add(i.metadataKey),r.add(i.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function cI(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=Aa.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Ce("create",r)}`,d.USAGE)}}function lI(e){let t=(n,r)=>{let o=Aa.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;sa(n,Ce("create",r),i)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function dI(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,d.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,d.USAGE)}var oy={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function mI(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:i,type:a,createMode:s,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(h=>{let g=h.type==="boolean"?"<true|false>":h.type==="array"?"<json-array>":h.type==="object"?"<json-object>":h.type==="number"?"<number>":h.type==="string_array"||h.repeatable?"<value>":"<string>";return{example:`--${h.cli_flag} ${g}`,description:`--${h.cli_flag} maps to ${h.metadata_key} (${h.type}${h.repeatable?", repeatable":""})`}}),p=[ny(n,r,o,i),...m.map(h=>h.example)].join(" "),u=[`Run "pm create --help --type ${a}" for type-aware required option guidance.`,...t.filter(h=>h==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+a+").")];s==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),Qg.has(a)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&u.push(`Required custom field formats: ${m.map(h=>h.description).join("; ")}.`);let f=[...new Set(t.flatMap(h=>{let g=h.split(" ",1)[0],y=oy[g];return y?[y]:[]}))];f.length>0&&u.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let _=t.length===1?`Missing required option ${t[0]} for type "${a}"`:`Missing required options ${t.join(", ")} for type "${a}"`;throw new l(_,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${a}" in one invocation.`,examples:[...f.map(h=>`pm create --type ${a} ${h} ...`),p],nextSteps:u,recovery:s==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function pI(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Lt(t.tags):[];return Nn(n,t.addTags)}function uI(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new l("--order and --rank must match when both are provided",d.USAGE);let n=t.order??t.rank,r=pn(e,"order",n,o=>fe(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function fI(e,t,n,r,o,i){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",d.USAGE);let a=e!==t.close_status?void 0:r.completedAt===void 0?i:se(r.completedAt,new Date(i),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:a,warnings:[]};let s=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:Qc(s,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:a,warnings:[]}}async function _I(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:i,author:a,extensionFieldNames:s,afterDocument:c,beforeDocument:m,historyMessage:p,changedFields:u,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,g=pt(t,n,r,o.item_format,i.type_to_folder),y=rt(t,r),w=Xe(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(P=>Ki(P.kind,w)),S=await ea({pmRoot:t,author:a,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:b}),T=b,$=[];try{let P=await Ie(t,r,o.locks.ttl_seconds,a,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let L=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await _e(t,o.item_format,i.type_to_folder,void 0,o.schema):void 0,q=await z(t,r,o.id_prefix,o.item_format,i.type_to_folder);if(q)throw new l(`Item "${r}" already exists`,d.CONFLICT,{code:"item_already_exists",id:q.id,path:q.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${q.id}.`]});if(L){zi(L,[...L,c.metadata],w);let me=F(o.schema);Ti(L,[...L,c.metadata],r,$e=>re($e,me),w)}let H=await wr({pmRoot:t,settings:o,operation:"create",author:a,before:null,after:c});await Yo({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:ki({pmRoot:t,settings:o,typeToFolder:i.type_to_folder})});let J=await Mt(t,a,{required:o.governance.duplicate_detection_mode==="strict"&&h!==!0}),ie=[];try{o.governance.duplicate_detection_mode==="strict"&&h!==!0&&await jn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await te(g,We(c,{format:o.item_format,schema:o.schema,extensionFieldNames:s}));try{let me=Fe({nowIso:f,author:a,op:"create",before:m,after:c,message:p,context:H.decisions.length===0?void 0:{workflow_policies:H.decisions}});await Nt(y,me)}catch(me){throw await Sn(g),me}T&&(await S(),T=!1),ie=await Dt({pmRoot:t,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:g,document:c})}finally{await J()}$=[...H.warnings,...L?qi(L,[...L,c.metadata],r):[],...ie,...await Y({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:u}),...await Y({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:u})],Cn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Qt(c.metadata,u),changed_fields:u})}finally{await P()}}finally{T&&await S()}return $}async function jt(e,t){let n=Zg(await F0(e)),r=E(process.cwd(),t.path);await I(r);let o=await A(r),i=F(o.schema),a=ot(o.schema),s=x(o,R()),c=await aI(n,t,r,o,s);n=c.resolvedOptions;let{typeDefinition:m,type:p,createMode:u}=c,f=S0(n.unset,a),{explicitUnsets:_,clearOptionKeys:h}=sI(n,f);cI(n,f),lI(n);let g=C(ve(n.author),o.author_default),y=G0(m,n,u,h,g),w=k(),b=E0(n.dep,w,o.id_prefix,g),S=un("--comment",n.comment,w,g),T=un("--note",n.note,w,g),$=un("--learning",n.learning,w,g),P=dl(n.file),L=ml(n.test);L.values=await Kn(L.values,g,w);let q=pl(n.doc),H=T0(n.reminder,w),J=C0(n.event,w),ie=L0(n.typeOption),me=or(p,ie.values,s),$e=R(),Be=It($e),K=mo(n.field,$e,ia),ae=Ru(n,a,p),as=new Set(ae.missing_required_flags),ss=a.definitions.filter(W=>as.has(`--${W.cli_flag}`));dI(K,ae,f);let tr=j0(me.errors,p),Ht=tr.map(W=>`--type-option ${W}=<value>`),to=[...new Set([...y,...Ht,...ae.missing_required_flags])].sort((W,_s)=>W.localeCompare(_s));mI({combinedMissingFlags:to,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:tr,openStatus:i.open_status,type:p,createMode:u,missingRequiredRuntimeFields:ss}),K0(me.errors,p,m,i);let Ke=await nI({pmRoot:r,settings:o,typeRegistry:s,explicitId:n.id}),At=n.status!==void 0?v0(n.status,i):b0(m,i),no=n.priority!==void 0?$n(n.priority):2,O=f.metadataKeys,Bt=pI(O,n),vn=pn(O,"deadline",n.deadline,W=>se(W,new Date(w),"deadline")),Tt=pn(O,"estimated_minutes",n.estimatedMinutes,W=>Ln(W,"estimated-minutes")),cs=V(O,"acceptance_criteria",n.acceptanceCriteria),nt=V(O,"definition_of_ready",n.definitionOfReady),ls=uI(O,n),ro=V(O,"goal",n.goal),Lb=V(O,"objective",n.objective),$b=V(O,"value",n.value),Fb=V(O,"impact",n.impact),Mb=V(O,"outcome",n.outcome),Db=V(O,"why_now",n.whyNow),Ub=V(O,"assignee",n.assignee),Gb=O.has("author")?void 0:ve(n.author)??g,jb=V(O,"parent",n.parent),Fd=await Z0(jb,n,O,r),ds=Fd.parent,qb=Fd.parentSource,Kb=V(O,"reviewer",n.reviewer),zb=pn(O,"risk",n.risk,W=>Ze(ta(W),bn,"risk")),Hb=pn(O,"confidence",n.confidence,W=>ra(W)),Bb=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Md=o.validation.sprint_release_format,Vt=[...c.warnings,...Q0(p,Ke,vn,H.values,J.values)],Dd=await tI({itemId:Ke,parent:ds,pmRoot:r,settings:o,typeRegistry:s,policy:Bb});ds=Dd.parent,Vt.push(...Dd.warnings);let Ud=Xg(O,"sprint",n.sprint,"sprint",Md),Vb=Ud.value;Vt.push(...Ud.warnings);let Gd=Xg(O,"release",n.release,"release",Md),Wb=Gd.value;Vt.push(...Gd.warnings);let jd=V(O,"blocked_by",n.blockedBy),qd=await rI({pmRoot:r,settings:o,typeRegistry:s,statusRegistry:i,blockedBy:jd,dependencyValues:b.values,status:At,statusExplicit:n.status!==void 0,nowValue:w,author:g}),ms=qd.dependencyValues;jr(Ke,ms),Vt.push(...await mn({pmRoot:r,dependencies:ms,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:s.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ke,createdAt:w}],schema:o.schema})),At=qd.status;let Yb=V(O,"blocked_reason",n.blockedReason),Jb=V(O,"unblock_note",n.unblockNote),Xb=V(O,"reporter",n.reporter),Qb=pn(O,"severity",n.severity,W=>Ze(na(W),kn,"severity")),Zb=V(O,"environment",n.environment),ek=V(O,"repro_steps",n.reproSteps),Kd=V(O,"resolution",n.resolution),tk=V(O,"expected_result",n.expectedResult),nk=V(O,"actual_result",n.actualResult),rk=V(O,"affected_version",n.affectedVersion),ok=V(O,"fixed_version",n.fixedVersion),ik=V(O,"component",n.component),ak=pn(O,"regression",n.regression,W=>oa(W)),sk=V(O,"customer_impact",n.customerImpact),ps=ul(n.title,"--title"),us=n.description??"",oo=n.body??"",zd=await jn({title:ps,description:us,body:oo},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Vt.push(...Ni(zd));let fs=fI(At,i,o,n,Kd,w),ck=fs.closeReason,lk=At===i.close_status?w:void 0,dk=fs.completedAt;Vt.push(...fs.warnings);let io=Js({id:Ke,title:ps,description:us,type:p,type_options:me.normalized,status:At,closed_at:lk,completed_at:dk,close_reason:ck,priority:no,tags:Bt,created_at:w,updated_at:w,deadline:vn,assignee:Ub,author:Gb,estimated_minutes:Tt,acceptance_criteria:cs,definition_of_ready:nt,order:ls,goal:ro,objective:Lb,value:$b,impact:Fb,outcome:Mb,why_now:Db,parent:ds,reviewer:Kb,risk:zb,confidence:Hb,sprint:Vb,release:Wb,blocked_by:jd,blocked_reason:Yb,unblock_note:Jb,reporter:Xb,severity:Qb,environment:Zb,repro_steps:ek,resolution:Kd,expected_result:tk,actual_result:nk,affected_version:rk,fixed_version:ok,component:ik,regression:ak,customer_impact:sk,dependencies:ms,comments:S.values,notes:T.values,learnings:$.values,files:P.values,tests:L.values,docs:q.values,reminders:H.values,events:J.values,...K,...ae.values});try{po(io,$e)}catch(W){throw new l(W instanceof Error?W.message:"Invalid extension item field values",d.USAGE)}let mk=it({metadata:io,body:oo},{schema:o.schema,extensionFieldNames:Be}),pk={metadata:{},body:""},Hd=[..._].sort((W,_s)=>W.localeCompare(_s)),uk=R0(n.message,Hd),Bd=I0(io,oo,Hd,[...Object.keys(K),...Object.keys(ae.values??{})]),fk=await _I({pmRoot:r,type:p,id:Ke,settings:o,typeRegistry:s,author:g,extensionFieldNames:Be,afterDocument:mk,beforeDocument:pk,historyMessage:uk,changedFields:Bd,nowValue:w,similarityCandidate:{title:ps,description:us,body:oo},allowDuplicate:n.allowDuplicate}),Vd=structuredClone(io);u==="strict"&&_.has("dependencies")&&(Vd.dependencies=[]);let _k=$g(Ke,p,At,i);return ry(p,vn,H.values,J.values)&&au(`[pm] warning: ${p} '${Ke}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ke} --deadline <ISO>' or 'pm update ${Ke} --event "start=<ISO>,end=<ISO>"'.`),{item:Vd,changed_fields:Bd,warnings:[...Vt,...fk],...Object.fromEntries([["parent_source",qb],["next_transition",_k],["similarity_advisory",zd]].filter(W=>W[1]!==void 0))}}import Ia from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d29ab3a3-319f-506f-8289-78d786b95255")}catch{}})();async function fl(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),i=C(t.author,o.author_default),a=await ff({pmRoot:r,settings:o,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),s=a.targetPath?Ia.relative(r,a.targetPath).split(Ia.sep).join("/"):void 0;return{item:a.item,changed_fields:a.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:a.item.status,...s?{target_path:s}:{},history_retained:Ia.relative(r,rt(r,a.item.id)).split(Ia.sep).join("/"),tombstone_retention:"retain_append_only",warnings:a.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c7047beb-5c3a-5d97-acb9-7ddd15a223ec")}catch{}})();async function hI(e){await I(e)}async function _l(e,t,n){let r=E(process.cwd(),n.path);if(await hI(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",d.USAGE);let p=await A(r),u=xn(C(void 0,p.author_default));return await Iu(r),await Hi({pmRoot:r,settings:p,principal:u}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await ri(r);if(p===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let u=await gI(r,p);return{action:"show",focused_item:p,title:u,message:`Focused on ${p}${u?` (${u})`:""}. New items default --parent to it.`}}let o=await A(r),i=x(o,R()),a=await z(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await gt(r,e,o.id_prefix,i.type_to_folder);let s=ze(a.id,o.id_prefix),c=await ce(a,{schema:o.schema}),m=iy(c.document.metadata.title);return await Cu(r,s),await Hi({pmRoot:r,settings:o,principal:xn(C(void 0,o.author_default)),itemId:s}),{action:"set",focused_item:s,title:m,message:`Focused on ${s}${m?` (${m})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function gI(e,t){let n=await A(e),r=x(n,R()),o=await z(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let i=await ce(o,{schema:n.schema});return iy(i.document.metadata.title)}function iy(e){return e.trim().length>0?e:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="961c1918-75f9-5e5d-bbae-b333ca29534f")}catch{}})();function Ra(e){return Bo("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1d77acec-3731-597e-ad30-9ea1d25c057f")}catch{}})();var wl=[...rl,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...ol,...wa],yI=(()=>{let e=new Map;for(let t of wl)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Oa=new Map(wl.map(e=>[e.optionKey,e.canonical])),wI=wl.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),vI=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),bI=aa({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function uy(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i},r=new Set([...Oa.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!Qe(i))continue;let a=o==="rank"?"order":Oa.get(o)??o;n(a),t[o]=void 0}return Oe(e,ca(t,bI))}function fy(e,t,n=[]){return va({raw:e,supportedFields:wI,resolveDefinition:r=>{let o=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return yI.get(r)??ba(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var ay=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function sy(e){let t=e.disallowedFlags.flatMap(r=>{let o=ay.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=ay.get(r);return o?[`Replace ${r} with: ${o(e.id)}`]:[]});return new l(e.message,d.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function kI(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let i=(c,m,p)=>{c&&p.push(m)};if(o){let c=[];if(i(t.title!==void 0,"--title",c),i(t.description!==void 0,"--description",c),i(t.body!==void 0,"--body",c),i(t.status!==void 0,"--status",c),i(t.closeReason!==void 0,"--close-reason",c),i(t.priority!==void 0,"--priority",c),i(t.type!==void 0,"--type",c),i(t.tags!==void 0,"--tags",c),i(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),i(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),i(t.deadline!==void 0,"--deadline",c),i(t.estimatedMinutes!==void 0,"--estimate",c),i(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),i(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),i(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),i(t.definitionOfReady!==void 0,"--definition-of-ready",c),i(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),i(t.goal!==void 0,"--goal",c),i(t.objective!==void 0,"--objective",c),i(t.value!==void 0,"--value",c),i(t.impact!==void 0,"--impact",c),i(t.outcome!==void 0,"--outcome",c),i(t.whyNow!==void 0,"--why-now",c),i(t.assignee!==void 0,"--assignee",c),i(t.parent!==void 0,"--parent",c),i(t.reviewer!==void 0,"--reviewer",c),i(t.risk!==void 0,"--risk",c),i(t.confidence!==void 0,"--confidence",c),i(t.sprint!==void 0,"--sprint",c),i(t.release!==void 0,"--release",c),i(t.blockedBy!==void 0,"--blocked-by",c),i(t.blockedReason!==void 0,"--blocked-reason",c),i(t.unblockNote!==void 0,"--unblock-note",c),i(t.reporter!==void 0,"--reporter",c),i(t.severity!==void 0,"--severity",c),i(t.environment!==void 0,"--environment",c),i(t.reproSteps!==void 0,"--repro-steps",c),i(t.resolution!==void 0,"--resolution",c),i(t.expectedResult!==void 0,"--expected-result",c),i(t.actualResult!==void 0,"--actual-result",c),i(t.affectedVersion!==void 0,"--affected-version",c),i(t.fixedVersion!==void 0,"--fixed-version",c),i(t.component!==void 0,"--component",c),i(t.regression!==void 0,"--regression",c),i(t.customerImpact!==void 0,"--customer-impact",c),i(t.depRemove!==void 0,"--dep-remove",c),i(t.replaceDeps===!0,"--replace-deps",c),i(t.replaceTests===!0,"--replace-tests",c),i(t.replaceFiles===!0,"--replace-files",c),i(t.replaceDocs===!0,"--replace-docs",c),i(t.comment!==void 0,"--comment",c),i(t.note!==void 0,"--note",c),i(t.learning!==void 0,"--learning",c),i(t.file!==void 0,"--file",c),i(t.test!==void 0,"--test",c),i(t.doc!==void 0,"--doc",c),i(t.reminder!==void 0,"--reminder",c),i(t.event!==void 0,"--event",c),i(t.typeOption!==void 0,"--type-option",c),i(t.clearDeps===!0,"--clear-deps",c),i(t.clearComments===!0,"--clear-comments",c),i(t.clearNotes===!0,"--clear-notes",c),i(t.clearLearnings===!0,"--clear-learnings",c),i(t.clearFiles===!0,"--clear-files",c),i(t.clearTests===!0,"--clear-tests",c),i(t.clearDocs===!0,"--clear-docs",c),i(t.clearReminders===!0,"--clear-reminders",c),i(t.clearEvents===!0,"--clear-events",c),i(t.clearTypeOptions===!0,"--clear-type-options",c),i(t.force===!0,"--force",c),i(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw sy({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let a=[];i(t.status!==void 0,"--status",a),i(t.closeReason!==void 0,"--close-reason",a),i(t.assignee!==void 0,"--assignee",a),i(t.parent!==void 0,"--parent",a),i(t.blockedBy!==void 0,"--blocked-by",a),i(t.blockedReason!==void 0,"--blocked-reason",a),i(t.unblockNote!==void 0,"--unblock-note",a),i(t.dep!==void 0,"--dep",a),i(t.depRemove!==void 0,"--dep-remove",a),i(t.replaceDeps===!0,"--replace-deps",a),i(t.replaceTests===!0,"--replace-tests",a),i(t.replaceFiles===!0,"--replace-files",a),i(t.replaceDocs===!0,"--replace-docs",a),i(t.note!==void 0,"--note",a),i(t.learning!==void 0,"--learning",a),i(t.test!==void 0,"--test",a),i(t.reminder!==void 0,"--reminder",a),i(t.event!==void 0,"--event",a),i(t.clearDeps===!0,"--clear-deps",a),i(t.clearComments===!0,"--clear-comments",a),i(t.clearNotes===!0,"--clear-notes",a),i(t.clearLearnings===!0,"--clear-learnings",a),i(t.clearFiles===!0,"--clear-files",a),i(t.clearTests===!0,"--clear-tests",a),i(t.clearDocs===!0,"--clear-docs",a),i(t.clearReminders===!0,"--clear-reminders",a),i(t.clearEvents===!0,"--clear-events",a);let s=[...n].filter(c=>vI.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(a.push(...s),a.length>0)throw sy({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${a.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:a})}function SI(e,t){let n=ee(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function EI(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Vp({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=ee(e.fromStatus,e.statusRegistry)??e.fromStatus,r=ee(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Wp(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,d.USAGE);return`workflow_transition_not_allowed: ${o}`}function AI(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:_y(e)}function _y(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(t).toISOString()}function Vn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var TI=["id","kind","type","author","created_at","source_kind"],CI=["id","kind","type","author","created_at","source_kind"];function hy(e){return e.startsWith("```")||e.includes(`
22
+ `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:ui(e)}function gy(e){return typeof e=="string"?Xe().resolve(e)?.kind??e.trim():e}function Pa(e,t,n,r){return e?(Pe(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=hy(i);Gr(i,a);let s=a?pe(o,"--dep"):{id:i,kind:"related"};a&&Je(s,"--dep",TI);let c=s.id?.trim(),m=gy((s.kind??s.type)?.trim());if(!c||!m)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",d.USAGE);if(c.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=br(Vn(s.source_kind)),u=Vn(s.author);return{id:kr(c,t,p),kind:Ur(m),created_at:AI(s.created_at,n),author:u??r,source_kind:p??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function II(e,t){return e?(Pe(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new l("--dep-remove requires id or key/value selectors",d.USAGE);let o=hy(r);if(Gr(r,o,"--dep-remove"),o){let i=pe(r,"--dep-remove");Je(i,"--dep-remove",CI);let a=i.id?.trim();if(!a)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(a.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${a}"`,d.USAGE);let s=gy(Vn(i.kind??i.type)),c=br(Vn(i.source_kind)),m=Vn(i.author),p=Vn(i.created_at);return{id:kr(a,t,c),kind:s?Ur(s):void 0,source_kind:c,author:m,created_at:p?_y(p):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:ze(r,t)}})):[]}function xa(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function RI(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),i=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,i].join("\0")}function OI(e,t,n,r){let o=[...e??[]],i=!1;if(t===void 0){let a=o.filter(s=>s.kind!=="blocked_by");return a.length!==o.length&&(o=a,i=!0),i?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(a=>a.kind==="blocked_by"&&a.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),i=!0),i?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function xI(e,t,n,r,o,i){if(e===void 0||t)return{};let a=e.trim();if(a.length===0)return{};let s=await z(n,ze(a,r),r,o,i);return s?{id:s.id}:{unresolved:a}}function PI(e,t,n,r,o){let i=OI(e.dependencies,t,n,r);i.changed&&(i.dependencies===void 0?delete e.dependencies:e.dependencies=i.dependencies,o.includes("dependencies")||o.push("dependencies"))}function NI(e){return`${e.path}::${e.scope}`}function LI(e){return`${e.path}::${e.scope}`}function $I(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function yy(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function cy(e,t){let n=rr("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function FI(e,t,n){let r=new Set,o=(i,a)=>{a&&r.add(i)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let i=fy(e.unset,t,n);for(let a of i.optionKeys)o(a,!0)}return r}function MI(e,t,n,r,o){let i=uo(e,n);if(!i)throw new l(`Invalid type value "${e}"`,d.USAGE);let a=An(i,"update",[]);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);let s=FI(t,r,o);for(let c of a.disabled)if(s.has(cy(c,e)))throw new l(`Option ${Ce("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of a.required)if(!s.has(cy(c,e)))throw new l(`Missing required option ${Ce("update",c)} for type "${e}"`,d.USAGE)}var DI=new Set(["order","rank"]),UI=Ts.filter(e=>!DI.has(e)),wy=["tags","closeReason",...UI],GI=["title","description","body","status","closeReason","completedAt","priority","type",...Ts,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],jI=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>se(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Ln(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],qI=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Ze(ta(e),bn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>ra(e)}],KI=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Ze(na(e),kn,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>oa(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function yl(e,t,n){for(let r of e){let o=t[r.optionKey],i=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!i)){if(i){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new l(`${Ce("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function zI(e){return uy(await fi(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function vl(e){return ht(e)?await zI(e):uy(e)}function HI(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function hl(e){if(e.enabled&&(!e.values||e.values.length===0))throw new l(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,d.USAGE);if(e.enabled&&e.clearEnabled)throw new l(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,d.USAGE)}function bl(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new l("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",d.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new l("--replace-deps requires at least one --dep entry",d.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new l("--replace-deps cannot be combined with --dep-remove",d.USAGE);hl({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),hl({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),hl({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function BI(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new l(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,d.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function VI(e){let t={};for(let n of wy)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function WI(e,t){let n=VI(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=Oa.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Ce("update",r)}`,d.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --add-ac",d.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --remove-ac",d.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new l("Cannot combine --unset tags with --remove-tags",d.USAGE)}}function YI(e){let t=(n,r)=>{let o=Oa.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;sa(n,Ce("update",r),i)};for(let n of wy)t(e[n],String(n));t(e.order??e.rank,"order"),Pe(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Pe(e.event,"--event","Use --clear-events to clear linked events.")}function JI(e,t){let n={};for(let r of GI)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function XI(e){let t=await z(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await gt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ce(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function QI(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return _e(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function ZI(e){e.before&&(zi(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Ti(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>re(t,e.statusRegistry),Xe()))}function eR(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new l("--order and --rank must match when both are provided",d.USAGE)}async function tR(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Ai(yi(e.options.parent),e.settings.id_prefix);if(Zo(t))return{resolvedParentValue:t,warnings:[]};if(vi(e.id,t,e.settings.id_prefix),await z(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let n=ze(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:wi(n,e.parentReferencePolicy).warnings}}function nR(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function rR(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await z(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await gt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ce(t,{schema:e.settings.schema}),r=e.options.type!==void 0?ke(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=EI({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function oR(e){if(!e.fieldFlags.status||ee(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let t=Object.entries(e.fieldFlags).filter(([a,s])=>s&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),n=[],r=[];if(t.length>0){let a=Oe(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),s=await ct(e.id,a,e.global);r=s.changed_fields,n.push(...s.warnings)}let o=await kt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...e.workflowTransitionWarnings,...n,...o.warnings,"auto_routed_from_update_to_close"];return{item:o.item,changed_fields:[...r,...o.changed_fields],warnings:i}}function iR(e,t,n,r){return t.title!==void 0&&(e.metadata.title=ul(t.title,"--title"),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),ee(e.metadata.status,n)??e.metadata.status}var aR=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function sR(e,t){for(let n of aR)e[n]!==void 0&&(delete e[n],t.push(n))}function cR(e,t,n,r,o){let i=SI(n,t.statusRegistry);if(e.metadata.status=i,o.push("status"),i===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!re(i,t.statusRegistry)&&re(r,t.statusRegistry)&&sR(e.metadata,o)}function lR(e,t,n,r){if(t.options.status!==void 0&&cR(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!re(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=se(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function dR(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&re(n,t.statusRegistry)&&!re(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function mR(e,t,n,r){lR(e,t,n,r),dR(e,t,n,r)}function pR(e,t,n){let r=ke(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=$n(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=ke(t.options.type,t.typeRegistry);if(!o)throw new l(xt(t.options.type,t.typeRegistry.types,Pt(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=o,r=o,n.push("type")}return MI(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),uR(e,t,r,n),r}function uR(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let i=Ea(t.options.typeOption??[]),a=or(n,i,t.typeRegistry);if(a.errors.length>0)throw new l(a.errors.join("; "),d.USAGE);e.metadata.type_options=a.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let o=or(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=o.normalized}function fR(e,t){let n=new Set(t.map(o=>xa(o))),r=new Set;return e.filter(o=>{if(!n.has(xa(o)))return!0;let i=RI(o);return r.has(i)?!1:(r.add(i),!0)})}function _R(e,t,n){let r=t.filter(o=>!e.some(i=>yy(i,o)));if(r.length!==0)throw new l(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,d.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function hR(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=fR(r,t.dependencyUpdates.additions);let o=new Set(r.map(i=>xa(i)));for(let i of t.dependencyUpdates.additions){let a=xa(i);o.has(a)||(r.push(i),o.add(a))}}t.dependencyRemovals.length>0&&(_R(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(i=>yy(o,i)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function gR(e,t,n){gl(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),gl(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),gl(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function gl(e,t,n,r,o,i){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],i.push(t))}function yR(e,t,n){ly(e,"files",t.options.file,t.fileUpdates.values,NI,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),wR(e,t,n),ly(e,"docs",t.options.doc,t.docUpdates.values,LI,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function ly(e,t,n,r,o,i,a,s){if(!(n===void 0&&!a.has(t))){if(i)e.metadata[t]=r;else if(a.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(p=>o(p)));for(let p of r){let u=o(p);m.has(u)||(c.push(p),m.add(u))}e.metadata[t]=c}s.push(t)}}function wR(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=dy(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=dy([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function dy(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=$I(r);n.has(o)||(t.push(r),n.add(o))}return t}function vR(e,t,n){let r=t.options.addTags,o=t.options.removeTags,i=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||i){let a=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Lt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=pi(Nn(a,r),o),n.changedFields.push("tags")}yl(jI,t.options,n),kR(e,t,n.changedFields)}function bR(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let i=mi(Pn(e.metadata.acceptance_criteria),r,o);if(i.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${i.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:i.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let a=i.criteria.join("; ");e.metadata.acceptance_criteria!==a&&(a===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=a,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function kR(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=fe(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function SR(e,t,n,r){ER(e,t,n.changedFields),AR(e,t,n.changedFields),yl(qI,t.options,n),my(e,t,"sprint",r,n.changedFields),my(e,t,"release",r,n.changedFields),TR(e,t,n.changedFields),yl(KI,t.options,n)}function ER(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new l("--assignee must not be empty. Use --unset assignee to clear it.",d.USAGE);e.metadata.assignee=r}n.push("assignee")}}function AR(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function my(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let i=bi(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=i.value,r.push(...i.warnings)}o.push(n)}}function TR(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&PI(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function CR(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=ka(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=Sa(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function IR(e,t,n){py(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),py(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,i]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let a=o.replaceAll("_","-"),s=t.runtimeFieldRegistry.definitions.find(c=>c.metadata_key===o)?.cli_flag??a;throw new l(`Cannot combine --unset ${a} with --${s}`,d.USAGE)}Se(e[o],i)||(e[o]=i,n.push(o))}let r=mo(t.options.field,t.extensionRegistrations,ia);for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new l(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,d.USAGE);for(let[o,i]of Object.entries(r))Se(e[o],i)||(e[o]=i,n.push(o))}function py(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function RR(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(o=>{let i=t[o];return i!==void 0&&(!Array.isArray(i)||!Se(i,n[o]??[]))});if(r!==void 0)throw new l(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,d.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${r}_requires_annotation_command`,required:`Use pm ${r} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${r} with pm ${r} ${e.metadata.id}.`,`Apply the correction with pm ${r} ${e.metadata.id} --edit <index> --add <text>.`]})}function OR(e,t){RR(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,o=[],i=[],a=iR(e,t.options,t.statusRegistry,o),s=e.metadata,c={metadataRecord:s,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};mR(e,t,a,o),pR(e,t,o),hR(e,t,o),gR(e,t,o),yR(e,t,o),vR(e,t,c),bR(e,t,c),SR(e,t,c,i),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&jr(e.metadata.id,e.metadata.dependencies),ee(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),CR(e,t,o),IR(s,t,o);try{po(s,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(u){throw new l(u instanceof Error?u.message:"Invalid extension item field values",d.USAGE)}let m=e.metadata,p=[...new Set(o)].filter(u=>u==="body"?e.body!==r:!Se(n[u],m[u]));return t.options.acceptanceCriteria!==void 0&&p.includes("acceptance_criteria")&&i.push(`acceptance_criteria_replaced:${Pn(n.acceptance_criteria).length}:${Pn(m.acceptance_criteria).length}`),{changedFields:p,warnings:i}}async function vy(e,t,n,r={}){t=await vl(t);let o=E(process.cwd(),n.path);await I(o);let i=await A(o),a=F(i.schema),s=ot(i.schema),c=R(),m=It(c),p=x(i,c),u=i.governance.workflow_enforcement??"off",f=u==="off"?[]:Bp(i.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][i.validation.parent_reference],h=fy(t.unset,s,m),g=new Set(h.optionKeys),y=new Set(h.metadataKeys);bl(t),BI({definitions:HI(t),options:t,clearOptionKeys:g,clearItemMetadataKeys:y}),kI(e,t,y),WI(t,h),YI(t);let w=C(t.author,i.author_default),b=new Date,S=b.toISOString(),T=Pa(t.dep,i.id_prefix,S,w);jr(e,T.additions);let $=await mn({pmRoot:o,dependencies:T.additions,idPrefix:i.id_prefix,itemFormat:i.item_format,typeToFolder:p.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:i.schema}),P=II(t.depRemove,i.id_prefix),L=un("--comment",t.comment,S,w),q=t.ownershipMetadataBypass===!0&&L.values?{...L,values:L.values.map(O=>({...O,author:w}))}:L,H=un("--note",t.note,S,w),J=un("--learning",t.learning,S,w),ie=dl(t.file),me=ml(t.test);me.values=await Kn(me.values,w,S);let $e=pl(t.doc),Be=[],K=await tR({id:e,options:t,unsetTargets:h,pmRoot:o,settings:i,typeRegistry:p,parentReferencePolicy:_}),ae=await xI(t.blockedBy,y.has("blocked_by"),o,i.id_prefix,i.item_format,p.type_to_folder),as=ae.id,ss=[...K.warnings,...nR(ae)],tr=ii(t,s,t.runtimeFieldCommands),Ht=JI(t,tr);if(!Object.values(Ht).some(Boolean))return XI({pmRoot:o,id:e,settings:i,typeRegistry:p});Be.push(...await rR({options:t,fieldFlags:Ht,workflowEnforcement:u,typeWorkflows:f,statusRegistry:a,typeRegistry:p,pmRoot:o,id:e,settings:i}));let to=await oR({options:t,fieldFlags:Ht,statusRegistry:a,workflowTransitionWarnings:Be,global:n,id:e});if(to)return to;eR(t);let Ke=Xe(),At=Ht.parent&&!y.has("parent")||T.additions.some(O=>Ki(O.kind,Ke)),no=await ea({pmRoot:o,author:w,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:At});try{let O=await QI({fieldFlags:Ht,clearedMetadataKeys:y,pmRoot:o,settings:i,typeToFolder:p.type_to_folder}),Bt,vn,Tt=await Si({pmRoot:o,settings:i,typeToFolder:p.type_to_folder,id:e,op:xR(t,r),author:w,message:t.message,resolveHistoryContext:()=>vn,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(nt){Bt=PR({document:nt,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:a}),vn=Bt?{recurrence:Bt}:void 0,O=O?.map(ro=>ro.id===nt.metadata.id?structuredClone(nt.metadata):ro);let ls=OR(nt,{options:t,settings:i,typeRegistry:p,statusRegistry:a,runtimeFieldRegistry:s,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:y,dependencyUpdates:T,dependencyRemovals:P,commentUpdates:q,noteUpdates:H,learningUpdates:J,fileUpdates:ie,testUpdates:me,docUpdates:$e,resolvedParentValue:K.resolvedParentValue,resolvedBlockedByDependencyId:as,runtimeFieldUpdates:tr,nowValue:b,nowIso:S,author:w,pmRoot:o});return ZI({before:O,document:nt,statusRegistry:a}),ls}});await no();let cs=O?qi(O,O.map(nt=>nt.id===Tt.item.id?Tt.item:nt),Tt.item.id):[];return{item:Tt.item,changed_fields:Tt.changedFields,warnings:[...Be,...ss,...$,...cs,...Tt.warnings],...Bt===void 0?{}:{lifecycle_transition:Bt}}}finally{await no()}}function xR(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function PR(e){if(e.recurrenceReason===void 0)return;let t=ee(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!re(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,d.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=ee(n,e.statusRegistry)??n,o=e.document.metadata,i=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(a=>{let s=o[a];return typeof s=="string"?[[a,s]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:i}}async function ct(e,t,n){return vy(e,t,n)}async function by(e,t,n,r){let o=await vy(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,d.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1e6c7ca-bea7-5875-83e6-917c4326b936")}catch{}})();async function kl(e,t,n,r){let o=t.trim();if(o.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",d.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let i=E(process.cwd(),r.path),a=n.expectedResult?.trim();if(a!==void 0&&a.length===0)throw new l("Reopen expected result must describe the current active outcome.",d.USAGE);let s=F((await A(i)).schema),c=s.open_status,m=Ra(s),p=n.status??c,u=ee(p,s)??p;if(u!==c&&u!==m)throw new l(`Reopen target status must be ${c} or ${m}; received ${p}.`,d.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([c,m])],suggested_retry:`pm item reopen ${e} "${o}" --status ${c}`,suggested_retry_args:["item","reopen",e,o,"--status",c]}});let f=await by(e,{status:u,expectedResult:a,unset:["close-reason","resolution",...a===void 0?["expected-result"]:[],"actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:f.item,changed_fields:f.changed_fields,warnings:f.warnings,recurrence:f.lifecycle_transition,...a===void 0?{recovery:{missing:["expected_result"],suggested_retry_args:["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"],suggested_retry:Te(["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"])}}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="56177893-3ccb-5b3f-aa82-9365c26c5d34")}catch{}})();async function ky(e,t,n){return[...await Promise.resolve().then(()=>Du(rt(e,t),t)).catch(()=>[])].reverse().find(r=>r.patch.some(o=>o.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ce03100c-3a4f-5ce4-a216-a3fabcfc655e")}catch{}})();var Sy="no_available_next_item";function Ey(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function qr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let i=await A(o),a=F(i.schema),s=C(r.author,i.author_default),c=xn(s),m=null,p=!1,u=[],f=await le({pmRoot:o,settings:i,id:e,op:"claim",author:s,message:r.message,force:t,skipNoop:!0,async mutate(_){let h=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||h;if(m=h.trim().length>0?h:null,jp(_.metadata.status,a)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&g!==c){if(r.ifAvailable===!0)return p=!0,u.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let b=await ky(o,_.metadata.id,h);throw new l(`Item ${_.metadata.id} is already ${b}. Use --force to take over, or --if-available to skip without failing.`,d.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."]})}u.push(`claim_takeover:${m}->${s}`)}let y={assignee:s,claim_principal:c},w=["assignee","claim_principal"].filter(b=>_.metadata[b]!==y[b]);return Object.assign(_.metadata,y),{changedFields:w,warnings:u}}});return p||await Ac({pmRoot:o,settings:i,principal:c,itemId:f.item.id}),{item:f.item,changed_fields:f.changedFields,claimed_by:p&&m!==null?m:s,previous_assignee:m,forced:t,...p?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function Ay(e,t,n={},r={}){let o=NR(n.maxAttempts),i=await A(E(process.cwd(),t.path)),a={...n,author:C(n.author,i.author_default)},s=await Rr({...r,callerAuthor:a.author,limit:String(o)},t),c=[s.recommended,...s.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return LR(c.slice(0,o),e,t,a)}function NR(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new l("--max-attempts must be an integer from 1 to 100",d.USAGE);return t}async function LR(e,t,n,r={},o=qr){let i=0;for(let s of e){i+=1;try{let c=await o(s.id,t,n,r),m={...c,recommendation:s,attempts:i,available:!0};if(!c.skipped)return m}catch(c){if(!Ey(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:C(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:i,warnings:[Sy]};let a=i===0;throw new l(a?"No actionable items matched the selection filters":"No actionable item remained available to claim",a?d.NOT_FOUND:d.CONFLICT,{code:Sy,why:a?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[a?"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 Kr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let i=await A(o),a=C(r.author,i.author_default),s=xn(a),c=r.ownershipReleaseBypass===!0,m=null,p;try{p=await le({pmRoot:o,settings:i,id:e,op:"release",author:a,message:r.message,force:t,bypassAssigneeConflict:c,mutate(_){return m=_.metadata.assignee??null,!m&&!_.metadata.claim_principal?{changedFields:[]}:(delete _.metadata.assignee,delete _.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(_){Lr(_,{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 Tc({pmRoot:o,principal:s,itemId:p.item.id});let u=F(i.schema),f=Ys(p.item.status,u)===Ys(u.in_progress_status,u);return{item:p.item,released_by:a,changed_fields:p.changedFields,previous_assignee:m,forced:t,...f?{warnings:["released_unclaimed_in_progress"],suggestions:[`${p.item.id} remains ${p.item.status} and unclaimed. If work is paused, run pm release ${p.item.id} --pause to move it to ${u.open_status}.`]}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69182e8d-b8c7-5b70-8650-185a8f07f6ee")}catch{}})();async function Sl(e,t,n){try{return await n()}catch(r){let o=r instanceof l?r.context:{},i=new l(r instanceof Error?r.message:String(r),r instanceof l?r.exitCode:d.GENERIC_FAILURE,{...o,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${o.why?` ${o.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...o.nextSteps??[]]});throw i.cause=r,i}}async function El(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new l("--start cannot be combined with --next or --if-available for an explicit item",d.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let r=await A(E(process.cwd(),n.path)),o=Ra(F(r.schema)),i=await qr(e,t.force===!0,n,t),a=i.item.id,s=await Sl(a,"claim",()=>ct(a,Ut(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:a,action:"start_task",claim:i,update:s}}async function Al(e,t,n){let r=await A(E(process.cwd(),n.path)),o=F(r.schema).open_status,i=await ct(e,Ut(t,{status:o},["assignee","pause"]),n),a=i.item.id,s=await Sl(a,"update",()=>Kr(a,t.force===!0,n,t));return{id:a,action:"pause_task",update:i,release:s}}async function Tl(e,t,n,r){let o=await kt(e,t,n,r),i=o.item.id,a=await Sl(i,"close",()=>Kr(i,n.force===!0,r,n));return{id:i,action:"close_task",close:o,release:a}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="140b50c9-b0b3-5446-8ef9-5993bf4d830c")}catch{}})();async function Ty(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options),o=e.force===!0||r.force===!0,i={...e.args,...r};if(i.start===!0)return fn(e,"start_task");let a=e.args.next===!0||r.next===!0?await Ay(o,e.global,i,i):await qr(zr(e,r),o,e.global,i);return Ae(a,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function zr(e,t){let n=e.id??v(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function Cl(e,t){return v(e.args,"reason")??v(e.args,"text")??v(t,"reason")??v(t,"text")}async function Cy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return r.releaseAssignment===!0?fn(e,"close_task"):Ae(await kt(zr(e,r),Cl(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function fn(e,t){let{changedFields:n,idOnly:r,runnerOptions:o}=he(e.args,e.options),i=zr(e,o),a=Ut(o,{force:e.force===!0||o.force===!0}),s=t==="start_task"?await El(i,a,e.global):t==="pause_task"?await Al(i,a,e.global):await Tl(i,Cl(e,o),a,e.global);return Ae(s,{changedFields:n,idOnly:r,compactEnvelope:n==="compact"&&!r})}async function Iy(e){if(e.options.pause===!0)return fn(e,"pause_task");let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options),o=await Kr(zr(e,r),e.force===!0,e.global,r);return Ae(o,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function Ry(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return Ae(await kl(zr(e,r),Cl(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a610a47-2af8-51b7-a8ab-2557eaf611e2")}catch{}})();function Na(e,t){let n=Te(["plan","show",e.plan.id,"--depth","deep",...t===void 0?[]:["--pm-path",t]]);return{kind:"plan_mutation",action:e.action,id:e.plan.id,status:e.plan.status,mode:e.plan.mode,steps_summary:e.plan.steps_summary,...e.step===void 0?{}:{step:{id:e.step.id,order:e.step.order,status:e.step.status}},materialized_count:e.materialized?.length??0,skipped_count:e.materialize_skipped?.length??0,warning_count:e.warnings.length,warnings:e.warnings.slice(0,3).map(r=>r.slice(0,160)),warnings_truncated:e.warnings.length>3||e.warnings.some(r=>r.length>160),next_action:e.next_actions?.[0]===void 0?n:t===void 0?e.next_actions[0]:`${e.next_actions[0]} --pm-path ${Xp(t)}`,inspection_command:n,omission_receipt:{has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"plan_detail",restore_with:n}]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1e5721e-92fd-5c2e-989f-d63892ed9d90")}catch{}})();var $R=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Oy=["brief","standard","deep"],Ny="plan-step-",Nl="draft",Pl=["bug-investigation","feature-implementation","refactoring-sprint"],xy={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function FR(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(xy,t)?xy[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${Pl.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Pl[0]}`]});return n.map(r=>({...r}))}function MR(e,t){return t>0?Math.round(e/t*100):0}function Ly(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(t=>t!=null).map(t=>(typeof t=="string"?t:String(t)).trim()).filter(t=>t.length>0)}function He(e){return Array.isArray(e)?e.flatMap(t=>Dn(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Dn(e,{unique:!1}):[]}function Ne(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function $y(e,t=Nl){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ys.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${ys.join(", ")}`,d.USAGE);return r}function Ll(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ws.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${ws.join(", ")}`,d.USAGE);return r}function Fy(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=bs.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${bs.join(", ")}`,d.USAGE);return r}function DR(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=vs.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${vs.join(", ")}`,d.USAGE);return n}function UR(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=Oy.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${Oy.join(", ")}`,d.USAGE);return n}function GR(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new l("Plan --fields requires a comma-separated list of plan field names",d.USAGE);return t}var Il=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function jR(e,t){let n=e,r={},o=[];for(let i of t){let a=i.startsWith("plan.")?i.slice(5):i;if(a.length!==0){if(!Il.has(a)){o.push(i);continue}Object.prototype.hasOwnProperty.call(n,a)&&(r[a]=n[a])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...Il].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...Il].join(",")}`}});return r}function $l(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let i=o.indexOf("=");if(i<=0)throw new l(`Invalid ${t} entry "${o}"; expected key=value`,d.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[o.slice(0,i).trim().toLowerCase()]=o.slice(i+1).trim()}return n}function Fl(e){let t=$l(e,"--file");if(!t.path)throw new l("--file requires path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function Ml(e){let t=$l(e,"--test");if(!t.command&&!t.path)throw new l("--test requires at least command=<value> or path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function Dl(e){let t=$l(e,"--doc");if(!t.path)throw new l("--doc requires path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function qR(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=MR(t.completed,t.total),t}function KR(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${Ny}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new l("Could not allocate step id (limit reached)",d.GENERIC_FAILURE)}function Wn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),i=e.find(a=>a.order===o);if(i)return i}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function Py(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function zR(e,t){let n=t.filter(a=>a.trim().toLowerCase()==="all"),r=[],o=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",d.USAGE);for(let a of e.slice().sort((s,c)=>s.order-c.order)){let s=Py(a);if(s){o.push({from_step:a.id,...s});continue}r.push(a)}return{targets:r,skipped:o}}let i=new Set;for(let a of t){let s=Wn(e,a);if(i.has(s.id))continue;i.add(s.id);let c=Py(s);if(c){o.push({from_step:s.id,...c});continue}r.push(s)}return{targets:r,skipped:o}}function HR(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function BR(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function VR(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function Ge(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((a,s)=>a.order-s.order),r=qR(n),o=BR(n),i={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Nl,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:VR(n),linked_items:(e.dependencies??[]).map(a=>({id:a.id,kind:a.kind}))};return(t==="standard"||t==="deep")&&(i.steps=n),t==="deep"&&(i.decisions=e.plan_decisions??[],i.discoveries=e.plan_discoveries??[],i.validation=e.plan_validation??[]),i}function je(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!cc(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function My(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new l(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,d.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function WR(e){let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n}}async function Dy(e,t){let n=x(e.settings,R()),r=await z(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,d.NOT_FOUND);let o=await ce(r,{schema:e.settings.schema});return My(o.document.metadata),{document:o.document,itemId:r.id}}function YR(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of He(e.related))t.push(`id=${n},kind=related`);for(let n of He(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of He(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function JR(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function XR(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||He(e.dependsOn).length>0||He(e.link).length>0}function QR(e){let t=e.stepTitle?.trim()||void 0,n=Ly(e.step),r=e.template?.trim()?FR(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function ZR(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",d.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${Pl[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",d.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function eO(e,t){let n=Ll(e.stepStatus,"pending"),r=Ul(e,"depends_on"),o=Ne(e.file).map(Fl),i=Ne(e.test).map(Ml),a=Ne(e.doc).map(Dl),s=k();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:a.length>0?a:void 0,created_at:s,updated_at:s,completed_at:n==="completed"?s:void 0}}function tO(e){let t=QR(e),n=XR(e);if(ZR(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[eO(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((o,i)=>({id:`${Ny}${String(i+1).padStart(3,"0")}`,order:i+1,title:o,body:t.templateSteps[i]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function Uy(e,t,n=[]){Oe(e,t),n.length>0&&tf(t,n)}async function nO(e,t,n){let r=e.title?.trim();if(!r)throw new l("pm plan create requires --title",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let o=$y(e.mode,Nl),i=DR(e.harness),a=e.fromSearch?.trim(),s=JR(e),{steps:c,hasPerStepDetailOptions:m}=tO(e);if(c.length===0&&m)throw new l("pm plan create step options require --step-title (or a single --step)",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let p=e.description?.trim()??e.scope?.trim()??r,u=e.claim?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:p,type:"Plan",template:void 0,file:Ne(e.file),test:Ne(e.test),doc:Ne(e.doc),field:Ne(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:YR(e),message:e.message??(a?`plan create (search: ${a})`:"plan create")};Uy(e,f);let _=await jt(f,t),h=await le({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(y){let w=["plan_mode"];y.metadata.plan_mode=o,i&&(y.metadata.plan_harness=i,w.push("plan_harness"));let b=e.scope?.trim();b&&(y.metadata.plan_scope=b,w.push("plan_scope"));let S=e.resumeContext?.trim();return S&&(y.metadata.plan_resume_context=S,w.push("plan_resume_context")),y.metadata.plan_steps=c,w.push("plan_steps"),s&&(y.metadata.plan_validation=[...y.metadata.plan_validation??[],s],w.push("plan_validation")),u&&(y.metadata.assignee=u,w.push("assignee")),{changedFields:w}}}),g=Ge(h.item,"brief");return{action:"create",plan:g,step:c[0],next_actions:je(_.item.id,g),warnings:[..._.warnings],generated_at:k()}}async function rO(e,t,n){let r=UR(t.depth),o=GR(t.fields),{document:i,itemId:a}=await Dy(n,e),s=Ge(i.metadata,o===null?r:"deep");return{action:"show",plan:o===null?s:jR(s,o),next_actions:je(a,s),warnings:[],generated_at:k()}}function oO(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function lt(e){let t=C(e.options.author,e.ctx.settings.author_default),n,r=await le({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){My(o.metadata);let i=F(e.ctx.settings.schema);if(re(o.metadata.status,i)||cc(o.metadata.plan_mode))throw new l(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.metadata.plan_mode??"unset"}) and cannot be mutated.`,d.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let a=(o.metadata.plan_steps??[]).slice(),s=new Map(Object.entries(o.metadata).filter(([u])=>u.startsWith("plan_")).map(([u,f])=>[u,JSON.stringify(f)])),c=e.mutator(a,o);n=c.resultStep;let m=a.slice().sort((u,f)=>u.order-f.order).map((u,f)=>({...u,order:f+1}));o.metadata.plan_steps=m;let p=oO(s,o.metadata);return p.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:p.length>0?p:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function iO(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let o=Ll(t.stepStatus,"pending"),i=t.allowMultipleActive===!0,{document:a,resultStep:s,itemId:c}=await lt({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(p){let u=p.length+1;Gy(p,void 0,o,i);let f=aO(p,t,{order:u,title:r,status:o});return p.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Ge(a.metadata,"standard");return{action:"add-step",plan:m,step:s,next_actions:je(c,m),warnings:[],generated_at:k()}}function Gy(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(i=>i.id!==t&&i.status==="in_progress");if(o)throw new l(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function aO(e,t,n){let r=Ul(t,"depends_on"),o=Ne(t.file).map(Fl),i=Ne(t.test).map(Ml),a=Ne(t.doc).map(Dl),s=k();return{id:KR(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:a.length>0?a:void 0,created_at:s,updated_at:s,completed_at:n.status==="completed"?s:void 0}}function Ul(e,t){let n=He(e.dependsOn).map(p=>({id:p,kind:t})),r=He(e.related).map(p=>({id:p,kind:"related"})),o=He(e.blocks).map(p=>({id:p,kind:"blocks"})),i=He(e.blockedBy).map(p=>({id:p,kind:"blocked_by"})),a=He(e.link),s=Fy(e.linkKind,t),c=e.linkNote?.trim(),m=a.map(p=>{let u={id:p,kind:s};return c&&(u.note=c),u});return[...n,...r,...o,...i,...m]}async function Rl(e,t,n,r){let{document:o,resultStep:i,itemId:a}=await lt({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let p=Wn(c,r.stepRef),u=k(),f=r.finalStatus??Ll(t.stepStatus,p.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return Gy(c,p.status==="in_progress"?p.id:void 0,f,_),sO(p,t,f,u),m.metadata.updated_at=u,{changedSteps:[p.id],resultStep:p}}}),s=Ge(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:s,step:i,next_actions:je(a,s),warnings:[],generated_at:k()}}function sO(e,t,n,r){cO(e,t,n),lO(e,t),e.status=n,e.updated_at=r,dO(e,n,r)}function cO(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new l("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",d.USAGE)}function lO(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=t.stepOwner.trim()||void 0),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let r=Ne(t.file).map(Fl),o=Ne(t.test).map(Ml),i=Ne(t.doc).map(Dl);r.length>0&&(e.files=Ol(e.files,r)),o.length>0&&(e.tests=Ol(e.tests,o)),i.length>0&&(e.docs=Ol(e.docs,i))}function Ol(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let i=JSON.stringify(o);r.has(i)||(r.add(i),n.push(o))}return n}function dO(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function mO(e,t,n,r,o){let{document:i,itemId:a,resultStep:s}=await lt({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(m){let p=Wn(m,r),u=m.filter(_=>_.id!==p.id),f=Math.max(1,Math.min(o,u.length+1));return u.splice(f-1,0,p),u.forEach((_,h)=>{_.order=h+1,_.updated_at=k()}),m.length=0,m.push(...u),{changedSteps:[p.id],resultStep:p}}}),c=Ge(i.metadata,"standard");return{action:"reorder-step",plan:c,step:s,next_actions:je(a,c),warnings:[],generated_at:k()}}async function pO(e,t,n,r){let{document:o,itemId:i,resultStep:a}=await lt({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(c){let m=Wn(c,r),p=c.filter(u=>u.id!==m.id);return p.forEach((u,f)=>{u.order=f+1}),c.length=0,c.push(...p),{changedSteps:[m.id],resultStep:m}}}),s=Ge(o.metadata,"standard");return{action:"remove-step",plan:s,step:a,next_actions:je(i,s),warnings:[],generated_at:k()}}async function uO(e,t,n,r){let o=Ul(t,Fy(t.linkKind,"related"));if(o.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let i=t.promoteToItemDep===!0,{document:a,itemId:s,resultStep:c}=await lt({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(p,u){let f=Wn(p,r),_=f.linked_items??[],h=y=>`${y.kind}:${y.id}`,g=new Set(_.map(h));for(let y of o){let w=h(y);g.has(w)||(_.push(y),g.add(w))}if(f.linked_items=_,f.updated_at=k(),i){let y=u.metadata.dependencies??[],w=S=>`${S.kind}:${S.id}`,b=new Set(y.map(w));for(let S of o){let T=S.kind==="depends_on"?"blocked_by":S.kind,$={id:S.id,kind:T,created_at:k(),author:C(t.author,n.settings.author_default)};b.has(w($))||(y.push($),b.add(w($)))}u.metadata.dependencies=y}return{changedSteps:[f.id],resultStep:f}}}),m=Ge(a.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:je(s,m),warnings:[],generated_at:k()}}async function fO(e,t,n,r){let o=He(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:i,itemId:a,resultStep:s}=await lt({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let p=Wn(m,r),u=(p.linked_items??[]).filter(f=>!o.includes(f.id));return p.linked_items=u.length>0?u:void 0,p.updated_at=k(),{changedSteps:[p.id],resultStep:p}}}),c=Ge(i.metadata,"standard");return{action:"unlink",plan:c,step:s,next_actions:je(a,c),warnings:[],generated_at:k()}}async function xl(e,t,n,r){let o=HR(r,t);if(!o){let m=`--${r}-text`,p=`--${r}`;throw new l(`pm plan ${r} requires ${m}`,d.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${m} "..."`,`pm plan ${r} <plan-id> ${p} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${m} <value>`}})}let i=C(t.author,n.settings.author_default),{document:a,itemId:s}=await lt({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,p){let u=k();if(r==="decision"){let _=p.metadata.plan_decisions??[];return _.push({ts:u,author:i,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),p.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=p.metadata.plan_discoveries??[];return _.push({ts:u,author:i,text:o}),p.metadata.plan_discoveries=_,{changedSteps:[]}}let f=p.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),p.metadata.plan_validation=f,{changedSteps:[]}}}),c=Ge(a.metadata,"deep");return{action:r,plan:c,next_actions:je(s,c),warnings:[],generated_at:k()}}async function _O(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:o,itemId:i}=await lt({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(s,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),a=Ge(o.metadata,"brief");return{action:"resume",plan:a,next_actions:je(i,a),warnings:[],generated_at:k()}}async function hO(e,t,n){let r=$y(t.mode??"approved","approved"),{document:o,itemId:i}=await lt({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(s,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),a=Ge(o.metadata,"brief");return{action:"approve",plan:a,next_actions:je(i,a),warnings:[],generated_at:k()}}function jy(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function gO(e,t){let n=Ge(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:je(e.itemId,n),warnings:jy(t),generated_at:k()}}function yO(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let i=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${i}`)}return r}async function wO(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Ne(e.options.field)){let i=o.indexOf("=");if(i<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let c=a.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let[m,...p]=c,u=`${m}${p.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(u))throw new l(`Invalid --field entry "${o}"; "${u}" is reserved by materialize and cannot be overridden`,d.USAGE);n[u]=s}for(let o of e.targets){let i={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:yO(e.parent,e.planItemId,o)};Uy(e.options,i,["description",...Object.keys(n)]);let a=await jt(i,{path:e.pmRoot});t.push({id:a.item.id,title:a.item.title,type:e.resolvedTypeName,parent:a.item.parent,tags:a.item.tags??[],from_step:o.id})}return t}function vO(e,t,n){for(let r of t){let o=n.find(s=>s.from_step===r.id);if(!o)continue;let i=e.find(s=>s.id===r.id);if(!i)continue;let a=i.linked_items??[];a.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),i.linked_items=a,i.updated_at=k()}}async function bO(e,t,n){let r=He(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let o=t.materializeType?.trim()||"Task",i=x(n.settings,R()),a=ke(o,i);if(!a)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let s=t.materializeParent?.trim()||e,c=t.materializeTags,m=await Dy(n,e),p=(m.document.metadata.plan_steps??[]).slice(),{targets:u,skipped:f}=zR(p,r);if(u.length===0){if(f.length>0)return gO(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await wO({targets:u,parent:s,planItemId:m.itemId,resolvedTypeName:a,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:g}=await lt({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(w){return vO(w,u,_),{changedSteps:u.map(b=>b.id)}}}),y=Ge(h.metadata,"standard");return{action:"materialize",plan:y,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:je(g,y),warnings:jy(f),generated_at:k()}}function kO(e){if(e.subcommand==="create")return e;let t=Ly(e.options.step);if(t.length>1)throw new l(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,d.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:Oe(e.options,{...e.options,stepTitle:t[0]})}:e}function St(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function _n(e,t){let n=St(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function SO(e){let t=_n(e,"reorder-step");if(e.reorderTo===void 0)throw new l("pm plan reorder-step requires <plan-id> <step> <new-order>",d.USAGE);return{...t,reorderTo:e.reorderTo}}var EO={create:(e,t)=>nO(e.options,e.global,t),show:(e,t)=>rO(St(e,"show"),e.options,t),"add-step":(e,t)=>iO(St(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=_n(e,"update-step");return Rl(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=_n(e,"complete-step");return Rl(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=_n(e,"block-step");return Rl(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=SO(e);return mO(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=_n(e,"remove-step");return pO(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=_n(e,"link");return uO(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=_n(e,"unlink");return fO(n.id,e.options,t,n.stepRef)},decision:(e,t)=>xl(St(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>xl(St(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>xl(St(e,"validation"),e.options,t,"validation"),resume:(e,t)=>_O(St(e,"resume"),e.options,t),approve:(e,t)=>hO(St(e,"approve"),e.options,t),materialize:(e,t)=>bO(St(e,"materialize"),e.options,t)};function AO(e){let t=EO[e];if(!t)throw Re({command_path:"plan",token:e,allowed:$R});return t}async function qy(e){let t=await WR(e.global),n=kO(e),r=await AO(n.subcommand)(n,t);return r.action==="show"?r:{...r,mutation_receipt:Na(r,t.pmRoot)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a59a772-3e2a-5ae2-88c1-a96bc36f9f85")}catch{}})();var zy=1,jl="update-many",TO=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),CO=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),IO={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},RO=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],OO={close_reason:"close_reason","close-reason":"close_reason",deadline:"deadline",estimate:"estimated_minutes",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",ac:"acceptance_criteria",definition_of_ready:"definition_of_ready","definition-of-ready":"definition_of_ready",order:"order",rank:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",why_now:"why_now","why-now":"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blocked_by:"blocked_by","blocked-by":"blocked_by",blocked_reason:"blocked_reason","blocked-reason":"blocked_reason",unblock_note:"unblock_note","unblock-note":"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",repro_steps:"repro_steps","repro-steps":"repro_steps",resolution:"resolution",expected_result:"expected_result","expected-result":"expected_result",actual_result:"actual_result","actual-result":"actual_result",affected_version:"affected_version","affected-version":"affected_version",fixed_version:"fixed_version","fixed-version":"fixed_version",component:"component",regression:"regression",customer_impact:"customer_impact","customer-impact":"customer_impact",type_options:"type_options","type-options":"type_options",tags:"tags"},Hy=e=>{let t={};for(let[n,r]of Object.entries(e))TO.has(n)||r!==void 0&&(t[n]=r);return t},xO=e=>Object.keys(Hy(e)).length>0,By=e=>typeof e=="string"?e.trim():e,PO=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Gl=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},NO=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??By(e)},LO={priority:PO,estimatedMinutes:Gl,order:Gl,rank:Gl,regression:NO},$O=(e,t)=>{if(t!==void 0)return(LO[e]??By)(t)},FO=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return OO[t]??t},La=(e,t)=>Se(e,t),MO=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],DO=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,UO=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",Ky=(e,t)=>t===void 0?void 0:e[t],Yn=e=>Array.isArray(e)?e.length:0,GO=(e,t,n)=>{let r=n[e.addKey],o=Ky(n,e.removeKey),i=Yn(r),a=Yn(o),s=n[e.clearKey]===!0,c=Ky(n,e.replaceKey)===!0;if(![s,c,i>0,a>0].includes(!0))return;let m=MO(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:UO({replace:c,clear:s,removeCount:a}),clear:s,replace:c,add_count:i,remove_count:a,before_count:DO(e.field,m)}}},jO=(e,t)=>{let n=[];for(let r of RO){let o=GO(r,e,t);o!==void 0&&n.push(o)}return n},qO=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],KO=(e,t)=>{if(![t.tags!==void 0,Yn(t.addTags)>0,Yn(t.removeTags)>0].includes(!0))return;let n=qO(e.tags),r=t.tags===void 0?n:Lt(t.tags),o=Nn(r,t.addTags),i=pi(o,t.removeTags).slice().sort((s,c)=>s.localeCompare(c)),a=n.slice().sort((s,c)=>s.localeCompare(c));if(!La(a,i))return{field:"tags",before:n,after:i}},zO=(e,t)=>{let n=e.acceptance_criteria,r=mi(Pn(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let o=r.criteria.join("; ");if(!La(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},HO=(e,t,n)=>{for(let[r,o]of Object.entries(IO)){let i=n[r];if(i===void 0)continue;let a=t[o],s=$O(r,i);La(a,s)||e.push({field:o,before:a,after:s})}},BO=(e,t,n,r)=>{let o=ii(n,r,["update_many"]);for(let[i,a]of Object.entries(o)){let s=t[i];La(s,a)||e.push({field:i,before:s,after:a})}},VO=(e,t,n)=>{for(let r of n??[]){let o=FO(r),i=t[o];i!==void 0&&e.push({field:o,before:i,after:null})}},WO=(e,t,n={})=>{let r=e,o=[],i=KO(r,n);if(i&&o.push(i),HO(o,r,n),Yn(n.addAc)>0||Yn(n.removeAc)>0){let a=zO(r,n);a!==void 0&&o.push(a)}return o.push(...jO(r,n)),BO(o,r,n,t),VO(o,r,n.unset),{id:e.id,changes:o}},YO=(e,t)=>sf(e,t,{strict:!0,flagLabel:"--filter-status"}),JO=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)},XO=[({update:e})=>{e.priority!==void 0&&$n(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,R());if(!ke(e.type,r))throw new l(xt(e.type,r.types,Pt(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!ee(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,d.USAGE)}},({update:e})=>{e.deadline!==void 0&&se(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&Ln(e.estimatedMinutes,"estimated-minutes")}],QO=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let i of XO)i(o)},ZO=async e=>{let t=await li(e.pmRoot,jl,e.rollbackId,zy),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await di(t.items,(o,i)=>on(o,i,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...Zt({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},ex=async e=>{let t={schema_version:zy,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await ci(e.pmRoot,jl,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},tx=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},ql=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},nx=async e=>{let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:F(n.schema),runtimeFieldRegistry:ot(n.schema)}},rx=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Ir(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",d.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",d.USAGE);return ZO({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},ox=async e=>{YO(e.options.status,e.runtime.statusRegistry);let t=await yt(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let i=WO(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?i:{...i,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await yt(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:tx(e.options.list?.ids,r)}},ix=e=>({outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...ql(e)}),ax=e=>({...Zt({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...ql(e)}),sx=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(i=>i.changes.length>0).map(i=>i.id));for(let i of e.items){if(!o.has(i.id)){t.push({id:i.id,status:"skipped"});continue}try{let a=ic({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),s=await ct(i.id,a,e.global);t.push({id:i.id,status:"updated",changed_fields:s.changed_fields,warnings:s.warnings}),n.push(i.id)}catch(a){t.push({id:i.id,status:"failed",error:En(a)})}}return{rows:t,updatedIds:n}},cx=async e=>{if(e.plan.actionable.length===0)return ax(e.plan);let t=k(),n=si(jl,t),r=new Set(e.plan.actionable.map(u=>u.id)),o=e.plan.listed.items.filter(u=>r.has(u.id)).map(u=>({id:u.id,target_updated_at:u.updated_at})),i=e.options.checkpoint===!1?void 0:await ex({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),a=await sx({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),s=u=>a.rows.filter(f=>f.status===u).length,c=s("updated"),m=s("skipped"),p=s("failed");return{...Zt({applied:c,skipped:m,failed:p,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...i?{checkpoint:i}:{},updated_count:c,skipped_count:m,failed_count:p,rows:a.rows,ids:a.updatedIds,...ql(e.plan)}},Vy=async(e,t)=>{let n=await nx(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:ic(await vl(e.update))});let o=Hy(e.update);if(JO(e.list),r!==void 0)return rx({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!xO(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${CO}), or pass --dry-run for a filter-only preview.`,d.USAGE);QO(e.update,n.settings,n.statusRegistry,n.pmRoot),bl(e.update);let i=await mn({pmRoot:n.pmRoot,dependencies:Pa(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),a=await ox({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:i});return await mn({pmRoot:n.pmRoot,dependencies:Pa(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:a.listed.items.map(s=>({id:s.id,createdAt:s.created_at})),schema:n.settings.schema}),e.dryRun===!0?ix(a):cx({runtime:n,options:e,global:t,plan:a})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6263346a-08ee-5eb9-81b9-47e933793c07")}catch{}})();function lx(e){if(e===void 0)return;if(e.trim().length===0)throw new l("--add-json must contain a JSON value",d.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new l("--add-json must be valid JSON",d.USAGE,{code:"structured_event_json_invalid"})}return t}function dx(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function mx(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new l("--since must be a valid ISO timestamp",d.USAGE,{code:"structured_event_since_invalid"});return t}async function Wy(e,t,n){let r=lx(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let i=r===void 0?void 0:Yt(r),a=[t.since,t.eventType].some(h=>h!==void 0),s=mx(t.since),c=yr(t.limit),m=await Hn(e,{...t,...a?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,a].includes(!0)},n,{input:await Qi(i===void 0?t:{add:i},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>zn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:dx(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm notes --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}}),p=t.eventType?.trim(),u=m.notes.filter(h=>{let g=[h.format==="json",h.data!==void 0].every(Boolean),y=[s===void 0,Date.parse(h.created_at)>=(s??Number.POSITIVE_INFINITY)].includes(!0),w=[!p,h.event_type===p].includes(!0);return[!a,[g,y,w].every(Boolean)].includes(!0)}),f=a?Gc(u,c):u,_=f.filter(h=>h.format==="json").length;return{...m,notes:f,count:f.length,...a?{total_count:u.length,returned_count:f.length,has_more:f.length<u.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}import Ex from"node:path";import px from"node:fs/promises";import Yy from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ac2020a4-78bf-5aa3-a5c4-88d3196dfb1f")}catch{}})();var ux="templates",fx=".json",_x=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,hx=ei.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),gx=new Set(hx);function yx(e){let t=e.trim();if(!_x.test(t))throw new l(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,d.USAGE);return t}function Jy(e){return Yy.join(e,ux)}function Xy(e,t){return Yy.join(Jy(e),`${t}${fx}`)}async function wx(e){await I(e)}function Qy(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function vx(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(gx.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(i=>typeof i=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return Qy(t)}function bx(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new l(`Template "${t}" has invalid options payload.`,d.GENERIC_FAILURE);let n=e,r={};for(let[o,i]of Object.entries(n)){let a=o.trim();if(a.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof i=="string"){r[a]=i;continue}if(Array.isArray(i)&&i.every(s=>typeof s=="string")){r[a]=[...i];continue}throw new l(`Template "${t}" contains invalid value for option "${a}".`,d.GENERIC_FAILURE)}return Qy(r)}function kx(e,t){let n;try{n=JSON.parse(e)}catch{throw new l(`Template "${t}" contains invalid JSON.`,d.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Template "${t}" has invalid document shape.`,d.GENERIC_FAILURE);let r=n,o=bx(r.options,t),i=k();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:i,updated_at:typeof r.updated_at=="string"?r.updated_at:i,options:o}}async function Sx(e,t){let n=await X(Xy(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return kx(n,t)}async function Kl(e,t,n){let r=E(process.cwd(),n.path);await wx(r);let o=yx(e),i=vx(t);if(Object.keys(i).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let a=k(),s=Xy(r,o),c=a;await j(s)&&(c=(await Sx(r,o)).created_at);let m={name:o,created_at:c,updated_at:a,options:i},p=await A(r);return await px.mkdir(Jy(r),{recursive:!0}),await Ye({pmRoot:r,filePath:s,raw:`${JSON.stringify(m,null,2)}
23
+ `,op:"templates:save",author:C(void 0,p.author_default),lockTtlSeconds:p.locks.ttl_seconds,lockWaitMs:p.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:s,options:m.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aa4e2ff3-dc3b-5688-bf40-bdd71c65320b")}catch{}})();var nw=["list","show","apply","lint"],Ax="schema-types",Tx="schema-statuses",Cx="schema-fields";function $a(){let e=R();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function rw(){let{profiles:e,warnings:t}=Dp($a());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:Kp(n.definition)})),warnings:t,generated_at:k()}}function ow(e){let t;try{t=zo(e,$a())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...zp(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function iw(e){let t;try{t=zo(e,$a())}catch(o){throw new l(o instanceof Error?o.message:String(o),d.USAGE)}let{resolved:n}=t,r=du(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:k()}}function Ix(e,t){return Ex.join(e,"templates",`${t}.json`)}async function Rx(e,t){let n=await X(Ix(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function Zy(e,t,n,r){let o=new Map;for(let i of r.templates){let a=await Rx(e,i.name);a!==void 0&&o.set(i.name,a)}return{typesRaw:await X(ft(e,t.files.types,ut.types)),statusesRaw:await X(ft(e,t.files.statuses,ut.statuses)),fieldsRaw:await X(ft(e,t.files.fields,ut.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Jn(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function ew(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Jn(t.types.changes),statuses:Jn(t.statuses.changes),fields:Jn(t.fields.changes),workflows:Jn(t.workflows.changes.map(i=>({key:i.type,status:i.status}))),config:Jn(t.config.changes),templates:Jn(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(o)].sort((i,a)=>i.localeCompare(a)),generated_at:k()}}async function Ox(e){await I(e)}function xx(e){try{let t=zo(e,$a());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function aw(e,t,n){let r=E(process.cwd(),n.path);await Ox(r);let o=xx(e),i=o.profile,a=o.warnings,s=t.dryRun===!0,c=await A(r),m=Ho(c.schema);if(s){let w=await Zy(r,m,c,i),b=tw(i,w);return ew(i,b,!1,!0,[...a])}let p=C(t.author,c.author_default),u=Xu(c),f=!!t.force,_=[...a],h=[],g=async w=>{h.push(await Ie(r,w,c.locks.ttl_seconds,p,f,u.force_required_for_stale_lock,c.locks.wait_ms))},y;try{await g(Ax),await g(Tx),await g(Cx);let w=await Zy(r,m,c,i);if(y=tw(i,w),y.types.changed){let b=ft(r,m.files.types,ut.types);await Ye({pmRoot:r,filePath:b,raw:Ko(y.types.file),op:"profile:apply-types",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(i.types.map($=>Pp($).name)),T=y.types.file.definitions.filter($=>S.has($.name));await Uf(r,T,_,"profile:apply-type-folder"),_.push(...await Y({path:b,scope:"project",op:"profile:apply-types"}))}if(y.statuses.changed){let b=ft(r,m.files.statuses,ut.statuses);await Ye({pmRoot:r,filePath:b,raw:qp(y.statuses.file),op:"profile:apply-statuses",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await Y({path:b,scope:"project",op:"profile:apply-statuses"}))}if(y.fields.changed){let b=ft(r,m.files.fields,ut.fields);await Ye({pmRoot:r,filePath:b,raw:Up(y.fields.file),op:"profile:apply-fields",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await Y({path:b,scope:"project",op:"profile:apply-fields"}))}if(y.config.changed||y.workflows.changed){for(let b of y.config.changes){if(b.status==="unchanged")continue;let S=Vo(b.key);S!==void 0&&Wo(c,S,b.value)}c.schema.type_workflows=y.workflows.result,await Me(r,c,"profile:apply-config")}for(let b of y.templates.changes)b.status!=="unchanged"&&await Kl(b.name,{...b.options},n)}finally{for(let w of h.reverse())try{await w()}catch{}}return ew(i,y,y.changed,!1,_)}function tw(e,t){try{return mu(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import Dx from"node:fs/promises";import Bl from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c34cc860-67c7-548b-99ff-f4155ef44bb0")}catch{}})();var cw=10,hn="https://schema.unbrained.dev/pm/eval-query-set/v1";var Fa={schema:hn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},et=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},Px=new Set(["keyword","semantic","hybrid"]);function sw(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function Nx(e,t,n){if(t.size===0)return 0;let r=e.map(s=>t.has(s)?1:0),o=sw(r,n),i=Array.from({length:t.size},()=>1),a=sw(i,n);return a===0?0:o/a}function Lx(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function zl(e,t,n){let r=Math.min(n,e.length),o=0;for(let i=0;i<r;i+=1)t.has(e[i])&&(o+=1);return o}function $x(e,t,n){return n<=0?0:zl(e,t,n)/n}function Fx(e,t,n){return t.size===0?0:zl(e,t,n)/t.size}function lw(e,t,n){return{ndcg:Nx(e,t,n),mrr:Lx(e,t,n),precision:$x(e,t,n),recall:Fx(e,t,n),relevant_total:t.size,retrieved_relevant:zl(e,t,n)}}function dw(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function Mx(e,t){if(typeof e!="object"||e===null)throw new et(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new et(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new et(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(i=>typeof i!="string"))throw new et(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new et(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!Px.has(n.mode)))throw new et(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.minimum===void 0?{}:{minimum:th(n.minimum)},...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Hl(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==hn)throw new et(`Unsupported eval query set schema; expected "${hn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new et('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new et("Eval query set must contain at least one query");return{schema:hn,queries:n.map((r,o)=>Mx(r,o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d26721c-719a-5c7e-8baf-72cbf1088988")}catch{}})();var Ux=Bl.join("search","eval-queries.json"),Vl={schema:hn,examples:[JSON.stringify(Fa)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},Gx=new Set(["keyword","semantic","hybrid"]),jx=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!Gx.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},qx=e=>{if(e===void 0||e==="")return cw;let t=am(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},Kx=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new l("Eval --fail-under must be a number in the range [0, 1]",d.USAGE);return n},qt=e=>Math.round(e*1e4)/1e4,zx=async e=>{try{return await Dx.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Vl,examples:[`echo '${JSON.stringify(Fa)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},Hx=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new l(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,d.USAGE,Vl)}},Bx=e=>{try{return Hl(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Vl)}},Vx=async e=>Bx(Hx(await zx(e),e)),Wx=async(e,t,n,r)=>{let o=e.mode??t,i=(await Or(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(s=>s.id).filter(s=>typeof s=="string"),a=lw(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:nh(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:qt(a.ndcg),mrr:qt(a.mrr),precision:qt(a.precision),recall:qt(a.recall)}}},Yx=(e,t,n,r)=>{let o=dw(n);return{k:e,query_count:t.length,aggregate:{ndcg:qt(o.ndcg),mrr:qt(o.mrr),precision:qt(o.precision),recall:qt(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:(r===void 0||o.ndcg>=r)&&t.every(i=>(i.violations?.length??0)===0)}},mw=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=qx(e.k),o=jx(e.mode),i=Kx(e.failUnder),a=e.queries?Bl.resolve(process.cwd(),e.queries):Bl.join(n,Ux),s=await Vx(a),c=[],m=[];for(let p of s.queries){let{report:u,metrics:f}=await Wx(p,o,r,t);m.push(f),c.push(u)}return Yx(r,c,m,i)};import{readFile as Jx,writeFile as Xx}from"node:fs/promises";import Qx from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="932450d7-963b-566b-a5ad-1b577a895e8e")}catch{}})();var pw=["item","history","relationship","json"];function Zx(e){let t=e.trim().toLowerCase();if(pw.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${pw.join(", ")}.`,d.USAGE)}function eP(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new l(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,d.USAGE)}async function Wl(e,t){try{return await Jx(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function tP(e){let t=E(process.cwd(),e.path);return await j(ne(t))?A(t):null}function nP(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function uw(e,t){let n=Zx(e.artifact),r=eP(e.prefer),o=Qx.resolve(e.outputPath??e.oursPath),[i,a,s]=await Promise.all([Wl(e.basePath,"base"),Wl(e.oursPath,"ours"),Wl(e.theirsPath,"theirs")]),c,m,p=[],u={};if(n==="history"){let _=g_(i,a,s);c=_.merged,u.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=y_(i,a,s);c=_.merged,u.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await tP(t),h=nP(e.itemPath??o,_),g=It(R()),y=w_(i,a,s,{format:h,schema:_?.schema,extensionFieldNames:g,preferred:r,conflictResolution:"latest_document_update"});if(c=y.merged,p.push(...y.conflict_fields),u.item={fields_from_theirs:y.fields_from_theirs,union_fields:y.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let w=Fu(c,{format:h,schema:_?.schema,extensionFieldNames:g}),b=w.metadata,S=[...new Set([...y.fields_from_theirs,...y.union_fields,...y.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:y.fields_from_theirs,unionFields:y.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,h_(T==="body"?w.body:b[T])])),decisions:y.conflict_decisions,operation:await b_(process.cwd(),e.itemPath,a)}}}else{let _=v_(i,a,s,{preferred:r});c=_.merged,p.push(..._.conflict_paths),u.json={paths_from_theirs:_.paths_from_theirs}}if(await Xx(o,c,"utf8"),m!==void 0){let _=await S_(m);_!==null&&(u.receipt=tn(_))}let f=[];if(p.length>0){let _=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${p.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&u.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:p.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:p,...u,guidance:f,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3fe6f853-6742-5305-b722-0cc74547f367")}catch{}})();async function fw(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await k_(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Gt(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Gt(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:r,message:e.message??`Settle ${n.operation.kind} receipt after exact original Git state restoration`,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...tn(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await $i(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as rP}from"node:fs/promises";import oP from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7b1ffef4-9e2b-5ff9-8b8c-030ea89ea27e")}catch{}})();var iP=4;function _w(e){let t=e.checks.find(s=>s.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,a=Array.isArray(o)?o.flatMap(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return[];let c=s;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:i,coordinates:a}}async function aP(e,t){let n=[];for(let r of t){let o;try{o=await rP(oP.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let i=o.split(/\r?\n/)[r.history_line-1];if(i===void 0||i.trim().length===0)continue;let a;try{a=JSON.parse(i)}catch{continue}let s=I_(a,r.item_id).find(c=>c.receiptId===r.receipt_id);s===void 0||!C_(s)||s.eventTimestamp===void 0||Qo(s.eventTimestamp,T_)>=0||n.push({...r,original_event_ts:s.eventTimestamp})}return n}async function sP(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;let t=new Map;for(let n of e.candidates){let r=t.get(n.item_id)??[];r.push(n),t.set(n.item_id,r)}for(let[n,r]of t)await Gt(n,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:r.map(o=>({receipt_id:o.receipt_id,original_history_line:o.history_line,original_event_ts:o.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function cP(e){try{return{status:"fulfilled",value:await Gt(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function lP(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function dP(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>$i(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}function mP(e,t){if(!(e===0||t))return'If receipt proof is unavailable or competing values were discarded, first review receipts.summaries and repair.streams and re-apply intended values. Only with explicit authority to accept that review, run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>". This appends an audit event; it does not restore missing evidence or discarded values.'}async function hw(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await Tr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=_w(o),a=await aP(r,i.coordinates),s=await Ii(r),c=s??r,m=await E_(c,{includeLossless:!0,pmRoot:r});if(m.invalid_evidence_count>0)throw new l(`Merge reconciliation refused ${m.invalid_evidence_count} invalid receipt evidence file(s).`,d.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let p=await sP({candidates:a,options:e,global:t}),u=m.receipts,f=await fw({cwd:s,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),_=new Set(f),h=new Map;for(let K of u.filter(ae=>!_.has(ae.id))){let ae=h.get(K.item_id)??[];ae.push(K),h.set(K.item_id,ae)}let g=Object.fromEntries([...h].map(([K,ae])=>[K,{merge:{receipts:ae.map(tn)}}])),y=Object.fromEntries([...h].map(([K,ae])=>[K,{gitWorkspaceRoot:s,receipts:ae}])),w=await Mi({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:g,...u.length>0?{mergeReceiptProofById:y}:{}},t),b=new Set(w.streams.map(K=>K.id)),S=[...h.keys()].filter(K=>!b.has(K)),T=await Xf(S,iP,K=>cP({id:K,dryRun:n,options:e,global:t,auditContext:g[K],mergeReceiptProof:y[K]}));lP({receiptOnlyIds:S,results:T,repair:w});let $=await dP({dryRun:n,pendingReceipts:u,repair:w,receiptWorkspaceRoot:c}),P=await ji({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),L=p===0?o:await Tr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),q=_w(L),H=P.checks.every(K=>K.status==="ok"),J=n?u.length===0:$+f.length===u.length,ie=[w.totals.failed===0,H,J,q.count===0,!q.truncated].every(Boolean),me=i.truncated||q.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,$e=mP(u.length,ie),Be=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",me,$e,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:ie?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.",me,$e,...a.length>0&&p===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(K=>K!==void 0);return{ok:ie,dry_run:n,repair:w,receipts:{pending_before:u.length,reconciled:$,abandoned:f.length,summaries:u.map(tn),missing_history_references_before:i.count,legacy_disposition_eligible:a.length,legacy_disposition_recorded:p,missing_history_references_after:q.count},validation:P,guidance:Be,generated_at:P.generated_at}}import{createHash as pP}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3483e997-6bee-52bf-a048-8fe5c2427d06")}catch{}})();var ww=1,vw=/^[A-Za-z0-9_-]+$/,uP=100,gw=1e3;var sB=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function tt(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function fP(e){return pP("sha256").update(Yt({type:tt(e.type),author:tt(e.author),item:tt(e.item),harness:tt(e.harness),agent_instance:tt(e.agentInstance),provenance:tt(e.provenanceFilter)})).digest("hex").slice(0,24)}function yw(e,t){let n={version:ww,fingerprint:t,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function _P(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===ww,n.fingerprint===t,typeof n.ts=="string",typeof n.stream_id=="string",typeof n.stream_offset=="number",Number.isSafeInteger(n.stream_offset),Number(n.stream_offset)>=0].every(Boolean)}function hP(e,t){let n=e.trim();if(n.length===0||n.length>4096||!vw.test(n))throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"})}if(!_P(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function gP(e){let t=e??uP;if(!Number.isSafeInteger(t)||t<0||t>gw)throw new l(`Mutation event limit must be an integer from 0 to ${gw}.`,d.USAGE,{code:"invalid_event_limit"});return t}function yP(e,t){let n=e?.trim();if(!n)return{};if(vw.test(n))return{cursor:hP(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new l("Mutation event --since must be an event cursor or ISO timestamp.",d.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function wP(e,t){let n=await Xs(e,t);if(n===null){if(!await Uu(e))return{...await Gu(e,t),source:"authoritative_history"};n=await Xs(e,t)}if(n===null)throw new l("Mutation event index could not be opened after rebuild.",d.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function vP(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Ma(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=gP(e.limit),r=vP(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new l("Mutation event projections are mutually exclusive. Use --provenance or --full.",d.USAGE);let o=await A(t),i=o.agent_identity.identity_vocabulary,a=W_(o.agent_identity.harness_signals),s=Y_({provenance:e.provenanceFilter},a),c=tt(e.harness),m=fP(e),{cursor:p,sinceTimestamp:u}=yP(e.since,m),f={...p?{after_ts:p.ts,after_stream_id:p.stream_id,after_stream_offset:p.stream_offset}:u?{since_ts:u}:{},ops:tt(e.type),authors:tt(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,g])=>c.includes(g)).map(([g])=>g):void 0,agent_instances:tt(e.agentInstance),provenance:[...s].map(([g,y])=>({dimension:g,values:[...y]})),stream_ids:tt(e.item),limit:n},_=await wP(t,f),h=_.events.map(g=>({...r==="row"?{cursor:yw(g,m)}:{},item_id:g.stream_id,version:g.stream_offset+1,ts:g.entry.ts,author:g.entry.author,type:g.entry.op,...g.entry.message===void 0?{}:{message:g.entry.message},patch_count:g.entry.patch.length,...e.full===!0?{entry:g.entry}:{},...e.provenance===!0?{provenance:J_(g.entry,i,{itemId:g.stream_id,version:g.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:yw(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:X_(_.events.map(g=>g.entry),i,a)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="015a3a52-f631-5ab7-b5c5-10a54a0b750c")}catch{}})();var bP="1h",kP="now",SP="+1d";function Kt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function bw(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return Oe(n,r)}async function kw(e,t,n,r){let o=bw(e,t,n),i=[];return Kt(i,"start",n.start??kP),n.end!==void 0?Kt(i,"end",n.end):Kt(i,"duration",n.duration??bP),Kt(i,"location",n.location),Kt(i,"timezone",n.timezone),n.allDay===!0&&Kt(i,"all_day","true"),o.event=[i.join(",")],jt(o,r)}function Sw(e,t,n){return kw("Meeting",e,t,n)}function Ew(e,t,n){return kw("Event",e,t,n)}function Aw(e,t,n){let r=bw("Reminder",e,t),o=[];return Kt(o,"at",t.at??SP),Kt(o,"text",t.text??e),r.reminder=[o.join(",")],jt(r,n)}import Br from"node:crypto";import{cp as Tw,lstat as EP,mkdir as gn,readFile as Xn,readdir as Jl,rename as Rw,rm as Ql,writeFile as Da}from"node:fs/promises";import M from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3b4a5521-a665-5f60-8d01-16033b078916")}catch{}})();var Ow="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var xw=M.join("runtime","workspace-snapshots"),AP=new Set(["checkpoints","locks","runtime","search","transactions"]),TP=/^[a-z0-9][a-z0-9._-]*$/,Hr="sdk-workspace-transaction",Yl={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Pw={renameEntry:Rw,removeEntry:async e=>{await Ql(e,{recursive:!0,force:!0})}},Xl=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await Xn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==Hr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await te(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
24
+ `)}};async function Nw(e,t=""){let n=await Jl(M.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((i,a)=>i.name.localeCompare(a.name))){if(t.length===0&&AP.has(o.name))continue;let i=M.posix.join(t.replaceAll(M.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${i}`);if(o.isDirectory())r.push(...await Nw(e,i));else if(o.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function Lw(e){let t=await Nw(e),n=Br.createHash("sha256"),r=[],o=0;for(let a of t){let s=await Xn(M.join(e,a));r.push(s),o+=s.byteLength,n.update(a),n.update("\0"),n.update(String(s.byteLength)),n.update("\0"),n.update(s)}let i=n.digest("hex");return{manifest:{schema:Ow,fingerprint:i,files:t,bytes:o},contents:r}}function Cw(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
25
+ `).filter(t=>t.trim().length>0).length}async function CP(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),i=await Promise.all(o.map(async a=>[a,await Xn(M.join(e,a))]));for(let[a,s]of i)n.set(a,s)}return n}function Zl(e){if(!TP.test(e))throw new l("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",d.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function $w(e,t){return ir(`workspace_snapshot_${e}`,t,{codes:{capacity:Yl.capacity.code,permission:Yl.permission.code,resource:Yl.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function yn(e){return M.join(e,xw)}function Fw(e){return new l(`Unknown workspace snapshot: ${e}`,d.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Mw(e,t){try{return JSON.parse(await Xn(e,"utf8"))}catch(n){throw Ve(n)?Fw(t):n}}async function Iw(e,t,n){try{await Ql(e,{recursive:n})}catch(r){throw Ve(r)?Fw(t):r}}async function IP(e,t,n=Pw){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function RP(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(i){throw await r.renameEntry(n,t),await r.removeEntry(e),i}await r.removeEntry(n)}async function OP(e,t){return Zl(t),/^[a-f0-9]{64}$/.test(t)?t:(await Mw(M.join(yn(e),"refs",`${t}.json`),t)).fingerprint}async function ed(e,t={}){if(t.name!==void 0&&(Zl(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new l("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",d.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await Lw(e),o=yn(e),i=M.join(o,"objects",n.fingerprint),a=!1;try{a=(await EP(i)).isDirectory()}catch(s){if(!(s instanceof Error&&"code"in s&&Ve(s)))throw s}if(!a){let s=M.join(o,"objects",`.create-${process.pid}-${Br.randomUUID()}`);await $w("create_object",async()=>{await gn(M.join(s,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let p=M.join(s,"files",m);await gn(M.dirname(p),{recursive:!0}),await Da(p,r[c])}await Da(M.join(s,"manifest.json"),`${JSON.stringify(n,null,2)}
26
+ `,"utf8"),await gn(M.dirname(i),{recursive:!0})}),a=await IP(s,i)}if(t.name!==void 0){let s={name:t.name,fingerprint:n.fingerprint},c=M.join(o,"refs");await gn(c,{recursive:!0});let m=M.join(c,`.ref-${process.pid}-${Br.randomUUID()}`);await Da(m,`${JSON.stringify(s,null,2)}
27
+ `,"utf8"),await Rw(m,M.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:a}}async function Vr(e,t){let n=await OP(e,t),r=await Mw(M.join(yn(e),"objects",n,"manifest.json"),t);if(r.schema!==Ow||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,d.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function td(e){let t=yn(e),n=await Jl(M.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&Ve(o))return[];throw o}),r=await Jl(M.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&Ve(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Vr(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await Xn(M.join(t,"refs",o),"utf8"))))}}async function nd(e,t){let n=await Vr(e,t),{manifest:r,contents:o}=await Lw(e),i=new Map(r.files.map((u,f)=>[u,o[f]])),a=await CP(M.join(yn(e),"objects",n.fingerprint,"files"),n.files),s=new Set(r.files),c=new Set(n.files),m=new Set([...s,...c]);for(let u of m){let f=i.get(u),_=a.get(u);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(u)}let p=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let f=Cw(i.get(u)),_=Cw(a.get(u));return{path:u,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(u=>u.removed_entries>0).sort((u,f)=>u.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:m.size,removed_file_count:[...s].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!s.has(u)).length,removed_item_count:[...s].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:p.length,removed_history_entry_count:p.reduce((u,f)=>u+f.removed_entries,0),affected_history_streams:p,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function Dw(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",d.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",o=n.lockTtlSeconds??60,i=n.lockWaitMs??5e3,a=await Ie(e,Hr,o,r,!1,!1,i),s=new Xl(fo(e,Hr),r,o);s.start(),await s.refreshNow();let c,m=!1,p=!1;try{let u=await nd(e,t),f=await Vr(e,t),_=await ed(e),h=f.fingerprint,g=yn(e),y=M.join(g,"objects",h,"files"),w=M.dirname(e),b=M.basename(e);c=M.join(w,`.${b}.restore-${Br.randomUUID()}`);let S=M.join(w,`.${b}.backup-${Br.randomUUID()}`);await $w("restore_stage",async()=>{await gn(c,{recursive:!0}),await Tw(y,c,{recursive:!0,force:!1}),await gn(M.join(c,"runtime"),{recursive:!0}),await Tw(g,M.join(c,xw),{recursive:!0,force:!1})});let T=await Wu({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:u.changed_file_count,removed_file_count:u.removed_file_count,removed_item_count:u.removed_item_count,affected_history_stream_count:u.affected_history_stream_count,removed_history_entry_count:u.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:i}),$=M.relative(c,T.historyPath).replaceAll("\\","/");await s.stop(),p=!0;let P=fo(c,Hr);return await gn(M.dirname(P),{recursive:!0}),await Da(P,await Xn(fo(e,Hr)),{flag:"wx"}),m=!0,await RP(c,e,S,Pw,async()=>{s.start(),p=!1,await s.refreshNow()}),await s.stop(),p=!0,{manifest:f,plan:u,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:$,audit_operation:"workspace_snapshot_restore"}}catch(u){throw c!==void 0&&!m&&await Promise.allSettled([Ql(c,{recursive:!0,force:!0})]),u}finally{try{p||await s.stop()}catch{}finally{await a()}}}async function Uw(e,t){Zl(t);let n=yn(e);if(!/^[a-f0-9]{64}$/.test(t))return await Iw(M.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await td(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Iw(M.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01f25e4f-09a1-554f-9e0b-a999fcce5c55")}catch{}})();function Wr(e){let t={...e.args,...e.options};return Oe(e.options,t)}function Et(e,t){let n=v(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Qn(e){return typeof e=="string"?[e]:ye(e)}function Gw(e){return mw(Wr(e),e.global)}function jw(e){let t=Wr(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Ma({cwd:v(t,"cwd"),pmRoot:v(t,"path"),since:v(t,"since"),type:Qn(t.type),author:Qn(t.author),item:Qn(t.item),limit:t.limit===void 0?void 0:De(t.limit,"limit"),full:t.full===!0,cursorMode:r,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Qn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Qn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Qn(t.provenanceFilter)}})}function qw(e){let t=Wr(e),n=Et(t,"subcommand");if(n==="install")return Pf({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return hw({dryRun:t.dryRun===!0,author:v(t,"author"),message:v(t,"message"),force:t.force===!0},e.global);if(n==="report")return A_({includeReconciled:t.includeReconciled===!0,cwd:v(t,"cwd")});if(n==="driver")return uw({artifact:Et(t,"artifact"),basePath:Et(t,"basePath"),oursPath:Et(t,"oursPath"),theirsPath:Et(t,"theirsPath"),outputPath:v(t,"outputPath")??v(t,"output"),itemPath:v(t,"itemPath"),prefer:v(t,"prefer")},e.global);throw Re({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Kw(e){let t=Wr(e),n=Et(t,"subcommand");if(n==="position")return rh(e.global);if(n!=="snapshot")throw Re({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=v(t,"snapshotAction")??Et(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return ed(o,{name:v(t,"name")});if(r==="list")return td(o);let i=Et(t,"target");if(r==="inspect")return Vr(o,i);if(r==="delete")return Uw(o,i);if(r==="restore")return t.dryRun===!0?nd(o,i):Dw(o,i,{force:t.force===!0,author:v(t,"author"),message:v(t,"message"),lockTtlSeconds:De(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:De(t.lockWaitMs,"lockWaitMs")});throw Re({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Ua(e){let t=Wr(e),n=Et(t,"title");return e.action==="meet"?Sw(n,t,e.global):e.action==="event"?Ew(n,t,e.global):Aw(n,t,e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27bbfaed-a594-5b3b-84ba-431be02e002e")}catch{}})();function zw(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:v(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ye(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:v(e,"measurementSource"),measurementItem:v(e,"measurementItem"),measurementRevision:v(e,"measurementRevision"),author:v(e,"author"),message:v(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:v(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import uN from"node:fs/promises";import cv from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function Ga(e,t,n,r,o,i="min"){let a=o==="min"?e-t:t-e,s=i==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return a<0||a===0&&r!==null&&s<0}function xP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,i=null,a=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let p;try{p=JSON.parse(m)}catch{continue}if(p===null||typeof p!="object"||!("ts"in p)||typeof p.ts!="string")continue;let u=p.ts,f=Date.parse(u);Number.isNaN(f)||(Ga(f,a,u,o,"min")&&(a=f,o=u),Ga(f,s,u,i,"max","max")&&(s=f,i=u))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:i}}function Hw(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:h})=>xP(_,h)),i=0,a=0,s=null,c=null,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY;for(let _ of o){if(i+=_.lines,a+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);Ga(h,m,_.id,s?.id??null,"min")&&(m=h,s={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);Ga(h,p,_.id,c?.id??null,"max")&&(p=h,c={id:_.id,ts:_.newest_ts})}}let u=r===0?[]:[...o].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...o].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:i,total_bytes:a,largest_by_bytes:u,deepest_by_lines:f,oldest_entry:s,newest_entry:c}}import{createHash as NP}from"node:crypto";import{execFile as LP}from"node:child_process";import Ww from"node:path";import{promisify as $P}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed03b6c8-6275-55a6-8e5f-4f27a23d6696")}catch{}})();var Bw=1;function PP(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function rd(e){if(e===null)return{format_version:Bw,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Bw||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!PP(r))throw new l("Improvement ledger contains an invalid observation.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7ad59ce-5111-5649-9025-340183539b4a")}catch{}})();var FP=$P(LP),MP=50,Vw=1e3,DP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Yw(e){let t=e.trim().toLowerCase();if(!DP.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function UP(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function Yr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return n}}function GP(e){let t=e??MP;if(!Number.isSafeInteger(t)||t<0||t>Vw)throw new l(`Improvement observation limit must be an integer from 0 to ${Vw}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Jw(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function jP(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});let r=Yw(n.metric),o=UP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let i=await KP(e,n.revision),a=Yr(n.source,"source"),s=Yr(n.itemId,"itemId"),c=Yr(n.unit,"unit"),m=Yr(n.idempotencyKey,"idempotencyKey")??(i.revision_source==="unversioned"?void 0:[i.revision,r,a??"manual",s??"workspace"].join(":")),p={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Jw(n.observedAt??k(),"observedAt"),...i,author:C(n.author,t.author_default),...s===void 0?{}:{item_id:s},...a===void 0?{}:{source:a},...m===void 0?{}:{idempotency_key:m}};return{id:NP("sha256").update(Yt(p)).digest("hex").slice(0,24),...p}}function qP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function KP(e,t){let n=Yr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await FP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:cm(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function zP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function Xw(e,t={}){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await jP(n,r,e),i=Ww.join(n,"improvement-ledger.json"),a=await ai({pmRoot:n,filePath:i,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:s=>{let c=rd(s),m=qP(c,o);return m?{raw:s,result:m}:(c.observations.push(o),c.observations.sort((p,u)=>p.observed_at.localeCompare(u.observed_at)||p.metric.localeCompare(u.metric)||p.id.localeCompare(u.id)),{raw:`${Yt(c)}
28
+ `,result:o})}});return{changed:a.changed,observation:a.result,ledger_path:"improvement-ledger.json"}}async function Qw(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=e.metric===void 0?void 0:Yw(e.metric),r=e.since===void 0?void 0:Jw(e.since,"since"),o=GP(e.limit),i=rd(await X(Ww.join(t,"improvement-ledger.json"))).observations.filter(s=>(n===void 0||s.metric===n)&&(e.itemId===void 0||s.item_id===e.itemId)&&(r===void 0||s.observed_at>=r)),a=new Map;for(let s of i){let c=a.get(s.metric)??[];c.push(s),a.set(s.metric,c)}return{observations:[...i].reverse().slice(0,o),total:i.length,truncated:i.length>o,trends:[...a].map(([,s])=>zP(s)).sort((s,c)=>s.metric.localeCompare(c.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function Zw(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function HP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function BP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function od(e=ur,t=On){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function VP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function id(e,t=On,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let i of t){let a=`${o.agent_harness}\0${i}`,s=r.get(a)??{harness:o.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1;let c=o.agent_provenance?.[i];c!=null&&c.value.length>0?s.observed+=1:c===null?s.unavailable+=1:s.legacy_missing+=1,r.set(a,s)}return[...r.values()].map(o=>{let i=o.observed+o.unavailable;return{...o,coverage:i===0?null:o.observed/i,inert:i>=n&&o.observed===0}}).sort((o,i)=>o.harness.localeCompare(i.harness)||o.dimension.localeCompare(i.dimension))}function WP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let p=`${c.agent_harness}\0${m}`,u=o.get(p)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(u.observed+=1,u.by_source[f.source]=(u.by_source[f.source]??0)+1),o.set(p,u)}let i=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[p])=>m.localeCompare(p)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),a=i.filter(c=>c.entries>=r),s=a.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:a.length>0&&s.length===0,minimum_coverage:n,minimum_entries:r,rows:i,failures:s}}function YP(e){let t=[...e].sort((i,a)=>i.ts.localeCompare(a.ts)||i.author.localeCompare(a.author)||i.op.localeCompare(a.op)||i.before_hash.localeCompare(a.before_hash)||i.after_hash.localeCompare(a.after_hash)),n=new Map,r=new Map;for(let i of t){let a=i.agent_episode,s=Zw(i),c=`${s.source}:${s.id}`,m=n.get(c);if(m){m.entries.push(i);continue}let p={id:s.id,...a?.label===void 0?{}:{label:a.label},...a?.parent_id===void 0?{}:{parent_id:a.parent_id},source:s.source,entries:[i],children:[]};n.set(c,p),a!==void 0&&r.set(s.id,p)}let o=[];for(let i of n.values()){let a=i.parent_id?r.get(i.parent_id):void 0;a&&HP(i,a,r)?a.children.push(i):o.push(i)}return BP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();var JP=1e4,ev=1e5,XP=1e3,QP=30,ZP=["append","comment","docs","file","learning","note","test_run"];function eN(e){let t=e??JP;if(!Number.isSafeInteger(t)||t<1||t>ev)throw new l(`History analytics event limit must be an integer from 1 to ${ev}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function tv(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",d.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function tN(e){let t=e?.trim();if(!t)return new Date(Date.now()-QP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),i=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*i).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function nv(e,t){let n=eN(t.eventLimit),r=tN(t.since),o=[],i=r,a=!1;for(;o.length<n;){let s=await Ma({pmRoot:e,since:i,limit:Math.min(XP,n-o.length),full:!0}),c=s.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),a=s.has_more,i=s.next_cursor,!s.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:a,...a?{next_cursor:i}:{},source:"history_event_index"}}}function nN(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function rN(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function oN(e){return ZP.some(t=>e.startsWith(t))}function rv(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function iN(e,t,n){let r=new Map,o=new Map,i=new Map;for(let a of t){let s=nN(a.entry,e),c=rN(a.entry),m=o.get(a.item_id)===!0,p=c===void 0?m:n.has(c);if(c!==void 0&&o.set(a.item_id,p),!s)continue;let u=rv(r,s);u.events+=1,oN(a.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!m&&p?(u.closes+=1,i.set(a.item_id,s)):c!==void 0&&m&&!p&&(u.reopens+=1)}return{buckets:r,lastCloseValue:i}}function aN(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(i=>i.kind==="discovered_from").map(i=>i.id));for(let i of o){let a=t.get(i);a&&(rv(e,a).defectEscapes+=1)}}}function sN(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function cN(e,t,n,r,o,i){let{buckets:a,lastCloseValue:s}=iN(e,t,r);return aN(a,s,n),{dimension:e,status:a.size===0?"unavailable":"available",rows:[...a].map(([c,m])=>sN(c,m,o,i)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function lN(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),i=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(i)?1:Math.max(1,(i-o)/864e5)}function dN(e,t,n){let r=od(t),o=id(e,On,n),i=o.filter(s=>s.inert).map(s=>({harness:s.harness,dimension:s.dimension,explicit_samples:s.observed+s.unavailable})),a=r.filter(s=>!s.covered).map(s=>s.dimension);return{descriptors:r,observations:o,inert:i,undeclared:a,warnings:[...i.map(s=>`provenance_dimension_inert:${s.harness}:${s.dimension}:${String(s.explicit_samples)}`),...a.map(s=>`provenance_dimension_undeclared:${s}`)]}}function ov(e,t=ur,n={}){let r=tv(n.minimumSample);return{...dN(e.events.map(o=>o.entry),t,r),window:e.receipt}}function iv(e,t,n,r={}){let o=tv(r.minimumSample),i=lN(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(a=>cN(a,e.events,t,n,o,i)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3e70310d-fc4f-5ea9-b9fb-7c519035301b")}catch{}})();var mN=32;function pN(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let i=o.slice(0,o.indexOf("=")).trim();r.length>0&&i!=="unit"&&i!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Jr(e,t){let n=pN(e).map(r=>{let[o,...i]=r.split(","),a=o.indexOf("="),s=o.slice(0,a).trim(),c=o.slice(a+1).trim(),m=Number(c);if(a<=0||s.length===0||c.length===0||!Number.isFinite(m))throw new l(`Invalid --measure "${r}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,u;for(let f of i){let _=f.indexOf("="),h=f.slice(0,_).trim(),g=f.slice(_+1).trim();if(h==="unit"&&g.length>0)p=g;else if(h==="threshold"&&g.length>0&&Number.isFinite(Number(g)))u=Number(g);else throw new l(`Invalid --measure attribute "${f}"`,d.USAGE)}return{name:s,value:m,unit:p,threshold:u,recorded_at:t}});return[...new Map(n.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,mN)}function av(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function sv(e,t){let n=e.flatMap(i=>i.measurements??[]).filter(i=>i.name===t).sort((i,a)=>a.recorded_at.localeCompare(i.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9d089ef-bca9-547f-a860-4002ec181cd0")}catch{}})();function fN(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function _N(e,t,n,r,o){let i=vr(e,"type",r),a=new Set(i.rows.map(u=>u.key)),s=t.filter(u=>!a.has(u)),c=(o?[...i.rows,...s.map(u=>({label:u,key:u,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:i.rows).map(u=>({type:u.key??u.label,total:u.total,open:u.buckets.open,in_progress:u.buckets.in_progress,blocked:u.buckets.blocked,draft:u.buckets.draft,closed:u.buckets.closed,canceled:u.buckets.canceled,other:u.buckets.other})),m=fN([...n]);for(let u of e)m[u.status]+=1;let p=Object.fromEntries(Object.entries(m).filter(([,u])=>o||u>0));return{byType:c,byStatus:p,omitted:o?0:s.length+Object.values(m).filter(u=>u===0).length}}function hN(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function gN(e){let t=cv.join(e,"history");if(!await j(t))return[];await In({path:t,scope:"project"});let n=(await uN.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,i)=>o.localeCompare(i)),r=[];for(let o of n){let i=cv.join(t,o),a=await X(i);a!==null&&(await In({path:i,scope:"project"}),r.push({id:o.slice(0,-6),raw:a}))}return r}async function yN(e,t){let n=[],r=k();for(let o of Jr(t.observe,r))n.push(await Xw({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function wN(e,t,n){let r={};return t.byAssignee&&(r.assignee=vr(e,"assignee",n)),t.byTag&&(r.tag=vr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=vr(e,"priority",n)),r}async function vN(e,t,n,r,o){let i={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},a=o.provenanceCoverage||o.fleetAttribution?await nv(e,i):void 0;return{provenanceCoverage:o.provenanceCoverage&&a?ov(a,n.agent_identity?.harness_signals,i):void 0,fleetAttribution:o.fleetAttribution&&a?iv(a,t,r,i):void 0}}function bN(e,t,n,r,o){let i=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...i?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:k()}}async function ad(e,t={}){let n=E(process.cwd(),e.path);await I(n);let r=await A(n),o=await yN(e,t),i=x(r,R()),a=F(r.schema),s=t.fieldUtilization?await uf(n,r.item_format,i.type_to_folder,void 0,r.schema):await _e(n,r.item_format,i.type_to_folder,void 0,r.schema);await of({pmRoot:n,settings:r,itemIds:s.map(S=>S.id),commandLabel:"stats"});let c=Ei(a),m=_N(s,i.types,a.definitions.map(S=>S.id),c,t.includeEmpty===!0),p=await gN(n),u=0;for(let S of p)u+=hN(S.raw);let f=t.storage?Hw(p):void 0,_=t.metadataCoverage?vf(s,c):void 0,h=wN(s,t,c),g=t.fieldUtilization?bf(s):void 0,y=t.measurements===!0||o.length>0?await Qw({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:b}=await vN(n,s,r,a.terminal_statuses,t);return bN({items:s.length,history_streams:p.length,history_entries:u},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:g,improvementLedger:y,recordedObservations:o,provenanceCoverage:w,fleetAttribution:b})}import kN from"node:fs/promises";import zt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a41eaff2-6a15-5e82-b3aa-03ca48fc3eb5")}catch{}})();var fv=zt.join("runtime","telemetry","events.jsonl"),_v=zt.join("runtime","telemetry","state.json"),SN=zt.join("runtime","telemetry"),EN=20,hv=Jt.filter(e=>e.lifecycle==="deprecated"),lv=["status","flush","stats","clear"],dv=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},sd=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,mv=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},AN=e=>({command:sd(e.event.command,"<unknown>"),eventType:sd(e.event.event_type,"unknown"),eventSchemaVersion:mv(e.event.schema_version),clientSchemaVersion:mv(e.client_schema_version)}),TN=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),CN=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},IN=e=>{let t=e?.command_resolution;return sd(t,"")||void 0},gv=(e,t)=>{e[t]=(e[t]??0)+1},RN=(e,t)=>{let n=CN(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=IN(t);r!==void 0&&gv(e.resolution_counts,r)},ON=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,pv=(e,t)=>{t!==void 0&&e.add(t)},xN=(e,t)=>{let n=AN(t),r=e.get(n.command)??TN();r.count+=1,r.max_attempts=Math.max(r.max_attempts,ON(t.attempts)),gv(r.event_type_counts,n.eventType),pv(r.event_schema_versions,n.eventSchemaVersion),pv(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&RN(r,t.event.payload),e.set(n.command,r)},PN=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((i,a)=>i-a),o=Object.entries(t.resolution_counts).sort((i,a)=>i[0].localeCompare(a[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((i,a)=>i[0].localeCompare(a[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((i,a)=>i-a),client_schema_versions:[...t.client_schema_versions].sort((i,a)=>i-a),...r.length>0?{duration_p50_ms:dv(r,.5),duration_p95_ms:dv(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},NN=e=>{let t=(e??"status").trim().toLowerCase();if(lv.includes(t))return t;throw Re({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:lv,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},ld=()=>{throw new l("--limit must be a positive integer",d.USAGE)},yv=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?ld():e,LN=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?ld():yv(Number.parseInt(t,10))},$N=e=>e===void 0?EN:typeof e=="number"?yv(e):typeof e=="string"?LN(e):ld(),FN=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},MN=e=>{try{let t=JSON.parse(e);return FN(t)?t:void 0}catch{return}},DN=e=>e===null?[]:e.split(`
29
+ `).map(t=>t.trim()).filter(t=>t.length>0),wv=e=>{let t=DN(e),n=[],r=0;for(let o of t){let i=MN(o);i===void 0?r+=1:n.push(i)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},UN=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),GN=e=>{try{let t=JSON.parse(e);return UN(t)?t:{}}catch{return{}}},cd=async e=>{let t=await X(e);return t===null||t.trim().length===0?{}:GN(t)};function jN(e){let t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-Math.max(1,Math.trunc(e))+1)).toISOString().slice(0,10)}function qN(e,t,n){let r=Object.create(null);for(let[o,i]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(o)||o<t||o>n||typeof i!="object"||i===null||Array.isArray(i))continue;let a=i;!Number.isSafeInteger(a.count)||a.count<1||typeof a.last_seen!="string"||!a.last_seen.startsWith(o)||(r[o]={count:a.count,last_seen:a.last_seen})}return r}function uv(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,o=new Date().toISOString().slice(0,10);for(let i of hv){let a=r[i.alias];if(typeof a!="object"||a===null||Array.isArray(a))continue;let s=a;if(s.canonical!==i.canonical||typeof s.days!="object"||s.days===null||Array.isArray(s.days))continue;let c=qN(s.days,t,o);Object.keys(c).length>0&&(n[i.alias]={canonical:i.canonical,days:c})}return n}async function KN(e,t,n){let r=jN(n),o=await cd(t),i=uv(o.alias_usage,r);if(JSON.stringify(o.alias_usage??{})===JSON.stringify(i))return i;try{await lc(async()=>{let a=await cd(t);if(a.alias_usage===void 0)return;let s=uv(a.alias_usage,r);JSON.stringify(a.alias_usage)!==JSON.stringify(s)&&await te(t,`${JSON.stringify({...a,alias_usage:s},null,2)}
30
+ `)},e,250)}catch{}return i}var ja=e=>e??null,qa=async e=>{let t=await A(e),n=zt.join(e,fv),r=zt.join(e,_v),o=await X(n),i=wv(o),a=await cd(r),s=_f();return{enabled:t.telemetry.enabled&&!s.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:s,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:i.rows_total,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:ja(a.last_attempted_flush_at),last_successful_flush_at:ja(a.last_successful_flush_at),last_failed_flush_at:ja(a.last_failed_flush_at),last_failed_flush_error:ja(a.last_failed_flush_error)}},zN=e=>{let t=new Map;for(let n of e)xN(t,n);return[...t.entries()].map(([n,r])=>PN(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},HN=async(e,t)=>({action:"telemetry",subcommand:"status",status:await qa(t.globalPmRoot),generated_at:k()}),BN=async(e,t)=>{let n=await qa(t.globalPmRoot);await yf(t.globalPmRoot);let r=await qa(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),i=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:i,queue_drained:i,status:r,generated_at:k()}},VN=async(e,t)=>{let n=$N(e.limit),r=await X(t.queuePath),o=wv(r),i=zN(o.entries),a=i.slice(0,n),s=await A(t.globalPmRoot),c=await KN(t.globalPmRoot,t.statePath,s.telemetry.retention_days),m=Object.entries(c).map(([p,u])=>{let f=Object.values(u.days);return{alias:p,canonical:u.canonical,count:f.reduce((_,h)=>Math.min(Number.MAX_SAFE_INTEGER,_+h.count),0),last_seen:f.map(_=>_.last_seen).sort().at(-1)}}).sort((p,u)=>u.count-p.count||p.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:i.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:i.length>a.length,stats:a,alias_usage:m,zero_use_aliases:hv.map(p=>p.alias).filter(p=>c[p]===void 0),alias_usage_retention_days:s.telemetry.retention_days,generated_at:k()}},WN=async(e,t)=>lc(async()=>{let n=await A(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await Me(t.globalPmRoot,n,"telemetry:clear");let o=zt.join(t.globalPmRoot,SN),i=await j(o);return await kN.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:i&&!await j(o),queue_exists_after:await j(t.queuePath),state_exists_after:await j(t.statePath),status:await qa(t.globalPmRoot),generated_at:k()}},t.globalPmRoot),YN={status:HN,flush:BN,stats:VN,clear:WN};async function vv(e,t){let n=NN(e.subcommand),r=mt(process.cwd());return YN[n](e,{globalPmRoot:r,queuePath:zt.join(r,fv),statePath:zt.join(r,_v)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b74444c7-c283-52b2-b65f-b0a086ff2b53")}catch{}})();var bv=20;function JN(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return bv;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?bv:t}function dd(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let i=Qo(r.recorded_at,o.recorded_at);if(i!==0)return i;let a=r.run_id.localeCompare(o.run_id);return a!==0?a:r.kind.localeCompare(o.kind)}),n=JN();return t.length>n?t.slice(t.length-n):t}async function Ka(e){await le({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=dd([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="92f73d30-eac7-5c84-a7be-133323d1f549")}catch{}})();function kv(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(o))return[];t.push(o);continue}t.push(r)}return t}function md(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=kv(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let i of r){if(typeof o!="object"||o===null)return{found:!1,value:void 0};if(typeof i=="number"&&(!Array.isArray(o)||i>=o.length))return{found:!1,value:void 0};let a=Object.getOwnPropertyDescriptor(o,i);if(!a||!Object.hasOwn(a,"value"))return{found:!1,value:void 0};o=a.value}return{found:!0,value:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8316bbdc-b0f7-59b2-8875-1e0ad77eb8c0")}catch{}})();var XN=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],QN=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function za(e,t){let n=`${e}
31
+ ${t}`;for(let r of XN)if(r.regex.test(n))return{code:r.code};return null}function Sv(e,t){for(let[n,r]of[["stdout",e],["stderr",t]]){let o=QN.find(i=>i.regex.test(r));if(o)return{code:o.receiptCode,stream:n}}}import{cp as ZN,lstat as eL,mkdir as tL,readlink as nL,realpath as ud,stat as rL,symlink as Ev}from"node:fs/promises";import{execFile as oL}from"node:child_process";import G from"node:path";import{promisify as iL}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="26cfff37-1b7e-556f-8656-2e5c7c9d616f")}catch{}})();var aL=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),Av=iL(oL);async function sL(e,t){let n=await Ha(G.join(e,".git"));if(!n||n.isDirectory()&&!await Ha(G.join(e,".git/HEAD")))return;let r=Object.fromEntries(Object.entries(process.env).filter(([o])=>!o.toUpperCase().startsWith("GIT_")));await Av("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:r,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await Av("git",["-C",t,"remote","remove","origin"],{env:r,timeout:1e4,windowsHide:!0})}function pd(e){return e.split(G.sep).some(t=>aL.has(t.toLowerCase()))}function Xr(e){return e===".."||e.startsWith(`..${G.sep}`)||G.isAbsolute(e)}async function Ha(e){try{return await rL(e)}catch(t){if(!Ve(t))throw t;return}}async function Ba(e){let t=[],n=e;for(;G.dirname(n)!==n;)try{return G.join(await ud(n),...t)}catch(r){if(!Ve(r))throw r;t.unshift(G.basename(n)),n=G.dirname(n)}return G.join(await ud(n),...t)}async function cL(e,t,n){let r=G.relative(t,await Ba(e));if(!Xr(r))return r;let o=[],i=e;for(;G.dirname(i)!==i;){let a=await Ba(i),s=n.find(([,c])=>c===a);if(s)return G.join(s[0],...o);o.unshift(G.basename(i)),i=G.dirname(i)}return r}async function Tv(e,t){let n=[],r=[],o=await ud(e),i=await Ba(G.resolve(t));if(![G.relative(o,i),G.relative(i,o)].every(Xr))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await tL(G.dirname(t),{recursive:!0}),await sL(o,t),await ZN(o,t,{recursive:!0,force:!0,async filter(a){let s=G.relative(o,a);if(!s)return!0;if(pd(s))return!1;if(G.basename(a).toLowerCase()==="node_modules"){if((await Ha(a))?.isDirectory()){let c=await Ba(a),m=G.relative(o,c);if(!Xr(G.relative(c,o))||!Xr(m)&&(pd(m)||!m.split(G.sep).some(p=>p.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${s}`);n.push([s,c])}return!1}return(await eL(a)).isSymbolicLink()?(r.push([s,G.resolve(G.dirname(a),await nL(a)),(await Ha(a))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[a]of n)await Ev(G.resolve(o,a),G.join(t,a),"junction");for(let[a,s,c]of r){let m=await cL(s,o,n);if(Xr(m)||pd(m))throw new Error(`Source symlink must target included workspace source: ${a}`);await Ev(G.resolve(t,m),G.join(t,a),c)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2661c74e-3e73-50f5-80a2-f103ff0cf2d4")}catch{}})();var Cv=100;function Zn(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,d.USAGE);return n}function lL(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=Cv?t:`${t.slice(0,Cv-3)}...`}function Iv(e){return e.map((t,n)=>`${n+1}. ${lL(t)}`).join("; ")}function dL(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function mL(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Rv(e,t){let n=dL(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,i)=>i+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,d.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,d.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let i=[],a=[];for(let s=0;s<e.length;s+=1)mL(e[s],o)&&(a.push(e[s]),i.push(s+1));if(a.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Iv(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:a,selected_indexes:i,selected_count:a.length,skipped_count:e.length-a.length}}if(r==="only-index"){let o=Zn(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${Iv(e)}`,d.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cfcc5f4f-caf0-5a2e-8a9d-219c3afb5d2d")}catch{}})();function Ov(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new l("Use exactly one --update or --update-index with --set-json",d.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new l("--set-json must contain a JSON object with explicit linked-test metadata fields",d.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:Zn(e.updateIndex,"--update-index")},patch:t};let n=e.update,r=/^(command|path)=/u.exec(n);return{selector:r?.[1]==="path"?{path:n.slice(r[0].length)}:{command:r?n.slice(r[0].length):n},patch:t}}function xv(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new l("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",d.USAGE)}function pL(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("Select one linked test by index, command, or path",d.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new l("Select one linked test by index, command, or path",d.USAGE);if("index"in t){let r=Zn(t.index,"--update-index");if(r<=e.length)return r-1}else{let r="command"in t?"command":"path",o="command"in t?t.command:t.path;if(typeof o!="string"||o.trim().length===0)throw new l("Linked-test selector must be a non-empty command or path",d.USAGE);let i=e.flatMap((a,s)=>a[r]===o?[s]:[]);if(i.length===1)return i[0];if(i.length>1)throw new l(`Linked-test selector is ambiguous; matching indexes: ${i.map(a=>a+1).join(", ")}`,d.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new l("No linked test matched the update selector",d.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function uL(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("Linked-test metadata patch must be a JSON object",d.USAGE);let n=Object.keys(t);if(n.length===0||n.some(s=>!wt.includes(s)||["command","cmd","timeout"].includes(s)))throw new l("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",d.USAGE);if(t.scope===null)throw new l("scope is required and cannot be cleared",d.USAGE);let r=Object.fromEntries(Object.entries(e).filter(([s])=>wt.includes(s))),o=$u(ya(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([s,c])=>[s,c===null?void 0:c]))}),"--set-json")[0]);U_(o);let i=n.filter(s=>!Se(e[s],o[s])),a={...e};for(let s of i){let c=o[s];Object.assign(a,{[s]:c}),c===void 0&&delete a[s]}if(!a.command?.trim()&&!a.path?.trim())throw new l("Linked-test entry must retain a command or path",d.USAGE);return{test:a,fields:i}}async function fd(e,t,n={}){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),i=C(t.author,o.author_default),a=x(o,R()),s=0,c=[],m=await Si({pmRoot:r,settings:o,id:e,author:i,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:a.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:s,fields:c}}),mutate(u){let f=u.metadata.tests??[],_=pL(f,t.selector),h=uL(f[_],t.patch);return s=_+1,c=h.fields,h.fields.length===0?{changedFields:[]}:(u.metadata.tests=f.map((g,y)=>y===_?{...h.test,updated_by:i,updated_at:k()}:g),{changedFields:["tests"]})}}),p=m.item.tests;return{ok:!0,id:m.item.id,tests:p,count:p.length,changed:m.changedFields.length>0,updated_index:s,updated_fields:c}}import{spawn as Wv}from"node:child_process";import{cp as Nv,mkdir as vd,mkdtemp as Yv,open as gd,readdir as yd,rm as Zr,symlink as fL}from"node:fs/promises";import{tmpdir as Jv}from"node:os";import oe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5aa7e990-08d9-56e4-860c-3fc52cebe728")}catch{}})();function Pv(e,t,n,r,o){if((t.measure?.length??0)===0||o.some(a=>typeof a.stdout=="string"&&a.failure_category!=="spawn_error"&&a.failure_category!=="empty_run"&&za(a.stdout,a.stderr??"")===null))return;let i=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[],"test",e,"--list","--json"];throw new l("--measure requires an executed linked test",d.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:Te(i),suggested_retry_args:i}})}function _d(e,t,n,r,o=!1){if((t.measure?.length??0)===0||t.run===!0)return;let i=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[]],a=[...i,...e_(e,t),...t.list?["--list"]:[],...o?["--background"]:[]],s=t.acknowledgeLinkedTests?[...i,"test",e,"--help"]:a,c=[...i,"test",e,"--acknowledge-linked-tests",...t.author?["--author",t.author]:[]];throw new l("--measure requires --run",d.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...t.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${Te([...i,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${Te(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${Te(a)}`]}:{},recovery:{missing:["--run"],suggested_retry:Te(s),suggested_retry_args:s}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54338522-5725-5511-be94-b047d2c82fdc")}catch{}})();var Ya=20*1024*1024,_L=3e3,hL=1e4,gL=5e3,Lv=120,yL=new Set(["locks","extensions","runtime"]),wL=new Set(["history","index","search","extensions","locks","runtime"]),vL=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],bL=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,kL=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,SL=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function bd(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function EL(){return bd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",_L)}function AL(){return bd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",hL)}function TL(){return bd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",gL)}function CL(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function IL(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"||o.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function kd(e){let t=0,n=0,r=0,o=0;for(let i of e){let a=i.execution_context;!a||a.is_pm_command!==!0||(t+=1,a.is_pm_tracker_read_command===!0&&(n+=1),a.mismatch_detected===!0&&(r+=1),a.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function RL(e){let t=e??"project";if(!dt.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function Xa(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(sn.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${sn.join(", ")}`,d.USAGE)}function OL(e){return ln(e??"source","--workspace-context")}function Xv(e,t,n){return n?t:ln(e.workspace_context_mode,"linked test")??t}function Qv(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Xa(e.pm_context_mode)}function Zv(e,t){return e==="auto"?t?"tracker":"schema":e}function xL(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function PL(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function NL(e,t){let n={};if(!e)return n;for(let r of e){let o=Mr(r,t);if(o)for(let[i,a]of Object.entries(o))n[i]=a}return n}function LL(e,t){if(!e)return[];let n=[];for(let r of e){let o=Dr(r,t);o&&n.push(...o)}return[...new Set(n)]}function $L(e){let t=Qa(e);return Cr(t).some(n=>yc(n)!==null)}function eb(e){let t=Qa(e);return Cr(t).some(n=>{let r=yc(n);if(!r)return!1;let o=D_(r);return o?SL.has(o.subcommand):!1})}function Va(e){if(e)return $_.has(e.subcommand)?qn(e.args,F_)?.subcommand:e.subcommand}function $v(e,t){if(e==="npx"||e==="bunx")return Ui(t)?.command;if(e==="pnpm")return Va(qn(t,x_));if(e==="npm")return Va(qn(t,P_));if(e==="yarn")return Va(qn(t,N_));if(e==="bun")return Va(qn(t,L_))}function Wa(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function hd(e){return!e||!vc(e.command)&&!M_(e.command)?!1:Di(e.args)==="test-all"}var tb=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),FL=new Set(["npx","bunx"]);function nb(e){let t=e.split(" ").filter(a=>a.length>0),n=wc(t);if(n.length===0)return!1;let[r,...o]=n,i=tb.get(r);if(i){let a=o.findIndex(s=>i.test(s));return a>=0?nb(o.slice(a+1).join(" ")):!1}return vc(r)||bc(r)?Di(o)==="test-all":r==="node"&&o.length>0&&bc(o[0])?Di(o.slice(1))==="test-all":FL.has(r)?hd(Ui(o)):r==="pnpm"?hd(kc(o)):r==="npm"?hd(Sc(o)):!1}function rb(e){let t=Qa(e);return Cr(t).some(n=>nb(n))}function ob(e){if(rb(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function Qa(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function ib(e){let t=e.split(" ").filter(a=>a.length>0),n=wc(t);if(n.length===0)return!1;let[r,...o]=n,i=tb.get(r);if(i){let a=o.findIndex(s=>i.test(s));return a>=0&&ib(o.slice(a+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?ML(o):DL(r,o)}function ML(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function DL(e,t){return e==="npx"||e==="bunx"?Wa(Ui(t)?.command):e==="pnpm"||e==="npm"?Wa((e==="pnpm"?kc(t):Sc(t))?.command)||Wa($v(e,t)):(e==="yarn"||e==="bun")&&Wa($v(e,t))}function UL(e){if(rb(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function GL(e){return e?e.map(jL):[]}function jL(e){let t=e.trim(),n=G_(t)?Gi(pe(e,"--add"),"--add"):{command:t},r=ge(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return ob(r),{command:r,path:ge(n.path),scope:RL(n.scope),timeout_seconds:qL(ge(n.timeout_seconds),ge(n.timeout)),pm_context_mode:ua(ge(n.pm_context_mode),"--add"),workspace_context_mode:ln(ge(n.workspace_context_mode),"--add"),env_set:Mr(ge(n.env_set),"--add"),env_clear:Dr(ge(n.env_clear),"--add"),shared_host_safe:pa(ge(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:dn(ge(n.assert_stdout_contains)),assert_stdout_regex:Bn(ge(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:dn(ge(n.assert_stderr_contains)),assert_stderr_regex:Bn(ge(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:fa(ge(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:_a(ge(n.assert_json_field_equals),"--add"),assert_json_field_gte:ha(ge(n.assert_json_field_gte),"--add"),note:ge(n.note)}}function ge(e){let t=e?.trim();return t&&t.length>0?t:void 0}function qL(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",d.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(fe(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function KL(e){return e?e.flatMap(t=>{let n=ya(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",d.USAGE);ob(o)}return n}):[]}function zL(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",d.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=pe(n,"--remove"),i=o.path!==void 0?"path":"command",a=o.path??o.command;if(!a?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:i,value:a.trim()}}return{kind:"either",value:n}}):[]}function HL(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function BL(e){try{e.stdin?.end()}catch{}}function ab(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=Lv?t:`${t.slice(0,Lv-3)}...`}function sb(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function wd(e){try{process.stderr.write(`${e}
32
+ `)}catch{}}function VL(e,t){if(!sb(t))return null;let n=ab(e.command),r=Date.now();wd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let i=Date.now()-r;wd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${i} command="${n}"`)},AL());return o.unref?.(),o}function WL(e,t,n,r){if(!sb(r))return;let o=ab(e.command),i=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",s=[];t.timedOut&&s.push("reason=timeout"),t.maxBufferExceeded&&s.push("reason=max_buffer"),t.outputTruncated&&s.push("output=truncated"),t.signal&&s.push(`signal=${t.signal}`);let c=t.exitCode===null?"null":String(t.exitCode),m=s.length>0?` ${s.join(" ")}`:"";wd(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${c} elapsed_ms=${i}${m} command="${o}"`)}async function Fv(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Wv("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function YL(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function JL(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await Fv(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{Fv(r)},EL()),t.forceKillTimer.unref?.()}}function XL(e){return new Promise(t=>{let n=!1,r=null,o=(i,a=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),a&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(i))};e.on("exit",(i,a)=>{n||(r=setTimeout(()=>{o({code:i,signal:a},!0)},TL()),r.unref?.())}),e.on("close",(i,a)=>{o({code:i,signal:a})})})}function QL(e,t,n,r,o){return Wv(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function Mv(e){let t=await gd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,Ya),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>Ya}}finally{await t.close()}}async function ZL(e,t,n,r,o,i=process.cwd()){let a=Date.now(),s=await Yv(oe.join(Jv(),"pm-linked-test-output-"));try{let c=oe.join(s,"stdout.log"),m=oe.join(s,"stderr.log"),[p,u]=await Promise.all([gd(c,"w"),gd(m,"w")]),f;try{f=QL(e,n,p.fd,u.fd,i)}catch(H){throw await Promise.all([p.close(),u.close()]),H}let _=XL(f),h;f.on("error",H=>{h=H.message}),await Promise.all([p.close(),u.close()]),BL(f);let g={heartbeat:VL(r,o),forceKillTimer:null,timedOutTimer:null},y=JL(f,g),w=!1;g.timedOutTimer=setTimeout(()=>{w=!0,y()},t),g.timedOutTimer.unref?.();let{code:b,signal:S}=await _;YL(g);let[T,$]=await Promise.all([Mv(c),Mv(m)]),P=T.truncated||$.truncated,L=P?`
33
+ [pm linked-test output truncated at ${Ya} bytes per stream; the child process continued to completion]
34
+ `:"",q={stdout:`${T.text}${L}`,stderr:$.text,exitCode:b,signal:S,timedOut:w,maxBufferExceeded:!1,outputTruncated:P,spawnError:h};return WL(r,q,a,o),q}finally{await Zr(s,{recursive:!0,force:!0})}}function e$(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Ya} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function t$(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
35
+ `);return vL.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>bL.test(n)&&kL.test(n))}function n$(e){return t$(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function r$(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function eo(e){let t=r$();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}function Dv(e,t){for(let[n,r]of Object.entries(t.env_set))cn.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)cn.has(n.toUpperCase())||delete e[n]}function o$(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function i$(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function a$(e,t,n){return{env_set:NL(e,"--env-set"),env_clear:LL(t,"--env-clear"),shared_host_safe:n===!0}}async function Qr(e,t,n=!1,r=vd){if(await j(e))try{await ir("seed_linked_test",async()=>{if(await r(oe.dirname(t),{recursive:!0}),n){await Nv(e,t,{recursive:!0,force:!0});return}await Nv(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&Ve(o))return;throw o}}async function Uv(e,t,n,r=!1){for(let[o,i]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let a=await X(ne(o));if(a!==null){let s=await A(i);await Ye({pmRoot:i,filePath:ne(i),raw:a,op:"settings:write",author:C(void 0,s.author_default),lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Qr(ne(o),ne(i));await Qr(oe.join(n.projectPmRoot,"extensions"),oe.join(e,"extensions"),!0),await Qr(oe.join(n.globalPmRoot,"extensions"),oe.join(t,"extensions"),!0)}async function Gv(e,t){if(!await j(e))return;let n=await yd(e,{withFileTypes:!0});for(let r of n){if(yL.has(r.name))continue;let o=oe.join(e,r.name),i=oe.join(t,r.name);if(r.isDirectory()){await Qr(o,i,!0);continue}r.isFile()&&await Qr(o,i)}}async function jv(e,t){let n=await X(ne(e));if(n===null||await j(tc(e)))return;let r=await A(t);await Zr(tc(t),{force:!0}),await Zr(ne(t),{force:!0}),await Ye({pmRoot:t,filePath:ne(t),raw:n,op:"settings:write",author:C(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function er(e){if(!await j(e))return 0;let t=0,n=await yd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||wL.has(r.name))continue;let o=oe.join(e,r.name),i;try{i=await yd(o,{withFileTypes:!0})}catch{continue}for(let a of i)a.isFile()&&sm.some(s=>a.name.toLowerCase().endsWith(s))&&(t+=1)}return t}function s$(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function c$(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function l$(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?Se(e,t):Object.is(e,t)}function d$(e,t,n){let r=[];r.push(...qv("stdout",t,e.assert_stdout_contains)),r.push(...Kv("stdout",t,e.assert_stdout_regex)),r.push(...qv("stderr",n,e.assert_stderr_contains)),r.push(...Kv("stderr",n,e.assert_stderr_regex)),r.push(...m$(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},i=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(i).length>0))return r;let a;try{a=JSON.parse(t)}catch(s){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${s instanceof Error?s.message:String(s)}`),r}for(let[s,c]of Object.entries(o)){let m=md(a,s);if(!m.found){r.push(`assert_json_field_equals missing path "${s}"`);continue}let p=c$(c);l$(m.value,p)||r.push(`assert_json_field_equals mismatch at "${s}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(m.value)})`)}for(let[s,c]of Object.entries(i)){let m=md(a,s);if(!m.found){r.push(`assert_json_field_gte missing path "${s}"`);continue}if(typeof m.value!="number"||!Number.isFinite(m.value)){r.push(`assert_json_field_gte path "${s}" resolved to non-numeric value`);continue}m.value<c&&r.push(`assert_json_field_gte failed at "${s}" (expected >= ${c}, actual ${m.value})`)}return r}function qv(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function Kv(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(i){r.push(`${e} regex assertion is invalid: /${o}/ (${i instanceof Error?i.message:String(i)})`)}return r}function m$(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function zv(e){let t=Qa(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Cr(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&ib(n))}function p$(e){return{root:e,schemaProjectPmPath:oe.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:oe.join(e,"schema","global"),trackerProjectPmPath:oe.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:oe.join(e,"tracker","global"),workspaceSnapshotRoot:oe.join(e,"workspace","project"),workspaceIsolatedRoot:oe.join(e,"workspace","isolated")}}function u$(e,t,n){return e.some(r=>Xv(r,t,n)==="snapshot")}async function f$(e,t){let n=oe.join(e,".agents"),r=oe.join(n,"pm");await vd(n,{recursive:!0}),await Zr(r,{recursive:!0,force:!0}),await fL(t,r,process.platform==="win32"?"junction":"dir")}async function _$(e,t=Nr,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function h$(e,t,n){t&&(await Uv(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await Uv(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Gv(t.projectPmRoot,e.trackerProjectPmPath),await Gv(t.globalPmRoot,e.trackerGlobalPmPath),await jv(t.projectPmRoot,e.trackerProjectPmPath),await jv(t.globalPmRoot,e.trackerGlobalPmPath)))}function g$(e,t,n){return e.some(r=>{let o=r.command??"",i=o.length>0&&eb(o),a=n?.autoPmContext===!0&&i?"auto":Qv(r,t,n?.overrideLinkedPmContext===!0);return Zv(a,i)==="tracker"})}async function y$(e,t){return{sourceProjectItemCount:t?await er(t.projectPmRoot):0,sourceGlobalItemCount:t?await er(t.globalPmRoot):0,schemaProjectItemCount:await er(e.schemaProjectPmPath),schemaGlobalItemCount:await er(e.schemaGlobalPmPath),trackerProjectItemCount:await er(e.trackerProjectPmPath),trackerGlobalItemCount:await er(e.trackerGlobalPmPath)}}function w$(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,i=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,a=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,s=e.workspaceContextMode==="isolated"?"":a;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:i,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==i),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:a,source_workspace_root:s,trust:e.trust}}async function v$(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Xa(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?$L(n):!1,o=r&&n?eb(n):!1,i=e.options?.autoPmContext===!0&&o,a=i?"auto":Qv(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),s=Zv(a,o),c=s==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await f$(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await Ec(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Ec(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:w$({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:a,effectivePmContextMode:s,autoPmContextApplied:i,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function Hv(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function b$(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function k$(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function S$(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return k$(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function E$(e){if(!e.linkedTest.command)return Hv(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=UL(e.linkedTest.command);return t?Hv(e.linkedTest,e.executionContext,t):null}function A$(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Ja(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?Ja(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function Ja(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function T$(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=PL({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Ja(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function C$(e){return E$(e)||S$(e)||A$(e)||T$(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!xL(e.linkedTest)?Ja(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function I$(e){let t=i$(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return Dv(n,e.runtimeDirectives),Dv(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&o$(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Er]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Er]="read_only"),n}function R$(e,t,n,r){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...r?{execution_receipt:r}:{}}}function Bv(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function O$(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:s$(e.execution),failure_category:n$(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:e$(e.execution,e.timeoutMs)}}function x$(e){let t=Sv(e.execution.stdout,e.execution.stderr);if(e.options?.failOnEmptyTestRun===!0||zv(e.linkedTest.command??"")){let r=za(e.execution.stdout,e.execution.stderr);if(r)return Bv({...e,emptyRunSignal:r});if(zv(e.linkedTest.command??"")&&!t)return Bv({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let n=d$(e.linkedTest,e.execution.stdout,e.execution.stderr);return n.length>0?b$(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${n.join("; ")}`,e.execution):R$(e.linkedTest,e.executionContext,e.execution,t)}async function P$(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await ZL(t,n,I$(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?x$({...e,execution:r}):O$({...e,execution:r,timeoutMs:n})}async function Sd(e,t,n){let r=[],o=await Yv(oe.join(Jv(),"pm-linked-test-")),i=p$(o),a=Xa(n?.pmContext),s=OL(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=a$(n?.envSet,n?.envClear,n?.sharedHostSafe),p=n?.sourceRoots,u=q_(),f=g$(e,a,n),_=u$(e,s,n?.overrideLinkedWorkspaceContext===!0),h=await j_(u);try{await _$(i,Nr,f),await vd(i.workspaceIsolatedRoot,{recursive:!0}),await h$(i,p,f),_&&await Tv(u,i.workspaceSnapshotRoot);let g=await y$(i,p);for(let y=0;y<e.length;y+=1){let w=e[y],b=Xv(w,s,n?.overrideLinkedWorkspaceContext===!0),S=await v$({linkedTest:w,layout:i,counts:g,sourceRoots:p,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:s,workspaceContextMode:b,currentSourceRef:h,sourceWorkspaceRoot:u}),T=C$({linkedTest:w,executionContext:S.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:S.linkedOverridePmContextMode,options:n});if(T){r.push(T);continue}r.push(await P$({linkedTest:w,index:y,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:S.executionContext,options:n}))}}finally{await Zr(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function N$(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,i=await z(n,t,r.id_prefix,r.item_format,o);if(!i)throw new l(`Item ${t} not found`,d.NOT_FOUND);let a=await ce(i,{schema:r.schema});return{itemId:i.id,tests:a.document.metadata.tests??[],testRuns:a.document.metadata.test_runs??[],changed:!1,removed:0}}function L$(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function $$(e,t){let n=[...e];for(let r of t)n.some(o=>L$(o,r))||n.push(r);return n}function F$(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((i,a)=>r.has(a+1)?!1:!t.some(s=>s.kind==="command"?i.command===s.value:s.kind==="path"?i.path===s.value:i.command===s.value||i.path===s.value));return{tests:o,removed:e.length-o.length}}function M$(e,t,n,r){return F$($$(e,t),n,r)}function D$(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function cb(e){if(D$(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",d.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",d.USAGE)}async function U$(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:i,adds:a,removes:s,removeIndexes:c}=e;if(a.length===0&&s.length===0&&c.length===0)return N$({id:t,pmRoot:r,settings:o,typeToFolder:i});let m=0,p=await le({pmRoot:r,settings:o,id:t,op:a.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let f=u.metadata.tests??[],_=M$(f,a,s,c);if(m=_.removed,(s.length>0||c.length>0)&&m===0)throw new l("No linked tests matched the requested removal selector",d.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...s.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return u.metadata.tests=_.tests,{changedFields:Se(f,_.tests)?[]:["tests"]}}});return{itemId:p.item.id,tests:p.item.tests??[],testRuns:p.item.test_runs??[],changed:p.changedFields.length>0,removed:m}}function G$(e,t){cb(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Zn(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?Rv(t,n):void 0,o=e.timeout===void 0?void 0:fe(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:Xa(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function j$(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Sd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:mt(process.cwd())}})}function q$(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=kd(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function K$(e){let t=IL(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=k(),i=Jr(e.options.measure,o);return{run_id:CL("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:i.length>0?i:void 0,executions:e.runResults.filter(a=>a.command?.trim()).slice(0,32).map(a=>({command:a.command.trim(),requested_pm_context_mode:a.execution_context?.requested_pm_context_mode,pm_context_mode:a.execution_context?.pm_context_mode,workspace_context_mode:a.execution_context?.workspace_context_mode,trust_reason:a.execution_context?.trust.reason}))}}async function z$(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:i,runResults:a,failOnSkippedTriggered:s,warnings:c}=e;if(t.run!==!0||!i)return;let m=K$({options:t,runStartedAt:i,runResults:a,failOnSkippedTriggered:s});if(r.testing.record_results_to_items!==!0)return{entry:m,receipt:{recorded:!1,reason:"tracking_disabled",run_id:m.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Ka({pmRoot:n,settings:r,itemId:o,author:C(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),{entry:m,receipt:{recorded:!0,reason:"recorded",run_id:m.run_id}}}catch(p){return c.push(`test_result_tracking_failed:${o}:${p instanceof Error?p.message:String(p)}`),{entry:m,receipt:{recorded:!1,reason:"write_failed",run_id:m.run_id}}}}function Vv(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),i=e.metricBelow.slice(0,o).trim(),a=e.metricBelow.slice(o+1).trim(),s=Number(a);if(o<=0||i.length===0||a.length===0||!Number.isFinite(s))throw new l("--metric-below must use name=value",d.USAGE);r=av(t,i,s)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:sv(t,e.metricDiff)}}async function H$(e,t,n){if(e.acknowledgeLinkedTests===!0)return K_(t,n,k())}function B$(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:i,warnings:a,recording:s,measurementProjection:c}=e;return{ok:n.every(m=>m.status!=="failed"&&m.status!=="refused")&&i!==!0,id:t.itemId,tests:t.tests,run_results:n,failure_categories:r,selection:o?{selector:o.selector,requested:o.requested,selected_indexes:o.selected_indexes,selected_count:o.selected_count,skipped_count:o.skipped_count}:void 0,fail_on_skipped_triggered:i?!0:void 0,warnings:a.length>0?a:void 0,changed:t.changed||s?.receipt.recorded===!0,...s?{evidence_recording:s.receipt}:{},count:t.tests.length,...t.removed>0?{removed:t.removed}:{},...c}}async function Za(e,t,n){let r=Ov(t);if(r)return xv(t),cb(t),_d(e,t,n,E(process.cwd(),n.path)),{...await fd(e,{...r,author:t.author,message:t.message,force:t.force},n),run_results:[],failure_categories:eo([])};let o=$t(),i=E(process.cwd(),n.path);await I(i);let a=await A(i);_d(e,t,n,i),Jr(t.measure,"validation"),Vv(t,[],void 0);let s=x(a,R()),c=await o.resolveList(t.add,"--add"),m=await o.resolveList(t.addJson,"--add-json"),p=await o.resolveList(t.remove,"--remove"),u=[...GL(c),...KL(m)],f=await Kn(u,C(t.author,a.author_default),k())??[],_=zL(p),h=HL(t.removeIndex),g=await U$({id:e,options:t,pmRoot:i,settings:a,typeToFolder:s.type_to_folder,adds:f,removes:_,removeIndexes:h}),y=G$(t,g.tests),w=await H$(t,i,g.tests),b=t.run===!0?k():void 0,S=await j$({options:t,runOptions:y,pmRoot:i,untrustedLinkedTestsPolicyEnabled:a.testing.allow_untrusted_linked_tests});Pv(e,t,n,i,S);let T=eo(S),$=t.run===!0&&t.failOnSkipped===!0&&S.some(J=>J.status==="skipped"),P=q$(t,y.runSelection,S);w&&P.push(`linked_test_trust_acknowledged:${w.acknowledged}`);let L=await z$({options:t,pmRoot:i,settings:a,itemId:g.itemId,runStartedAt:b,runResults:S,failOnSkippedTriggered:$,warnings:P}),q=L?.receipt.recorded?dd([...g.testRuns,L.entry]):g.testRuns,H=Vv(t,q,L?.entry);return B$({item:g,runResults:S,failureCategories:T,runSelection:y.runSelection,failOnSkippedTriggered:$,warnings:P,recording:L,measurementProjection:H})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="61f797d4-1c7c-52f2-83a9-818c2faca5ff")}catch{}})();var V$=(e,t)=>{if(e===void 0)return;let n=ee(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},W$=e=>{if(e===void 0)return;let t=fe(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},lb=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,d.USAGE);return n},Y$=e=>e instanceof Error?e.message:String(e),J$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},X$=e=>e.trim().replaceAll(/\s+/g," "),Q$=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),Z$=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),eF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},tF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},es=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),db=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),nF=e=>typeof e=="number"?e:void 0,rF=e=>{let t={assert_stdout_contains:es(e.assert_stdout_contains),assert_stdout_regex:es(e.assert_stdout_regex),assert_stderr_contains:es(e.assert_stderr_contains),assert_stderr_regex:es(e.assert_stderr_regex),assert_stdout_min_lines:nF(e.assert_stdout_min_lines),assert_json_field_equals:db(e.assert_json_field_equals),assert_json_field_gte:db(e.assert_json_field_gte)};return JSON.stringify(t)},oF=e=>{let t=Ed(e.command);return t!==void 0?`command:${e.scope}:${X$(t)}`:`path:${e.scope}:${Ed(e.path)??""}`},mb=e=>{let t=Q$(e.env_set),n=Z$(e.env_clear),r=eF(e.pm_context_mode),o=tF(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",a=rF(e);return`${oF(e)}:${t}:${n}:${r}:${o}:${i}:${a}`},iF=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,aF=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"||o.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},sF=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},ts=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
36
+ `)}catch{}},cF=async(e,t,n)=>{let r=[],o=0;for(let i of e){let a=await Za(i.id,{run:!1},{...t,path:n});o+=a.tests.length,r.push({item:i,tests:a.tests})}return{itemTests:r,linkedTests:o}},lF=async e=>{let t=F(e.settings.schema),n=x(e.settings,R()),r=V$(e.options.status,t),o=lb(e.options.limit,"--limit"),i=lb(e.options.offset,"--offset")??0,a=(await _e(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(s=>r?s.status===r:!0).sort((s,c)=>s.id.localeCompare(c.id));return{filteredItems:o===void 0?a.slice(i):a.slice(i,i+o),statusFilter:r,limitFilter:o,offsetFilter:i}},dF=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=mb(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,iF(t.get(o),r.timeout_seconds))}return t},mF=async(e,t)=>{let n=[],r=e.tests.map(p=>{let u=mb(p),f=t.seenTestKeys.has(u);if(!f){t.seenTestKeys.add(u);let _=t.effectiveTimeoutByKey.get(u);n.push(_===void 0?p:{...p,timeout_seconds:_})}return{test:p,key:u,duplicate:f}}),o=n.length>0?await Sd(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],i=0,a=r.map(({test:p,key:u,duplicate:f})=>{if(!f){let _=o[i];return i+=1,_}return{command:p.command,path:p.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),s=aF(a),c=eo(a),m=await fF(e,s,a,t);return{passed:s.passed,failed:s.failed,skipped:s.skipped,trackingWarnings:m,failureCategories:c,result:{ok:s.failed===0&&!(t.options.failOnSkipped===!0&&s.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:s.passed,failed:s.failed,skipped:s.skipped,run_results:a,failure_categories:c}}},pF=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),uF=e=>e?!0:void 0,fF=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=pF(t,r.options);await Ka({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:k(),recorded_at:k(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:uF(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${Y$(o)}`]}return[]},_F=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},Ed=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},hF=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:mt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:dF(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:J$(),trackingAttempt:_F(),trackingResumedFrom:Ed(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),gF=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:eo([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},yF=async(e,t,n)=>{for(let[r,o]of e.entries()){ts(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let i=await mF(o,t);sF(n.failureCategories,i.failureCategories),n.passed+=i.passed,n.failed+=i.failed,n.skipped+=i.skipped,n.trackingWarnings.push(...i.trackingWarnings),n.results.push(i.result),ts(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${i.failed===0?"passed":"failed"} passed=${i.passed} failed=${i.failed} skipped=${i.skipped}`)}},wF=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=kd(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},vF=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),bF=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),kF=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await lF({pmRoot:n,settings:r,options:e}),i=W$(e.timeout),a=k(),s=await cF(o.filteredItems,t,n);return ts(e,bF({...o,linkedTests:s.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:s.itemTests,linkedTests:s.linkedTests,defaultTimeoutSeconds:i,runStartedAt:a}},SF=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},pb=async(e,t)=>{let n=await kF(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=gF(e,n.linkedTests,n.filteredItems),i=hF({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await yF(n.itemTests,i,r),wF(e,r);let a=SF({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return ts(e,`end status=${a.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),vF({ok:a.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:a.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="920b5725-710a-5839-86e3-dbdbc8a602a8")}catch{}})();function ub(e,t,n){let r;if(typeof e.lines=="string")r=Li(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");r=Li(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="09fa5b5c-d44a-55e4-9365-a08702d8a952")}catch{}})();function Le(e,t){let n=v(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}function wn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9a4dbe8d-9341-55f1-8c4a-d476c2b338e5")}catch{}})();function EF(e){let t=v(e.args,"subcommand")??Le(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:v(e.args,"name")??v(e.options,"name"),author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ye(n)}}function AF(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=wn({list:()=>qf(t.global),show:()=>Kf(r,t.global),"show-status":()=>zf(r,t.global),"list-fields":()=>Vf(t.global),"show-field":()=>Wf(r,t.global),"remove-type":()=>Df(r,{author:o,force:i},t.global),"remove-field":()=>Bf(r,{author:o,force:i},t.global),"remove-status":()=>jf(r,{author:o,force:i},t.global),"apply-preset":()=>Yf(v(t.args,"typePreset")??v(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function TF(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,a=t.args.commands??t.options.commands,s=t.args.requiredTypes??t.options.requiredTypes;return Hf(n,{type:v(t.args,"fieldType")??v(t.options,"fieldType"),commands:a===void 0?void 0:ye(a),description:v(t.args,"description")??v(t.options,"description"),cliFlag:v(t.args,"cliFlag")??v(t.options,"cliFlag"),alias:i,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:s===void 0?void 0:ye(s),author:r,force:o},t.global)}function CF(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,a=t.args.role??t.options.role;return Gf(n,{role:a===void 0?void 0:ye(a),alias:i,description:v(t.args,"description")??v(t.options,"description"),order:De(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function IF(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return Mf(n,{description:v(t.args,"description")??v(t.options,"description"),defaultStatus:v(t.args,"defaultStatus")??v(t.args,"default_status")??v(t.options,"defaultStatus")??v(t.options,"default_status"),folder:v(t.args,"folder")??v(t.options,"folder"),alias:i,author:r,force:o},t.global)}function RF(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=v(t.args,"to")??Le(t.options,"to"),s=v(t.args,"migrationId")??v(t.args,"migration_id")??v(t.options,"migrationId")??v(t.options,"migration_id"),c=v(t.args,"fieldTypeScope")??v(t.options,"fieldTypeScope")??v(t.args,"type")??v(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:a}:n==="rename-field"?{kind:"rename-field",from:r??"",to:a,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:a};return $f(m,{migrationId:s,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function fb(e){let t=EF(e);Zu(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Tn.find(o=>o===t.subcommand);if(n)return Lf(n,t.name,{definition:e.args.definition??e.options.definition,policy:v(e.args,"policy")??v(e.options,"policy"),message:v(e.args,"message")??v(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=AF(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return RF(t);if(t.subcommand==="add-field")return TF(t);if(t.subcommand==="add-status")return CF(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Jf({minCount:De(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):IF(t);throw Re({command_path:"schema",token:t.subcommand,allowed:Ff,exit_code:64})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32f1d276-9fdd-5525-8c99-742d597f898a")}catch{}})();function ns(e){return v(e.args,"target")??v(e.options,"target")}function be(e,t=e.options){return e.id??Le(t,"id")}async function OF(e){let t=Rn("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),Uc(await yt(v(e.args,"status")??v(t,"status"),t,e.global),t)}async function xF(e){let t=Le(e.args,"query"),n=Rn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Uc(await Or(t,n,e.global),n)}async function PF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return Ae(await jt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function NF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Ae(await nl(be(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function LF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return Ae(await ct(be(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function $F(e){let t=Xi(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),qh(be(e),t,e.global)}function _b(e,t){return f_(ub(e.options,t,De),e.global)}function FF(e){let t=ye(e.options.lookupPath);if(t&&t.length>0)return _b(e,t);let n=be(e);return e.options.discover===!0?gc(n,Ri(e.options),e.global):u_(n,Ar(e.options),e.global)}function MF(e){return vv({subcommand:v(e.args,"subcommand")??v(e.options,"subcommand"),limit:o_(e.args,e.options)},e.global)}function DF(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Tr(e.global,t)}function UF(e){let t=v(e.args,"configAction")??v(e.options,"configAction")??v(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);let n=v(e.args,"value")??v(e.options,"value"),r=v(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return dg(v(e.args,"scope")??v(e.options,"scope")??"project",t,v(e.args,"key")??v(e.options,"key"),r,e.global,v(e.options,"policy")===void 0?n:void 0)}function GF(e){let t=e.options;return Z_(Q_(t),e.global)}function jF(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}async function qF(e){let t=v(e.args,"subcommand")??Le(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=he(e.args,e.options),i=await qy({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:KF(e),reorderTo:jF(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&t_(e.args)&&(i.mutation_receipt=Na(i,void 0)),t==="show"?i:Ae(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function KF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function zF(e){let t=v(e.args,"subcommand")??Le(e.options,"subcommand"),n=t.trim().toLowerCase(),r=v(e.args,"name")??v(e.options,"name"),o=wn({list:()=>rw(),show:()=>ow(r),lint:()=>iw(r),apply:()=>aw(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!o)throw Re({command_path:"profile",token:t,allowed:nw,exit_code:64});return o()}async function HF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return Ae(await Sg(be(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function BF(e){let{changedFields:t,runnerOptions:n}=he(e.args,e.options);return Ae(await Vy(Pi(n),e.global),{changedFields:t})}async function VF(e){let{changedFields:t,runnerOptions:n}=he(e.args,e.options),r=v(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Ae(await Ng(xi(o),e.global),{changedFields:t})}async function WF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options),o=v(r,"target")??Le(e.args,"target");return Ae(await on(be(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function YF(e){let t={...e.args,...e.options};return __(Le(t,"subcommand"),v(t,"id")??e.id,v(t,"target"),c_(t),e.global)}function JF(e){return d_(E(process.cwd(),e.global.path),{...e.args,...e.options})}var hb={init:e=>Nr(v(e.args,"prefix"),e.global,e.options),context:e=>Cc(Rn("context",e.options),e.global),next:e=>Rr(Rn("next",e.options),e.global),eval:Gw,events:jw,merge:qw,workspace:Kw,meet:Ua,event:Ua,remind:Ua,list:OF,get:e=>{let t=be(e);return Rc(t,e.global,Rn("get",e.options,[t]))},search:xF,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ye(e.options.status);return hc(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:v(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:De(e.options.limit,"limit")})},create:PF,copy:NF,focus:e=>_l(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:LF,"item-reopen":Ry,restore:WF,claim:Ty,release:Iy,"start-task":e=>fn(e,"start_task"),"pause-task":e=>fn(e,"pause_task"),"close-task":e=>fn(e,"close_task"),close:Cy,comments:$F,notes:e=>Wy(be(e),Xi(e.options),e.global),learnings:e=>kg(be(e),Xi(e.options),e.global),files:FF,docs:e=>p_(be(e),Ar(e.options),e.global),test:e=>Za(be(e),e.options,e.global),"test-all":e=>pb(e.options,e.global),telemetry:MF,validate:e=>ji(e.options,e.global,{runUpdate:(t,n,r)=>ct(t,n,r)}),health:DF,assurance:e=>z_(e.args,e.options,e.global),contracts:e=>Nc(e.options,e.global),config:UF,activity:GF,aggregate:e=>Ic(e.options,e.global),extension:e=>Un(ns(e),e.options,e.global),package:e=>Un(ns(e),e.options,e.global),install:e=>Un(ns(e),{...e.options,install:!0},e.global),upgrade:e=>B_(ns(e),e.options,e.global),delete:e=>fl(be(e),e.options,e.global),deps:e=>m_(be(e),e.options,e.global),graph:YF,"files-discover":e=>gc(be(e),e.options,e.global),"files-lookup":e=>_b(e,ye(e.options.paths)),history:e=>eh(be(e),e.options,e.global),"history-redact":e=>bg(be(e),e.options,e.global),"history-repair":hg,"history-compact":gg,"history-attest":e=>V_(e.options,e.global),"history-author-acknowledge":JF,plan:qF,schema:fb,profile:zF,stats:e=>ad(e.global,zw(e.options)),append:HF,"update-many":BF,"close-many":VF,gc:e=>H_(e.global,e.options)};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96234a42-d25c-5221-a12b-a992925a13ba")}catch{}})();var XF=new Map;function Ad(){XF.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69f9c792-7ee1-5e4b-9900-38e1c887c4d4")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5417c092-2e52-5b18-bcb6-da34f07f595f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ba66cac9-25d6-559e-95d1-71db5c404807")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f06f072-47a7-560e-9291-72e47225a73c")}catch{}})();function gb(){return{metadata:{},body:""}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f5ba86ac-336e-5fdb-a8fb-d8d7e7c1a504")}catch{}})();var wb=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:bu().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],yb=new Map;for(let e of wb){yb.set(e.id,e);for(let t of e.aliases)yb.set(t,e)}function Td(){return wb.map(e=>e.id)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b11b0e04-bad1-5090-8df9-d922568db013")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c8b847c-770a-556f-a7ea-151c82629318")}catch{}})();var H4=[...ao],B4=[...so],Cd=new Set(Jt.filter(e=>e.hidden).map(e=>e.alias)),vb=vu("full").filter(e=>!e.includes(" ")&&!Cd.has(e)),QF=N(go),ZF=N(yo),eM=N(Ao),tM=N(Oo),bb=pr("restore",Ot("restore")),kb=pr("history-attest",Ot("history-attest")),nM=N(xo),rM=N(gp),oM=N(yp),iM=N(Ro),aM=N($o),sM=N(Po),cM=N(No),lM=N(Eo),Id=[...new Set(Ee.map(e=>e.canonical_argv[0]))],Sb=[...new Set(Ee.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],V4=new Set(_o.filter(e=>e.disposition==="package_owned").map(e=>B(e.command))),Eb=Ee.filter(e=>e.canonical_argv[0]==="history"),dM=Eb.map(e=>e.canonical_argv[1]).join(" ");var mM=Eb.map(e=>({...e,flags:N(Ot(e.alias))})),pM=N(wo),uM=N(vo,!1),fM=N(Lo),_M=N(dr),hM=N(mr),gM=N(Uo),yM=N(Mo),wM=N(Co),vM=N(Do),bM=N(Fo),kM=N(Go),SM=N(To),EM=N(Io),AM=N(ko),TM=N(jo),CM=N(bo),Rd=`${Tn.join(" ")} list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status`;var IM=N(qo),RM=`${IM} bash zsh fish`,Od=os(Td()),rs="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",xd=`${rs} upgrade`,OM=N(So),xM=N(cr),PM=N(lr);var NM=N(Ot("close")),LM=N(Ot("close-task")),$M=N(Ot("release")),FM=N(Ot("claim"));var Ab=ho.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),Pd=[...Xo].join("|"),Nd=[...Xo].map(e=>`${e}=*`).join("|"),Ld=[...Ab.split(" ").filter(e=>!Xo.has(e)),"-h","-V"].join("|");function os(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5cb75946-44c9-5e10-a39c-c981011b7efe")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b0fbba44-df4b-5cf3-968c-a0e86fd4afb5")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d548143c-24be-5420-8185-f52e3941cff3")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7cfbd72-3010-53e7-946b-e65842ee4ceb")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c89b3de-0b7c-529b-a655-87d3e83bd46c")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e9a2374-d190-52e1-8afd-14e1954863f0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="710f1406-c114-56c7-9f0b-4f7c20b1eea1")}catch{}})();var xb=Symbol("pm.active-extension-host-context");function qe(e){return{fullChangedFields:!0,options:e}}var U=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[xb]=!0,n}run(t,n={}){return Nb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return $h(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return pc(await this.list(mc(t)))}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}append(t,n,r={}){return this.runTyped("append",{id:t,...qe(Ut(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,i={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,r={}){return this.runTyped("schema",{name:n,options:{...r,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){let{type:r,...o}=n;return this.runTyped("schema",{name:t,options:{...o,fieldType:r,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...i===void 0?{}:{reorderTo:i},options:Ut(r,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",qe(t))}update(t,n={}){return this.runTyped("update",{id:t,...qe(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...qe(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...qe(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...qe(t)})}release(t,n={}){return this.runTyped("release",{id:t,...qe(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...qe(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...qe(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...qe(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...qe(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...qe(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...qe(r)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function HM(e={},t={}){return new U(t).context(e)}function BM(e={},t={}){return new U(t).list(e)}function VM(e={},t={}){return new U(t).listAllComplete(e)}function WM(e,t={},n={}){return new U(n).search(e,t)}function YM(e,t={},n={}){return new U(n).get(e,t)}function JM(e={},t={}){return new U(t).next(e)}function XM(e={},t={}){return new U(t).aggregate(e)}function QM(e,t={},n={}){return new U(n).comments(e,t)}function ZM(e,t={},n={}){return new U(n).notes(e,t)}function eD(e,t={},n={}){return new U(n).learnings(e,t)}function tD(e,t={},n={}){return new U(n).files(e,t)}function nD(e,t={},n={}){return new U(n).filesDiscover(e,t)}function rD(e,t={},n={}){return new U(n).docs(e,t)}function oD(e,t={},n={}){return new U(n).deps(e,t)}function iD(e,t={},n={},r={}){return new U(r).graph(e,t,n)}function aD(e,t,n={},r={}){return new U(r).append(e,t,n)}function sD(e={},t={}){return new U(t).create(e)}function cD(e,t={},n={}){return new U(n).update(e,t)}function lD(e,t,n={},r={}){return new U(r).reopen(e,t,n)}function dD(e,t,n={},r={}){return new U(r).close(e,t,n)}function mD(e,t={},n={}){return new U(n).claim(e,t)}function pD(e={},t={}){return new U(t).claimNext(e)}function uD(e,t={},n={}){return new U(n).release(e,t)}function fD(e,t={},n={}){return new U(n).copy(e,t)}function _D(e,t={},n={}){return new U(n).delete(e,t)}function hD(e,t,n={},r={}){return new U(r).restore(e,t,n)}function gD(e,t={},n={}){return new U(n).focus(e,t)}var Rb=Yp(),yD=new zM;function is(){Ms(wm()),Ds(vm()),Us(bm()),Gs(km()),js(Sm()),qs(Em()),Ks(Am())}async function wD(e,t,n,r){return Jp(()=>t===void 0?Rb.read(()=>Ob(e,n,r)):Rb.write(()=>bD(t,()=>Ob(e,n,r))))}async function Ob(e,t,n){let r=E(t,e.path);if(e.noExtensions)return is(),$c({pmRoot:r},()=>n(null));if(!await j(ne(r)))return is(),n(null);let o=null,i;try{let a=await A(r),s=await ar({pmRoot:r,settings:a,cwd:t,noExtensions:!1}),c=await sr({...s,loaded:s.loaded});i={loadResult:s,activationResult:c},Ms(c.hooks),Ds(c.commands),Us(c.parsers),Gs(c.preflight),js(c.services),qs(c.renderers),Ks(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:s.loaded}}catch(a){is(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",a)}try{return await $c({pmRoot:r,packages:o?.packages},()=>n(o))}finally{is(),i&&await Os(i.loadResult,i.activationResult).catch(()=>{})}}function Pb(e,t){let n=Gn(e);return t?.registrations.commands.find(r=>Gn(r.action)===n)?.command??t?.commands.handlers.find(r=>Gn(r.command)===n)?.command}async function vD(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let i=Pb(e,o);if(!i)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let a=typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension",s=await Jo({command:Oi(i),args:ye(n.args??t.args),options:_c(t,n),global:r,pm_root:o.pmRoot,sdk:Oh(o.pmRoot,U.forActiveExtensionHost({pmRoot:o.pmRoot,author:a}),a,Oi(i))});if(!s.handled){let c=s.warnings.length>0?` (${s.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${c}`,d.USAGE)}return s.result}async function bD(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function kD(e){let t=Le(e,"action"),n=Gn(t),r=wn(Mh,n),o=r?.action??n,i={...e,action:o};return r?.options!==void 0&&(i.options={...r.options,...As(e.options)}),o==="package"&&(i.options={...As(i.options),vocabulary:"package"}),{action:o,args:i}}async function Nb(e){let t=kD(e),n=uc(t.args),r=a_(t.action),o=v(t.args,"cwd"),i=o??process.cwd();t.action==="init"&&(n[Dc]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(i,n.path));try{return t.action==="history-attest"?await $d(t.action,t.args,n,null):e[xb]===!0||yD.getStore()===!0?await $d(t.action,t.args,n,null):await wD(n,o,i,a=>$d(t.action,t.args,n,a))}finally{r&&Ad()}}async function $d(e,t,n,r){let o=fc(t,e),i=wn(hb,e),a=i?void 0:Pb(e,r),s=a===void 0?e:`extension:${a}`;Vs(s,o),tu(s,o);let c={action:e,args:t,options:o,id:v(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},m=i?await i(c):await vD(e,t,o,n,r);if(e==="history-attest")return m;{o.resolvedOutputFormat="json";let p=iu(s,o,m);return await Rh(E(process.cwd(),n.path),p),p}}var SD={closeManyOptionsFromFlat:xi,extensionOptionsFromArgs:_c,globalOptions:uc,mutationListOptions:s_,normalizeActionName:Gn,normalizeCommandPath:Oi,normalizeMcpUpdateOptions:l_,normalizeMcpOptionsArrays:i_,optionsWithAuthor:fc,readRequiredString:Le,readScalarString:n_,readScalarStringAllowBlank:r_,readStringArray:ye,updateManyOptionsFromFlat:Pi,withAddNoteOption:Ar,withFilesDiscoveryOptions:Ri,withMutationCompaction:he};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=SD);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48d03e9b-14a4-545c-8e5d-5f5f2092a113")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38023567-8a5b-5e25-8d71-5112f74d1894")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="484b88ea-87f1-5f53-86ca-74faee0fb9d1")}catch{}})();export{On as AGENT_PROVENANCE_DIMENSIONS,Ou as BASELINE_ITEM_FORMAT_VERSION,Lk as BUILTIN_AGENT_PROVENANCE_ADAPTERS,ur as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,ao as BUILTIN_ITEM_TYPE_VALUES,co as CONFIDENCE_TEXT_VALUES,xu as CURRENT_ITEM_FORMAT_VERSION,nr as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,kn as ISSUE_SEVERITY_VALUES,Wd as ITEM_TYPE_VALUES,Ef as PM_CLI_EXPECTED_ERROR_NAME,vk as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,yk as PM_READ_OUTPUT_DIMENSIONS,wk as PM_READ_OUTPUT_OPTION_FLAGS,Hs as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,U as PmClient,bn as RISK_VALUES,Yk as SEMANTIC_ATTRIBUTION_LIMITS,so as STATUS_VALUES,Nk as agentSessionEnvironment,XM as aggregate,od as analyzeAgentProvenanceDescriptorCoverage,Rk as analyzeSdkCliParameterCompleteness,aD as append,kk as applyReadOutputDimensions,Tk as applyReadOutputSessionReferences,Ck as attachReadOutputSessionReceipt,Ok as boundAgentEpisodeIdentity,it as canonicalDocument,mD as claim,pD as claimNext,Lu as classifyItemFormatVersion,dD as close,QM as comments,HM as context,fD as copy,sD as create,Af as createPmCliExpectedError,gk as decodeReadOutputContinuationCursor,_D as deleteItem,oD as deps,jk as detectAgentIdentity,zk as detectHarnessIdentity,qk as diagnoseAgentIdentity,rD as docs,Pu as effectiveItemFormatVersion,gb as emptyImportedDocument,hk as encodeReadOutputContinuationCursor,WP as evaluateSemanticAttributionCoverage,Vk as explainSourceTraceability,tD as files,nD as filesDiscover,gD as focus,YM as get,iD as graph,YP as groupHistoryByEpisode,Ey as isAlreadyClaimedError,Bk as isItemAlreadyExistsError,Ci as isPmCliExpectedError,Sk as isReadOutputBudgetExceeded,eD as learnings,BM as list,Fk as listAgentProvenanceAdapters,VM as listAllComplete,JM as next,Dk as normalizeAgentProvenanceAdapterValue,Nu as normalizeItemFormatVersion,ze as normalizeItemId,ee as normalizeStatusInput,ZM as notes,k as nowIso,Ak as parseReadOutputSession,Li as parseSourceLineRange,oi as readAuthorEnvironment,Ik as readOutputSessionRemainingTokens,Ac as recordClaimSemanticAttribution,Hi as recordFocusSemanticAttribution,Tc as recordReleaseSemanticAttribution,Mk as registerAgentProvenanceAdapters,$k as registerHarnessSignalDescriptors,uD as release,lD as reopen,xk as resolveAgentSessionContextFromSignals,Hk as resolveAuthorIdentity,Zw as resolveHistoryEpisodeGroupIdentity,bk as resolveReadOutputDimensions,Ek as resolveReadOutputEncoding,Bs as resolveReadOutputSurface,Wk as resolveSemanticLineageIds,hD as restore,Nb as runAction,Pk as runWithAgentSessionContext,Uk as runWithHarnessDetectionSignals,Gk as runWithWorkspaceHarnessSignalDescriptors,WM as search,Jk as semanticAttributionAffinity,We as serializeItemDocument,VP as summarizeAgentModelProvenance,id as summarizeAgentProvenance,cD as update,fd as updateLinkedTest,Vs as validateReadOutputOptions,Kk as writeAuthorEnvironment};
37
37
  //# sourceMappingURL=sdk-core.js.map