@unbrained/pm-cli 2026.11.3 → 2026.11.5

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 (294) hide show
  1. package/.agents/skills/HARNESS_COMPATIBILITY.md +1 -1
  2. package/.agents/skills/README.md +14 -14
  3. package/.agents/skills/pm-developer/SKILL.md +16 -16
  4. package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +14 -14
  5. package/.agents/skills/pm-developer/references/SCRIPTING_COMPOSITION.md +10 -10
  6. package/.agents/skills/pm-extensions/SKILL.md +13 -13
  7. package/.agents/skills/pm-extensions/references/AUTHORING.md +12 -12
  8. package/.agents/skills/pm-sdk/SKILL.md +27 -27
  9. package/.agents/skills/pm-sdk/references/SURFACE_MAP.md +32 -32
  10. package/.agents/skills/pm-test-audit/references/AUDIT.md +1 -1
  11. package/.agents/skills/pm-user/SKILL.md +35 -35
  12. package/.claude-plugin/marketplace.json +1 -1
  13. package/AGENTS.md +9 -9
  14. package/CHANGELOG.md +19 -0
  15. package/README.md +13 -13
  16. package/dist/cli/error-guidance.d.ts +14 -35
  17. package/dist/cli/error-guidance.js +2 -2
  18. package/dist/cli/expected-revisions.d.ts +55 -0
  19. package/dist/cli/expected-revisions.js +2 -0
  20. package/dist/cli/main.js +2 -2
  21. package/dist/cli/register-setup.js +1 -1
  22. package/dist/cli/runtime/invocation-options.js +1 -1
  23. package/dist/cli-bundle/bundle-manifest.json +1 -1
  24. package/dist/cli-bundle/chunks/chunk-2RPORE7M.js +31 -0
  25. package/dist/cli-bundle/chunks/{chunk-Y7H55PCY.js → chunk-335BZ75D.js} +2 -2
  26. package/dist/cli-bundle/chunks/chunk-5GWEY4P6.js +122 -0
  27. package/dist/cli-bundle/chunks/chunk-6VRX2CM7.js +2 -0
  28. package/dist/cli-bundle/chunks/{chunk-5JZMF4M5.js → chunk-7DEKAXVA.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-32BCU6HN.js → chunk-7ZRCYESH.js} +47 -46
  30. package/dist/cli-bundle/chunks/chunk-AUEKTX7V.js +6 -0
  31. package/dist/cli-bundle/chunks/chunk-D7KYPRK4.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-2CBHQXYJ.js → chunk-DAX3AOFI.js} +2 -2
  33. package/dist/cli-bundle/chunks/{chunk-JPKIUWLG.js → chunk-F6NDMKZ4.js} +2 -2
  34. package/dist/cli-bundle/chunks/chunk-FRNMQM45.js +2 -0
  35. package/dist/cli-bundle/chunks/chunk-HNGLDMSZ.js +9 -0
  36. package/dist/cli-bundle/chunks/{chunk-DEJHTFEF.js → chunk-HRCMORE7.js} +2 -2
  37. package/dist/cli-bundle/chunks/chunk-HRFGFIYU.js +2 -0
  38. package/dist/cli-bundle/chunks/{chunk-5IPXDZKU.js → chunk-JI2GDE4I.js} +66 -66
  39. package/dist/cli-bundle/chunks/{chunk-MQJXZX3Q.js → chunk-LS3GI3H4.js} +53 -53
  40. package/dist/cli-bundle/chunks/chunk-OH6WQ7VT.js +3 -0
  41. package/dist/cli-bundle/chunks/{chunk-TZ3D3DPQ.js → chunk-OJDMJT7Y.js} +2 -2
  42. package/dist/cli-bundle/chunks/chunk-S4LPZ4TN.js +20 -0
  43. package/dist/cli-bundle/chunks/chunk-UEGXWXUZ.js +2 -0
  44. package/dist/cli-bundle/chunks/chunk-XLSHFYXZ.js +2 -0
  45. package/dist/cli-bundle/chunks/{chunk-UYNMKUGA.js → chunk-YKXATU2G.js} +2 -2
  46. package/dist/cli-bundle/chunks/item-revision-OJJVPQY7.js +2 -0
  47. package/dist/cli-bundle/chunks/item-transaction-QEPBUCMY.js +2 -0
  48. package/dist/cli-bundle/chunks/mutation-admission-INMM3HHG.js +2 -0
  49. package/dist/cli-bundle/chunks/{register-list-query-I6AZA3IX.js → register-list-query-5Y5JKWU5.js} +2 -2
  50. package/dist/cli-bundle/chunks/{register-mutation-3DAXCLXR.js → register-mutation-WC7OSQID.js} +2 -2
  51. package/dist/cli-bundle/chunks/register-operations-PO63DBZH.js +2 -0
  52. package/dist/cli-bundle/chunks/register-setup-RRFOS7IT.js +2 -0
  53. package/dist/cli-bundle/chunks/{stage-7H36OTDJ.js → stage-E3MMV4TV.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-5PMJOJCZ.js +44 -0
  55. package/dist/cli-bundle/focused-chunks/chunk-7KK66ISG.js +2 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-D4XQOMG4.js → chunk-AHWJPZSJ.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/{chunk-LKN2WGGB.js → chunk-C6P6HPCX.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/chunk-CPMSL4HS.js +2 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-CZM75DE3.js +2 -0
  61. package/dist/cli-bundle/focused-chunks/{chunk-TYHDZUL4.js → chunk-D2TBEBNW.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/chunk-E56OXRYH.js +2 -0
  63. package/dist/cli-bundle/focused-chunks/{chunk-I5FODKYB.js → chunk-F62XGAAY.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/chunk-G4QP365K.js +2 -0
  65. package/dist/cli-bundle/focused-chunks/chunk-G5PJCR7R.js +2 -0
  66. package/dist/cli-bundle/focused-chunks/chunk-GS3JC5UU.js +23 -0
  67. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +2 -0
  68. package/dist/cli-bundle/focused-chunks/chunk-LW64TINU.js +3 -0
  69. package/dist/cli-bundle/focused-chunks/chunk-M6V7UMWL.js +26 -0
  70. package/dist/cli-bundle/focused-chunks/chunk-MC7IE7D7.js +8 -0
  71. package/dist/cli-bundle/focused-chunks/chunk-MG7C3JUY.js +2 -0
  72. package/dist/cli-bundle/focused-chunks/{chunk-F3X6UWMI.js → chunk-MK4HV4JO.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/{chunk-ZQRCVRGS.js → chunk-NQ7GYFOX.js} +54 -54
  74. package/dist/cli-bundle/focused-chunks/chunk-O7EI33NP.js +91 -0
  75. package/dist/cli-bundle/focused-chunks/{chunk-RY4QEMAE.js → chunk-RFTJZ5VB.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/chunk-SNOXXRSJ.js +2 -0
  77. package/dist/cli-bundle/focused-chunks/chunk-UPJUTP2V.js +12 -0
  78. package/dist/cli-bundle/focused-chunks/{chunk-HJ27QLZV.js → chunk-VWWTIX5L.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/{chunk-HOXIIZEO.js → chunk-XHOBYCVE.js} +2 -2
  80. package/dist/cli-bundle/focused-chunks/chunk-YMGB2O4E.js +81 -0
  81. package/dist/cli-bundle/focused-chunks/item-revision-CTDO4H3I.js +2 -0
  82. package/dist/cli-bundle/focused-chunks/item-transaction-AEAYVVHA.js +2 -0
  83. package/dist/cli-bundle/focused-chunks/mutation-admission-4WM7TNHZ.js +2 -0
  84. package/dist/cli-bundle/focused-chunks/{stage-4SQHVI3O.js → stage-WV7QXR4C.js} +2 -2
  85. package/dist/cli-bundle/main.js +25 -25
  86. package/dist/cli-bundle/sdk-authoring.js +1 -1
  87. package/dist/cli-bundle/sdk-contracts.js +5 -5
  88. package/dist/cli-bundle/sdk-core.js +1 -1
  89. package/dist/cli-bundle/sdk-governance.js +1 -1
  90. package/dist/cli-bundle/sdk-graph.js +1 -1
  91. package/dist/cli-bundle/sdk-merge.js +57 -57
  92. package/dist/cli-bundle/sdk-query.js +1 -1
  93. package/dist/cli-bundle/sdk-runtime.js +1 -1
  94. package/dist/cli-bundle/sdk-testing.js +1 -1
  95. package/dist/cli-bundle/sdk.js +11 -11
  96. package/dist/core/config/positional-value.d.ts +7 -1
  97. package/dist/core/config/positional-value.js +1 -1
  98. package/dist/core/extensions/reserved-host-flags.js +1 -1
  99. package/dist/core/history/history-rewrite.js +1 -1
  100. package/dist/core/item/literal-mutation-input.d.ts +17 -0
  101. package/dist/core/item/literal-mutation-input.js +1 -1
  102. package/dist/core/item/parent-reference-policy.d.ts +8 -4
  103. package/dist/core/item/parent-reference-policy.js +1 -1
  104. package/dist/core/item/sprint-release-format.d.ts +2 -1
  105. package/dist/core/item/sprint-release-format.js +1 -1
  106. package/dist/core/output/mutation-projection.js +1 -1
  107. package/dist/core/shared/command-types.d.ts +7 -0
  108. package/dist/core/store/item-mutation-precondition.d.ts +72 -6
  109. package/dist/core/store/item-mutation-precondition.js +1 -1
  110. package/dist/core/store/item-store.js +1 -1
  111. package/dist/core/store/settings-validator.js +1 -1
  112. package/dist/core/store/settings.d.ts +14 -0
  113. package/dist/core/store/settings.js +5 -4
  114. package/dist/core/telemetry/policy.d.ts +27 -1
  115. package/dist/core/telemetry/policy.js +1 -1
  116. package/dist/core/telemetry/runtime.d.ts +18 -7
  117. package/dist/core/telemetry/runtime.js +4 -4
  118. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  119. package/dist/sdk/cli-contracts/completeness.js +1 -1
  120. package/dist/sdk/cli-contracts/enum-contracts.d.ts +11 -0
  121. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  122. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  123. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  124. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  125. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  126. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +8 -5
  127. package/dist/sdk/cli-contracts.d.ts +1 -1
  128. package/dist/sdk/cli-contracts.js +1 -1
  129. package/dist/sdk/cli-program.js +1 -1
  130. package/dist/sdk/config.d.ts +3 -3
  131. package/dist/sdk/config.js +1 -1
  132. package/dist/sdk/environment/project-runtime-compatibility.js +1 -1
  133. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  134. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  135. package/dist/sdk/governance/health.d.ts +2 -2
  136. package/dist/sdk/governance/health.js +2 -2
  137. package/dist/sdk/governance/validate.js +1 -1
  138. package/dist/sdk/history/salvage.js +3 -3
  139. package/dist/sdk/history-compact.d.ts +7 -1
  140. package/dist/sdk/history-compact.js +1 -1
  141. package/dist/sdk/history-repair.d.ts +2 -1
  142. package/dist/sdk/history-repair.js +1 -1
  143. package/dist/sdk/index.d.ts +6 -1
  144. package/dist/sdk/index.js +1 -1
  145. package/dist/sdk/init.d.ts +4 -4
  146. package/dist/sdk/init.js +8 -8
  147. package/dist/sdk/lifecycle/checkpoint-rollback.d.ts +10 -2
  148. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  149. package/dist/sdk/lifecycle/claim.d.ts +4 -0
  150. package/dist/sdk/lifecycle/claim.js +1 -1
  151. package/dist/sdk/lifecycle/close-many.d.ts +11 -2
  152. package/dist/sdk/lifecycle/close-many.js +1 -1
  153. package/dist/sdk/lifecycle/close.d.ts +25 -0
  154. package/dist/sdk/lifecycle/close.js +1 -1
  155. package/dist/sdk/lifecycle/create.d.ts +7 -5
  156. package/dist/sdk/lifecycle/create.js +1 -1
  157. package/dist/sdk/lifecycle/item-revision.d.ts +162 -0
  158. package/dist/sdk/lifecycle/item-revision.js +2 -0
  159. package/dist/sdk/lifecycle/restore.js +1 -1
  160. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +628 -4
  161. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  162. package/dist/sdk/lifecycle/start-blockers.d.ts +52 -0
  163. package/dist/sdk/lifecycle/start-blockers.js +2 -0
  164. package/dist/sdk/lifecycle/task-composition.d.ts +11 -0
  165. package/dist/sdk/lifecycle/task-composition.js +1 -1
  166. package/dist/sdk/lifecycle/update-many.d.ts +11 -2
  167. package/dist/sdk/lifecycle/update-many.js +1 -1
  168. package/dist/sdk/lifecycle/update.d.ts +5 -4
  169. package/dist/sdk/lifecycle/update.js +2 -2
  170. package/dist/sdk/public-surface.json +1 -1
  171. package/dist/sdk/query/declared-blockers.d.ts +16 -0
  172. package/dist/sdk/query/declared-blockers.js +2 -0
  173. package/dist/sdk/query/get.d.ts +7 -0
  174. package/dist/sdk/query/get.js +1 -1
  175. package/dist/sdk/query/projection-contracts.js +1 -1
  176. package/dist/sdk/runtime/actions.js +1 -1
  177. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  178. package/dist/sdk/runtime-input.d.ts +12 -0
  179. package/dist/sdk/runtime-input.js +1 -1
  180. package/dist/sdk/runtime-primitives.d.ts +1 -0
  181. package/dist/sdk/runtime-primitives.js +1 -1
  182. package/dist/sdk/runtime.d.ts +10 -0
  183. package/dist/sdk/runtime.js +1 -1
  184. package/dist/sdk/structured-mutations.js +1 -1
  185. package/dist/sdk/telemetry.d.ts +1 -1
  186. package/dist/sdk/telemetry.js +2 -2
  187. package/dist/sdk/test/batch.js +2 -2
  188. package/dist/sdk/test/execution.js +2 -2
  189. package/dist/sdk/test/linked-command-detection.js +1 -1
  190. package/dist/sdk/workspace-transaction.d.ts +17 -6
  191. package/dist/sdk/workspace-transaction.js +1 -1
  192. package/dist/types.d.ts +6 -0
  193. package/dist/types.js +1 -1
  194. package/docs/AGENT_GUIDE.md +48 -48
  195. package/docs/AGENT_OUTPUT_ENCODINGS.md +20 -20
  196. package/docs/ASSURANCE.md +10 -10
  197. package/docs/BOUNDED_CONTEXT_READS.md +3 -3
  198. package/docs/CLAUDE_CODE_PLUGIN.md +1 -1
  199. package/docs/CLI_GRAMMAR.md +2 -2
  200. package/docs/COMMANDS.md +144 -32
  201. package/docs/COMMAND_NAMESPACES.md +1 -1
  202. package/docs/CONFIGURATION.md +82 -70
  203. package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +2 -2
  204. package/docs/CONTEXT_INTEGRITY_CONTRACTS.md +5 -5
  205. package/docs/CORPUS_SHAPES.md +1 -1
  206. package/docs/DEPENDENCY_KIND_CONTRACT.md +6 -6
  207. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +5 -5
  208. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +3 -3
  209. package/docs/EXTENSION_AUTHOR_CONTRACTS.md +4 -4
  210. package/docs/HISTORY_ATTESTATION.md +1 -1
  211. package/docs/HISTORY_MAINTENANCE.md +1 -1
  212. package/docs/LIFECYCLE_COMMANDS.md +1 -1
  213. package/docs/MCP_2026_07_28.md +16 -16
  214. package/docs/MCP_2026_07_28_CONFORMANCE.md +19 -19
  215. package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +22 -22
  216. package/docs/MCP_SKILLS_AND_APPS.md +1 -1
  217. package/docs/MERGE_SAFETY.md +6 -6
  218. package/docs/MUTATION_INTEGRITY.md +5 -5
  219. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +14 -14
  220. package/docs/PACKED_FIRST_RUN.md +1 -1
  221. package/docs/QUICKSTART.md +10 -10
  222. package/docs/README.md +21 -21
  223. package/docs/READ_OUTPUT_CONTRACTS.md +9 -9
  224. package/docs/RECURRENCE_RECOVERY_CONTRACTS.md +1 -1
  225. package/docs/RELEASING.md +19 -10
  226. package/docs/SCRIPTING.md +10 -10
  227. package/docs/SDK.md +183 -38
  228. package/docs/SDK_ARTIFACT_OUTPUT.md +1 -1
  229. package/docs/SDK_PRIMITIVE_INVENTORY.md +2 -2
  230. package/docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md +7 -7
  231. package/docs/TESTING.md +1 -1
  232. package/docs/WORKFLOW_POLICIES.md +2 -2
  233. package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +8 -8
  234. package/docs/agent-task-token-baseline.json +1 -1
  235. package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
  236. package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -1
  237. package/docs/generated/FLAG_LEXICON_BUDGETS.md +112 -112
  238. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +13 -4
  239. package/docs/performance/cli-transport-overhead.md +7 -7
  240. package/marketplace.json +1 -1
  241. package/package.json +1 -1
  242. package/packages/pm-beads/package.json +1 -1
  243. package/packages/pm-calendar/package.json +1 -1
  244. package/packages/pm-command-kit/README.md +5 -5
  245. package/packages/pm-command-kit/package.json +1 -1
  246. package/packages/pm-digital-twin/GAP_REPORT.md +16 -16
  247. package/packages/pm-digital-twin/package.json +1 -1
  248. package/packages/pm-governance-audit/package.json +1 -1
  249. package/packages/pm-guide-shell/package.json +1 -1
  250. package/packages/pm-kanban/README.md +1 -1
  251. package/packages/pm-kanban/package.json +1 -1
  252. package/packages/pm-lifecycle-hooks/package.json +1 -1
  253. package/packages/pm-linked-test-adapters/package.json +1 -1
  254. package/packages/pm-search-advanced/package.json +1 -1
  255. package/packages/pm-templates/package.json +1 -1
  256. package/packages/pm-todos/package.json +1 -1
  257. package/packages/pm-vcs/GAP_REPORT.md +1 -1
  258. package/packages/pm-vcs/package.json +1 -1
  259. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  260. package/plugins/pm-claude/README.md +6 -6
  261. package/plugins/pm-claude/package.json +1 -1
  262. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  263. package/plugins/pm-codex/package.json +1 -1
  264. package/plugins/pm-codex/plugin.json +1 -1
  265. package/runtime-dependencies.json +1 -1
  266. package/dist/cli-bundle/chunks/chunk-7ZEFHFAU.js +0 -2
  267. package/dist/cli-bundle/chunks/chunk-B6UTLYLM.js +0 -3
  268. package/dist/cli-bundle/chunks/chunk-HBKD5HZB.js +0 -2
  269. package/dist/cli-bundle/chunks/chunk-L6LCLC37.js +0 -2
  270. package/dist/cli-bundle/chunks/chunk-NR4KABHC.js +0 -31
  271. package/dist/cli-bundle/chunks/chunk-PWD5RY2D.js +0 -2
  272. package/dist/cli-bundle/chunks/chunk-XRMYA4R7.js +0 -20
  273. package/dist/cli-bundle/chunks/chunk-YWS4XV4I.js +0 -6
  274. package/dist/cli-bundle/chunks/chunk-ZOAJNPBL.js +0 -129
  275. package/dist/cli-bundle/chunks/item-transaction-ZHLJTBD7.js +0 -2
  276. package/dist/cli-bundle/chunks/mutation-admission-ZQMRMGIB.js +0 -2
  277. package/dist/cli-bundle/chunks/register-operations-G3QGGQ5Z.js +0 -2
  278. package/dist/cli-bundle/chunks/register-setup-LDXHMNOT.js +0 -2
  279. package/dist/cli-bundle/focused-chunks/chunk-3XGKBVJ3.js +0 -2
  280. package/dist/cli-bundle/focused-chunks/chunk-4HY6EGPB.js +0 -2
  281. package/dist/cli-bundle/focused-chunks/chunk-AK2CI2GI.js +0 -2
  282. package/dist/cli-bundle/focused-chunks/chunk-HUXZCPWT.js +0 -26
  283. package/dist/cli-bundle/focused-chunks/chunk-IKXJ57XA.js +0 -8
  284. package/dist/cli-bundle/focused-chunks/chunk-MOY6KZGJ.js +0 -44
  285. package/dist/cli-bundle/focused-chunks/chunk-PWUTFKSI.js +0 -2
  286. package/dist/cli-bundle/focused-chunks/chunk-PZRB7IXH.js +0 -91
  287. package/dist/cli-bundle/focused-chunks/chunk-WSYPVBKS.js +0 -80
  288. package/dist/cli-bundle/focused-chunks/chunk-WXLG7HZ5.js +0 -3
  289. package/dist/cli-bundle/focused-chunks/chunk-WZDFCVLX.js +0 -12
  290. package/dist/cli-bundle/focused-chunks/chunk-YGO3FWA2.js +0 -2
  291. package/dist/cli-bundle/focused-chunks/chunk-YVLAP3BL.js +0 -23
  292. package/dist/cli-bundle/focused-chunks/chunk-ZYXQACPB.js +0 -2
  293. package/dist/cli-bundle/focused-chunks/item-transaction-PZ2FQ6B2.js +0 -2
  294. package/dist/cli-bundle/focused-chunks/mutation-admission-XOOK6XFH.js +0 -2
@@ -1,44 +0,0 @@
1
- import{n as hu,o as si,p as bu,q as ku,r as sc,s as li,t as Su,u as cc,v as di,y as Vu,z as Yu}from"./chunk-HOXIIZEO.js";import{a as Ju,f as Xu,h as on,m as Qu,o as Tr,r as gi,s as Zu,t as ef,x as tf}from"./chunk-ZYXQACPB.js";import{$ as Y_,Aa as rh,Ab as aa,Ba as oh,Ca as ih,Da as ah,Ea as sh,Fa as ch,Ga as sn,H as O_,Ha as lh,Hb as Ph,I as x_,Ia as dh,Ib as Lh,J as N_,Ja as mh,Jb as $h,K as P_,Ka as ta,L as L_,La as ph,M as $_,Ma as uh,N as F_,Na as fh,Nb as Fh,O as M_,Oa as _h,Ob as Vh,P as D_,Pa as hh,Q as U_,Qa as na,R as G_,Ra as Ht,S as j_,Sa as gh,T as q_,Ta as ra,U as K_,V as z_,W as H_,Wa as zr,X as B_,Y as W_,Z as Bn,_ as V_,bb as yh,cb as wh,db as vh,eb as bh,fb as kh,g as h_,gb as Sh,h as g_,ha as J_,hb as oa,ib as Jc,ja as Q_,jb as Eh,ka as Vc,kb as Xc,lb as Vn,ma as Z_,mb as Ah,na as eh,nb as Th,oa as Yc,ob as Ch,pb as Ih,qb as Rh,rb as Hr,sb as ia,tb as Oh,ub as xh,vb as Yn,wb as Qc,xb as Nh,z as E_,za as nh}from"./chunk-ZQRCVRGS.js";import{a as Kr,b as A_,c as Zi,h as I_,i as R_}from"./chunk-D4XQOMG4.js";import{c as zc}from"./chunk-IDAYTYNN.js";import{A as d_,B as m_,C as Vi,D as p_,E as Yi,a as lt,b as df,c as mf,d as pf,e as Cr,f as n_,g as r_,h as pt,i as v,j as o_,k as i_,m as Ge,n as a_,o as Hi,p as s_,q as c_,r as qc,s as Dr,t as Bi,u as Hn,v as l_,w as Wi,x as be,y as Kc,z as we}from"./chunk-4HY6EGPB.js";import{e as uu,g as fu,h as _u,k as yu,q as vu}from"./chunk-I5FODKYB.js";import{M as Ku,N as yc,O as zu,P as hi,Q as wc,R as Hu,S as Bu,Z as vc,a as tp,b as np,ba as Wu,c as rp,d as op,f as ip}from"./chunk-WXLG7HZ5.js";import{a as b_,b as k_,c as sa,d as ca,e as la}from"./chunk-IKXJ57XA.js";import{K as th,b as S_}from"./chunk-LKN2WGGB.js";import{A as zh,Ea as nl,Ga as Hh,Va as Vr,Xa as Bh,Ya as Wh,b as v_,e as Hc,g as Bc,i as Wc,j as Br,l as Mh,m as Dh,n as Zc,sa as el,v as Uh,w as Gh,x as jh,xa as Wr,y as qh,z as Kh,za as tl}from"./chunk-WZDFCVLX.js";import{A as y_,B as w_,C as ea,H as Wn,h as Ji,k as f_,l as Ur,o as __,w as At,y as qr,z as an}from"./chunk-3XGKBVJ3.js";import{$ as ji,A as Ti,B as Ut,C as ge,D as Mn,F as uf,G as Sc,H as Ir,Ha as Jf,I as Ec,J as Ci,K as kt,L as ff,M as Ii,Q as Ri,R as Oi,U as Mi,V as Di,Va as zn,W as $f,Wa as Xf,X as Ui,Xa as Gc,Y as Gi,Ya as Qf,Z as qt,Za as Zf,_ as Fc,_a as e_,a as yi,b as rf,ba as Ff,bb as jc,c as wi,ca as Mf,cb as t_,d as vi,da as $r,e as bi,f as ki,g as of,i as De,j as af,k as Dt,l as $n,m as Si,n as Fn,o as Ei,p as fe,q as Ai,r as bc,s as Xe,t as sf,u as kc,v as cf,w as de,y as bt,z as lf}from"./chunk-YVLAP3BL.js";import{c as du,f as mu,g as pu,i as ai,j as Ft,k as On,l as Eu,m as Au}from"./chunk-TYHDZUL4.js";import{$ as Fp,A as Fo,Aa as nu,B as hp,Ba as ru,C as gp,Ca as Bo,D as yp,Da as ou,E as Mo,Ea as iu,F as wp,Fa as au,G as vp,Ga as Wo,H as bp,Ha as Vo,I as kp,Ia as Yo,J as Do,Ja as Jo,K as Uo,Ka as Sr,L as Sp,La as su,M as Go,Ma as Xo,Na as Er,O as Ep,Oa as Qo,P as br,Pa as Zo,Q as Ap,Qa as ei,R as Tp,Ra as ti,S as Cp,Sa as cu,T as Ip,Ta as $t,U as Rp,Ua as ni,V as Op,Va as ri,W as xp,Wa as oi,X as Np,Xa as ii,Y as Pp,Z as Lp,_ as $p,_a as lu,aa as Mp,ab as Me,ba as Dp,bb as $,ca as Up,d as rc,da as kr,e as lp,ea as Gp,fa as jp,ga as jo,h as Po,ha as qo,i as oc,ia as qp,j as nn,ja as Kp,ka as zp,l as dp,la as Hp,ma as Bp,na as Wp,oa as Vp,pa as Yp,q as ic,r as ac,ra as Jp,s as In,sa as Xp,t as Lo,ta as Qp,u as $o,ua as Zp,v as mp,va as eu,w as pp,wa as tu,x as up,xa as Ko,y as fp,ya as zo,z as _p,za as Ho}from"./chunk-F3X6UWMI.js";import{J as X_,d as u_,j as Gr,k as jr,l as Xi,m as tt,r as Qi}from"./chunk-PWUTFKSI.js";import{B as Kt,D as zt,F as j,G as ne,H as Bf,J as ye,K as Wf,L as zi,M as et,N as Vf,O as Kn,P as _e,Q as Yf,V as Uc,a as Re,b as Nf,c as Pf,d as jt,f as Ze,g as Lr,h as Gn,i as jf,j as jn,k as qn,l as qf,r as Mr,u as Kf,v as Ki}from"./chunk-PZRB7IXH.js";import{A as Rc,Aa as Gt,B as vf,Ba as Pc,C as dt,Ca as Or,D as Et,Da as xr,Ea as Lc,Fa as mt,Ga as Nr,Ha as Pr,O as Pi,Oa as xf,P as bf,Q as kf,Qa as $c,R as Rr,S as Li,Ta as Lf,Ua as Fi,Va as Qe,Xa as qi,Za as Df,_a as Fr,aa as Oc,ab as Uf,bb as Un,cb as Mc,d as St,db as Dc,ea as Dn,eb as Gf,fa as T,fb as E,g as _f,ga as Sf,gb as Oe,h as Ac,ha as $i,i as hf,ib as zf,j as Tc,jb as Hf,k as gf,ka as Ef,kb as O,la as Af,m as yf,ma as xc,n as xi,pa as Nc,q as Ni,ra as Tf,s as Cc,sa as Cf,ta as If,ua as Rf,v as se,va as Of,w as Ic,x as ce,z as wf,za as Ue}from"./chunk-WSYPVBKS.js";import{b as Ye,c as Io,d as Ro}from"./chunk-RY4QEMAE.js";import{a as gu,c as yt,e as ci,f as wt,g as Mt,h as wu,j as F,k as vt,l as Je,n as Rn}from"./chunk-HJ27QLZV.js";import{e as nf}from"./chunk-4PW5XWVI.js";import{b as _i,c as qu}from"./chunk-AK2CI2GI.js";import{A as Ks,Aa as gt,Ac as Nn,B as zs,C as Hs,Ca as Be,D as Bs,Da as No,Db as Wm,Dc as pi,E as Ws,Eb as Vm,Ee as ju,Fa as en,Fb as Ym,Fc as Ce,Ga as ae,Gb as Jm,Hb as Xm,I as Om,Ib as Qm,Ja as Cn,Jb as Zm,Jc as ui,Lb as yr,Mb as ep,Mc as Cu,Nc as Q,Oc as Iu,Od as S,P as xm,Pc as Pn,Qc as Ru,R as Nm,Sd as fi,Tb as wr,Ub as tc,Uc as Ou,Ud as te,V as Pm,Vb as vr,W as Lm,Wb as ap,Xb as sp,Ya as Te,Yb as cp,Zc as gc,_a as B,_d as Fu,ab as tn,ac as nc,be as ct,ce as Ar,da as Lt,eb as Mm,fa as $m,fb as Dm,fc as Tu,g as Ds,gb as Um,ha as Ys,hb as Gm,i as Us,ia as Js,ib as jm,ie as Mu,j as Gs,jb as qm,kb as Qs,la as Xs,lb as Km,lc,ma as hr,n as To,na as Ie,nb as zm,nc as dc,o as ft,ob as Hm,oc as mc,p as fr,pc,pd as xu,q as _r,qa as P,qc as uc,qd as Nu,qe as Du,r as js,ra as Ae,rb as Zs,rc as fc,rd as Pu,re as Uu,sa as Oo,sb as Bm,sc as _c,sd as Lu,t as Sm,ta as Tn,tb as ec,tc as hc,u as Em,ua as gr,uc as R,ud as $u,ue as Ln,v as Am,va as Fm,w as Tm,wa as A,wc as xn,x as Cm,xa as xo,xc as rn,y as Im,ya as ht,yc as Y,ye as Gu,z as qs,za as ie,zc as mi}from"./chunk-HUXZCPWT.js";import{a as C_}from"./chunk-EGN2HFRU.js";import{b as T_}from"./chunk-FOA7XKWP.js";import{A as l,C as z,D as _t,E as Fe,F as X,I as oe,K as An,m as Co,s as Vs,u as Rm,x as Pt,z as d}from"./chunk-G6ERMFJ5.js";import{readFile as ES}from"node:fs/promises";import AS 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 rl="context-intents.json";function da(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function TS(e,t,n){if(!da(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 Yh(e,t){let n=Array.isArray(e)?e:da(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)=>TS(r,t,o))}async function CS(e){let t=AS.join(e,rl),n;try{n=await ES(t,"utf8")}catch(o){if(_t(o))return[];throw await Hf(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${rl}: ${i}`,{cause:o})}return Yh(r,rl)}function IS(e){if(!da(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return da(n)?n.contextIntents??n.context_intents:void 0}function RS(e){return e.flatMap(t=>{let n=IS(t.module);return n===void 0?[]:Yh(n,`package ${t.name}`)})}async function OS(e){let t=await CS(e.pmRoot),n=RS(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function ma(e,t){let n=await OS(e);return await Uu(n,t)}import{readFile as xS}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 ua(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,de(e,t)}function Jh(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 ol(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function cn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Jn(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=fe(n,"--add");return Object.keys(o).map(i=>i.trim().toLowerCase()).some(i=>i!=="text")?n:o.text?.trim()||n}catch{return n}}function il(e){return typeof e=="object"&&e!==null&&"code"in e}function Jr(e,t){if(!bt(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 NS(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=Ut(),r=bt(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 Jr(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 Jr(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await xS(o,"utf8"),emptyFlag:"--file"}}catch(i){if(il(i)&&_t(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 fa(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 NS(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 Yr(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 Qh(e){return e==="comments"?"--stdin":"--add -"}function PS(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=Qh(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 LS(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> ${Qh(e.collectionKey)}`]})}function $S(e,t,n,r,o,i){let a=cn(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:S(),author:n,text:r})),e.metadata[t]=a,{changedFields:[t],entryIndex:a.length})}async function Xn(e,t,n,r){LS(r,t);let o=A(process.cwd(),n.path);await O(o);let i=await E(o),a=P(i,R()),s=$r(t.limit);if(r.input.mode==="list"){let _=await j(o,e,i.id_prefix,i.item_format,a.type_to_folder);if(!_)throw new l(`Item ${e} not found`,d.NOT_FOUND);let g=await ne(_,{schema:i.schema}),y=cn(g.document.metadata,r.collectionKey);return pa(_.id,r.collectionKey,y,s,t.includeMeta===!0)}let c=T(t.author,i.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,g;try{g=await _e({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=cn(w.metadata,r.collectionKey),k=Xh(r.input.index,b.length,r.collectionKey);return Jh(b[k],"deleted"),b.splice(k,1),w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){Yr(w,r.conflictGuidance)}let y=cn(g.item,r.collectionKey);return pa(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??"";PS(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 _=r.editOp??r.op,g;try{g=await _e({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=cn(w.metadata,r.collectionKey),k=Xh(r.input.index,b.length,r.collectionKey),I=b[k];return Jh(I,"edited"),b[k]={...I,text:p,edited_at:S()},w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){Yr(w,r.conflictGuidance)}let y=cn(g.item,r.collectionKey);return pa(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 _e({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(_){let g=$S(_,r.collectionKey,c,p,t.ifAbsent===!0,r.createEntry);return f=g.entryIndex,{changedFields:g.changedFields}}})}catch(_){Yr(_,r.conflictGuidance)}let h=cn(u.item,r.collectionKey);return pa(u.item.id,r.collectionKey,h,s,t.includeMeta===!0,{action:"add",entryIndex:f,entry:h[f-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Xh(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 FS(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 pa(e,t,n,r,o,i,a=!1){let s=i===void 0||a?ol(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}:{}}:{},...FS(t,i,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]="146c927e-4db7-5a69-a715-c6996983f5f8")}catch{}})();function MS(e){return e===void 0?"unknown":e==="claim"?"claim":"assignment"}async function Zh(e,t,n){let r=[...await Promise.resolve().then(()=>$i(Be(e,t),t)).catch(()=>[])].reverse().find(s=>s.patch.some(c=>c.path==="/metadata/assignee")),o=r?.patch.find(s=>s.path==="/metadata/assignee"),i=o!==void 0&&typeof o.value=="string"&&o.value.trim()===n.trim()?r:void 0,a=MS(i?.op);return{phrase:a==="claim"?`claimed by ${n}`:`assigned to ${n}`,holder:n,source:a,since:i?.ts??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]="4790c318-c305-53d4-895c-e9ac90665376")}catch{}})();function Qn(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Eu({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=vt(e.fromStatus,e.statusRegistry)??e.fromStatus,r=vt(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Au(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,d.USAGE);return`workflow_transition_not_allowed: ${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]="e32c9f13-2e6a-5ac6-a1ce-9c839121441a")}catch{}})();function _a(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new l("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",d.USAGE);let n=typeof e.handoff=="string"?vt(e.handoff,t):void 0;if(n===void 0||Rn(n,t)||n===t.in_progress_status)throw new l("--handoff must name a configured non-terminal status distinct from the in-progress status. Inspect pm schema statuses or add a project queue with pm schema add-status <queue> --role active.",d.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new l("--handoff requires --message with implementation evidence and the next verification step.",d.USAGE);return n}function eg(e,t,n,r,o){if(Rn(e.status,r)||!e.assignee?.trim())throw new l("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",d.CONFLICT);let i=n.governance.workflow_enforcement??"off",a=Qn({enforcement:i,typeWorkflows:i==="off"?[]:On(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),s={from_status:e.status,to_status:t,message:o},c=e.status===t?[]:["status"];return e.status=t,{receipt:s,warnings:a?[a]:[],changedFields: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]="f4c54507-c8b1-5f19-b58a-61186c79c8b0")}catch{}})();function Zn(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:vt("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]="f5335488-184f-5938-a61a-b3fd26fbf3e3")}catch{}})();var tg="no_available_next_item";function DS(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 Xr(e,t,n,r={}){let o=A(process.cwd(),n.path);await O(o);let i=await E(o),a=F(i.schema),s=T(r.author,i.author_default),c=Dn(s),m=null,p=!1,u={},f=[],h=await _e({pmRoot:o,settings:i,id:e,op:"claim",author:s,message:r.message,force:t,skipNoop:!0,async mutate(_){let g=_.metadata.assignee??"",y=_.metadata.claim_principal?.trim()||g;if(m=g.trim().length>0?g:null,Rn(_.metadata.status,a)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&y!==c){if(r.ifAvailable===!0)return p=!0,f.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let N=await Zh(o,_.metadata.id,g);throw new l(`Item ${_.metadata.id} is already ${N.phrase}. Use --force to take over, or --if-available to skip without failing.`,d.CONFLICT,{code:"already_claimed_by",item_id:_.metadata.id,claimed_by:N.holder,claimed_at:N.since,claim_source:N.source,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."]})}f.push(`claim_takeover:${m}->${s}`)}let w={assignee:s,claim_principal:c},b=["assignee","claim_principal"].filter(N=>_.metadata[N]!==w[N]);Object.assign(_.metadata,w);let{changedFields:k,warnings:I,...C}=jS(_.metadata,r.start===!0,i,a);return u=C,f.push(...I),{changedFields:[...b,...k],warnings:f}}});return p||f.push(...await GS({pmRoot:o,settings:i,principal:c,itemId:h.item.id})),{item:h.item,changed_fields:h.changedFields,claimed_by:p&&m!==null?m:s,previous_assignee:m,forced:t,...p?{skipped:!0}:{},...f.length>0?{warnings:f}:{},...u}}var US="claim_semantic_attribution_unrecorded";async function GS(e){try{return await Mh(e),[]}catch{return[US]}}function ng(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new l(n?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",d.USAGE,{code:"missing_required_argument",field:"id",required:"Pass an item id, or --next to select the next available item.",nextSteps:[`Retry as pm claim <id>${r}, or pm claim --next${r}.`]});if(t&&e)throw new l("Specify either an item id or --next, not both",d.USAGE,{code:"ambiguous_option_combination",required:"Pass either an item id or --next.",nextSteps:[`Retry as pm claim ${e}${r} to claim that item, or drop the id to select with --next.`]})}function jS(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(Rn(e.status,r))throw new l(`Cannot start terminal item ${e.id}; reopen it with pm item reopen before starting it`,d.CONFLICT,{code:"terminal_state_conflict",item_id:e.id,why:"Starting work moves an active item into progress; a terminal item must be reopened so its recurrence evidence is recorded.",nextSteps:[`Run pm item reopen ${e.id} "<reason>", then pm claim ${e.id} --start.`]});let o=Zn(r),i=n.governance.workflow_enforcement??"off",a=Qn({enforcement:i,typeWorkflows:i==="off"?[]:On(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:o}),s={from_status:e.status,to_status:o},c=e.status===o?[]:["status"];return e.status=o,{start:s,changedFields:c,warnings:a?[a]:[]}}async function rg(e,t,n={},r={}){let o=qS(n.maxAttempts),i=await E(A(process.cwd(),t.path)),a={...n,author:T(n.author,i.author_default)},s=await Wr({...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 KS(c.slice(0,o),e,t,a)}function qS(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 KS(e,t,n,r={},o=Xr){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(!DS(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:T(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:i,warnings:[tg]};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:tg,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 Qr(e,t,n,r={}){let o=A(process.cwd(),n.path);await O(o);let i=await E(o),a=T(r.author,i.author_default),s=Dn(a),c=r.ownershipReleaseBypass===!0,m=null,p=F(i.schema),u=_a(r,p);if(u!==void 0&&c)throw new l("Ownership-release bypass only clears ownership; it cannot change a handoff status.",d.USAGE);let f,h;try{h=await _e({pmRoot:o,settings:i,id:e,op:"release",author:a,message:r.message,force:t,bypassAssigneeConflict:c,mutate(g){m=g.metadata.assignee??null;let y=u===void 0?void 0:eg(g.metadata,u,i,p,r.message);return f=y?.receipt,!m&&!g.metadata.claim_principal?{changedFields:[]}:(delete g.metadata.assignee,delete g.metadata.claim_principal,{changedFields:["assignee","claim_principal",...y?.changedFields??[]],warnings:y?.warnings})}})}catch(g){Yr(g,{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 Dh({pmRoot:o,principal:s,itemId:h.item.id});let _=Ic(h.item.status,p)===Ic(p.in_progress_status,p);return{item:h.item,released_by:a,changed_fields:h.changedFields,previous_assignee:m,forced:t,...f===void 0?{}:{handoff:f},...h.warnings.length>0||_?{warnings:[...h.warnings,..._?["released_unclaimed_in_progress"]:[]]}:{},..._?{suggestions:[`${h.item.id} remains ${h.item.status} and unclaimed. If work is paused, run pm release ${h.item.id} --pause to move it to ${p.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]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function zS(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 HS(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 BS(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 og(e=Li,t=Rr){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 BU(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 ig(e,t=Rr,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 WU(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 VU(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=zS(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&&HS(i,a,r)?a.children.push(i):o.push(i)}return BS(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]="2661c74e-3e73-50f5-80a2-f103ff0cf2d4")}catch{}})();var ag=100;function tr(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 WS(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=ag?t:`${t.slice(0,ag-3)}...`}function sg(e){return e.map((t,n)=>`${n+1}. ${WS(t)}`).join("; ")}function VS(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 YS(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function cg(e,t){let n=VS(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)YS(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: ${sg(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=tr(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: ${sg(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]="1ce8c06c-cdc7-57bb-b4c3-477b2e07d71c")}catch{}})();var mn=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",Kr,A_,"FORCE_COLOR"]),ya=/^[A-Za-z_][A-Za-z0-9_]*$/,dn=["schema","tracker","auto","none"],lg=["source","isolated","snapshot"];function Zr(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(!ya.test(a))throw new l(`${t} env_set key "${a}" is invalid`,d.USAGE);if(mn.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 eo(e,t){if(!e)return;let n=zn(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(!ya.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(mn.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function wa(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 va(e,t){if(!e)return;let n=e.trim().toLowerCase();if(dn.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${dn.join(", ")}`,d.USAGE)}function pn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(lg.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${lg.join(", ")}`,d.USAGE)}function un(e){if(!e)return;let t=zn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function nr(e,t,n){let r=un(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 ba(e,t){if(!e)return;let n=ge(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 ka(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 Sa(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 JS=new Set(kt);function Ea(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function XS(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let a=o.toLowerCase();if(!JS.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: ${kt.join(", ")}.`);return n}function ln(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 ha(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 dg(e,t,n){let r=ha(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 ga(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 QS(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:ga(n,"timeout_seconds",t),i=r===void 0?void 0:ga(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 ZS(e,t){let n=ln(e,"scope",t);if(n===void 0)return"project";if(!ft.includes(n))throw t(`field "scope" must be one of: ${ft.join(", ")}`);return n}function eE(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Ea(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(!ya.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(mn.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 tE(e,t){let n=ha(e,"env_clear",t);if(n){for(let r of n){if(!ya.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(mn.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function nE(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 rE(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=ga(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 oE(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Ea(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 iE(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Ea(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]=ga(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function aE(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!Ea(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${kt.join(", ")}.`);let o=XS(e,r),i=ln(o,"command",r),a=ln(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=ln(o,"path",r),m=ln(o,"pm_context_mode",r);if(m!==void 0&&!dn.includes(m))throw r(`field "pm_context_mode" must be one of: ${dn.join(", ")}`);let p=pn(ln(o,"workspace_context_mode",r),`${n} ${t}`),u=ln(o,"note",r);return{command:s,path:c!==void 0&&c.length>0?c:void 0,scope:ZS(o,r),timeout_seconds:QS(o,r),pm_context_mode:m,workspace_context_mode:p,env_set:eE(o,r),env_clear:tE(o,r),shared_host_safe:nE(o,"shared_host_safe",r),assert_stdout_contains:ha(o,"assert_stdout_contains",r),assert_stdout_regex:dg(o,"assert_stdout_regex",r),assert_stderr_contains:ha(o,"assert_stderr_contains",r),assert_stderr_regex:dg(o,"assert_stderr_regex",r),assert_stdout_min_lines:rE(o,r),assert_json_field_equals:oE(o,r),assert_json_field_gte:iE(o,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function to(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)=>aE(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]="f75d72fe-b7f5-576d-b6c1-1cd94e3288b3")}catch{}})();var al=["command","cmd"],no=Object.freeze(kt.filter(e=>!["command","cmd","timeout"].includes(e)));function mg(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:tr(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 pg(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 sE(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=tr(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 ug(e,t){let n=Object.keys(e),r=n.filter(o=>!no.includes(o));if(n.length===0&&!t||r.length>0)throw new l("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",d.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...r.length>0?{field:r[0]}:{},required:`Patch at least one editable field: ${no.join(", ")}.`,recovery:{allowed_values:[...no]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new l("scope is required and cannot be cleared",d.USAGE)}function cE(e,t,n){let r={};for(let o of no){let i=t[o]!==void 0?t[o]:e[o];i!=null&&(r[o]=i)}return{command:n,...r}}function Aa(e){return{field:e,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function lE(e,t,n){let r=al.filter(i=>Object.hasOwn(e,i)).map(i=>e[i]),o=typeof e[t]=="string"?e[t].trim():"";if(r.length>1&&r.some(i=>typeof i!="string"||i.trim()!==o))throw new l("--set-json sets command and cmd to different values; send one command",d.USAGE,{code:"linked_test_command_immutable",...Aa(t),nextSteps:["Send the replacement command once, as command."]});if(o.length===0||o===n.command)throw new l(o.length===0?`--set-json cannot set ${t}: a linked test's command is its immutable identity`:`--set-json ${t} repeats the selected entry's command; omit it to edit only metadata`,d.USAGE,{code:"linked_test_command_immutable",...Aa(t),nextSteps:[`Patch only editable fields: ${no.join(", ")}.`]});return Hr(o),o}function dE(e){let{id:t,tests:n,index:r,identityKey:o,otherFields:i,requested:a,global:s}=e;ug(i,!0);let c=cE(n[r],i,a),m=to(JSON.stringify(c),"--add-json")[0];Ec(m);let p=n.findIndex((u,f)=>f!==r&&Ci(u,m));if(p>=0)throw new l(`--set-json cannot change ${o}: linked test ${p+1} already has the requested identity, so a replacement would merge into it`,d.USAGE,{code:"linked_test_command_immutable",...Aa(o),nextSteps:[`Edit linked test ${p+1} instead: ${Q([...Pn(s),"test",t,"--update-index",String(p+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${Q([...Pn(s),"test",t,"--remove-index",String(r+1)])}`]});return c}function mE(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function pE(e){let{id:t,tests:n,index:r,patch:o,global:i,controls:a}=e;if(typeof o!="object"||o===null||Array.isArray(o))return;let s=o,c=al.find(g=>Object.hasOwn(s,g));if(c===void 0)return;let m=n[r],p=lE(s,c,m),u=Object.fromEntries(Object.entries(s).filter(([g])=>!al.includes(g))),f=dE({id:t,tests:n,index:r,identityKey:c,otherFields:u,requested:p,global:i}),h=m.command!==void 0&&n.filter(g=>g.command===m.command).length===1?["--remove",`command=${m.command}`]:["--remove-index",String(r+1)],_=[...Pn(i),"test",t,...h,"--add-json",JSON.stringify(f),...mE(a)];throw new l(`--set-json cannot change ${c}: a linked test's command is its immutable identity; replace the entry instead`,d.USAGE,{code:"linked_test_command_immutable",...Aa(c),recovery:{suggested_retry:Q(_),suggested_retry_args:_},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(t)}, { ${h[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function uE(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);ug(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([s])=>kt.includes(s))),o=wf(to(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]);Ec(o);let i=n.filter(s=>!ae(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 fg(e,t,n={}){let r=A(process.cwd(),n.path);await O(r);let o=await E(r),i=T(t.author,o.author_default),a=P(o,R()),s=0,c=[],m=await Kn({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??[],h=sE(f,t.selector);pE({id:u.metadata.id,tests:f,index:h,patch:t.patch,global:n,controls:t});let _=uE(f[h],t.patch);return s=h+1,c=_.fields,_.fields.length===0?{changedFields:[]}:(u.metadata.tests=f.map((g,y)=>y===h?{..._.test,updated_by:i,updated_at:S()}: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}}(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 fE(){return{metadata:{},body:""}}import{AsyncLocalStorage as KD}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]="cf9867e5-2739-5bb0-b2f0-c432199942b6")}catch{}})();var _E=vc("list").properties.outputSession,hE={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:{..._E},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},_g={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."}},hg={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},me={type:"string",description:"pm item id, for example pm-abc1."},gE=`Operation name (one of): ${ec.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,yE={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."}},wE={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 U(e,t=[]){return{...hg,properties:{...hg.properties,...e},required:t}}var vE=[{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:U({action:{type:"string",enum:[...ec],description:gE},id:me,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."},...hE},["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:U({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:U({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:U({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:U({query:{type:"string"},options:{type:"object"},...wE},["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:U({options:{type:"object"},...yE})},{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:U({id:me,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:U({verify:{type:"boolean",description:"Verify complete selected authoritative history chains."},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:U({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, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:U({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:me,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"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},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"}},["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:U({id:me,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:U({id:me,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:U({id:me,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:U({id:me,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:U({id:me,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:U({id:me,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:U({id:me,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:U({id:me,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:U({id:me,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:U({id:me,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:U({id:me,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:U({id:me,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:U({id:me,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:U({subcommand:{type:"string",enum:[...Km]},id:me,target:me,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:U({id:me,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:U({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:U({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:U({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:U({..._g,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:[...Gs]},description:`Lifecycle roles for add-status: ${Gs.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:_g}},["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:U({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:U({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:U({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."}})}],bE={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"},kE=vE.map(e=>{let t=bE[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:vc(t,{properties:n,required:r})}});function gg(){return kE.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]="bcdd81cd-9922-5292-b762-0e19da0e408c")}catch{}})();var yg=new Map([["activity",["--limit","--after","--full"]],["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"]]]),SE=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Ig=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Ca=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"]),fn=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"]),Rg=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"]]),Og=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"]]),xg=new Map([...Og.entries()].flatMap(([e,t])=>Tt(t).map(n=>[n,e]))),Ng=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],ll=new Map(Ng.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),EE=10,AE=20,wg=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."]]),Pg=[["init",Ep],["install",Tp],["uninstall",Cp],["explore",Ip],["manage",Lp],["describe",Rp],["reload",$p],["doctor",Fp],["catalog",Mp],["adopt",Dp],["adopt-all",Op],["activate",xp],["deactivate",Np],["migrate",Pp]],TE=[...Pg.map(([e,t])=>e==="init"?[e,Ap]:[e,t]),["upgrade",kr]],CE=[...Pg.map(([e,t])=>[`extension ${e}`,t]),...TE.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Uo],["config",Sp],["extension",Go],["package",br],["packages",br],["install",Up],["create",Bo],["item mutate",ou],["item complete",iu],["item reopen",au],["copy",Wo],["focus",Vo],["update",Yo],["update-many",Jo],["upgrade",kr],["calendar",Sr],["cal",Sr],["context",Er],["ctx",Er],["get",Qo],["search",ri],["eval",cu],["events",Xo],["workspace",$t],["workspace position",[]],["workspace snapshot",$t],["workspace snapshot create",$t],["workspace snapshot list",$t],["workspace snapshot inspect",$t],["workspace snapshot restore",$t],["workspace snapshot delete",$t],["next",ni],["aggregate",$o],["deps",ei],["graph",ti],["guide",Zo],["reindex",Gp],["history",Fo],["history-compact",wp],["history-attest",vp],["history-redact",gp],["history-repair",yp],["history-author-acknowledge",Mo],["merge",hp],["schema",bp],["profile",kp],["plan",Do],["restore",Kp],["delete",zp],["close",jp],["close-many",jo],["append",qo],["claim",qp],["release",Hp],["start-task",Bp],["pause-task",Wp],["close-task",Vp],["comments",mp],["notes",pp],["learnings",up],["files",fp],["docs",_p],["test",Xp],["test-runs-worker",[]],["test-all",Qp],["telemetry",Zp],["test-runs",eu],["gc",tu],["stats",Ko],["ops",[]],["duplicates",zo],["validate",nu],["health",Ho],["assurance",ru],...lu,["contracts",oi],["completion",ii],["activity",su],...[...Ig].map(e=>[e,Lo])],ro=new Map(CE);for(let{alias:e,canonical:t}of Te){let n=ro.get(e);n!==void 0&&ro.set(t,n)}function IE(e){return xg.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function vg(e){let t=Te.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Qs.includes(e)?ke(e):e.startsWith("extension-")?ke(`extension ${e.slice(10)}`):e.startsWith("package-")?ke(`package ${e.slice(8)}`):e.startsWith("item-")?ke(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ke(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ke(`templates ${e.slice(10)}`):Ca.has(e)?Og.get(e)??ke(e):null}function RE(e,t){let n=B(t);return n!==t||Te.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:Tt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function Tt(e){return e.split("|").map(t=>ke(t)).filter(t=>t.length>0)}function OE(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let i of Tt(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 Ta(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function oo(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function xE(e,t){if(!t)return{...e};let n=oo(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 sl(e,t){let n=oo(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 ke(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Lg(e){return e.replace(/\s+/g,"-")}function Bt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function bg(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=Bt(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function cl(e,t,n){n&&(e[t]=!0)}function kg(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?Om(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function NE(e){let t=kg(e.long,"long"),n=kg(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),cl(o,"required",e.required===!0),cl(o,"repeatable",e.repeatable===!0),cl(o,"list",e.list===!0),e.default!==void 0&&(o.default=e.default);let i=Bt(e.description);i&&(o.description=i);let a=ep(e);o.value_arity=a.value_arity;let s=Bt(e.value_name)??a.value_name;s&&(o.value_name=s);let c=a.value_type??(a.value_name?"string":null);return c&&(o.value_type=c),o}function $g(e){let t=new Map;for(let r of e){let o=ke(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=NE(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 PE(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...ac.filter(({flag:n})=>n.startsWith("--output-"))]}}function LE(e){let t=$g(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let a=ke(i.command);if(a.length===0)continue;let s=Bt(i.action)??Lg(a),c=Array.isArray(i.arguments)?i.arguments.map(m=>{let p=Bt(m.name);return p?{name:p,required:m.required===!0,variadic:m.variadic===!0,description:Bt(m.description)}:null}).filter(m=>m!==null):[];n.set(a,{...i.tier===void 0?{}:{tier:i.tier},...PE(i,t.get(a)?.flags??[]),command:a,action:s,source:{layer:i.layer,name:i.name},description:Bt(i.description),intent:Bt(i.intent),arguments:c,examples:bg(i.examples),failure_hints:bg(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(ke(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($E(i,a,t.get(i)?.flags??[]))}return o}function $E(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Lg(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function FE(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 ME(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 DE(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}}:{},...e.default!==void 0?{default:e.default}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function UE(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]=ME(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=FE(o);!i||n[i]!==void 0||(n[i]=ac.some(a=>a.flag===o.flag&&a.flag.startsWith("--output-"))?Ku[i]:DE(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 GE(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 jE(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&&GE(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 qE(e,t=E){let n={mode:Pt.extensions.policy.mode,trust_mode:Pt.extensions.policy.trust_mode,default_sandbox_profile:Pt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=A(process.cwd(),e.path);if(!await z(ie(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await wr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),a=await vr({...i,loaded:i.loaded});return{handlers:new Set(a.commands.handlers.map(s=>ke(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 KE(e,t={}){let n=new Map;for(let r of Zs){let o=Ca.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=vg(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of Ca)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:vg(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:Te.find(o=>o.alias===r.command)?.canonical??ke(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function zE(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&&(!fn.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?Tt(e.command_path):[],r=n.some(a=>t.handlers.has(a)||t.handlers.has(B(a))),o=n.map(a=>Rg.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 Fg(e){let t=ro.get(e)??In,n=Me(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function HE(e){return fn.has(B(e))?!1:ro.has(e)}function BE(e){return Ig.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Sg(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function WE(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function VE(e){let t=new Map;for(let r of e.definitions){let o=Sg(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(s=>WE(s)).find(s=>s!==null),a=r.cli_aliases.map(s=>Sg(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,ic(o.flags));return n}function Eg(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 ic(n)}function YE(e,t,n,r,o){let i=new Map(t);for(let{alias:a,canonical:s}of Te){let c=t.get(s)??t.get(a);c&&(i.set(a,c),i.set(s,c))}return e.map(a=>{let s=HE(a),c=s?Fg(a):[],m=n.get(BE(a))??[],p=i.get(a),u=Eg(c,m),f=Eg(u,p?.flags??[]),h=c.length>0&&(p?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:a,flags:f,...r?{canonical_command:Dg(a),visibility:Mg(a,o),positionals:lp(a)?.slots??[],flag_invocations:Tr(a,f)}:{},provider:h,extension_sources:p?.sources}}).sort((a,s)=>a.command.localeCompare(s.command))}function JE(e,t=tn){let n=new Set(e),r=new Map;for(let o of Ng){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 XE(){return{create_string_options:zu,create_repeatable_options:hi,update_string_options:Hu,update_repeatable_options:Bu,list_string_options:tp,search_string_options:np,calendar_string_options:rp,context_string_options:op,activity_string_options:ip}}function Ag(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=>Ie("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 QE(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){let o=e.by_type[r];t[r]=Ag(o,"strict"),n[r]=Ag(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function ZE(e,t){let n=oo(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 eA(e){let t=Ta(e.action)!==void 0||Ta(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=Ta(e.action),p=Ta(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 tA(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 nA(e,t=E){try{return await t(e)}catch{return structuredClone(Pt)}}async function rA(e,t,n){let r=await nA(t),o=await qE(e),i=P(r,o.registrations??R()),a=Je(r.schema),s=LE(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:F(r.schema),runtimeFieldRegistry:a,runtimeFieldFlagMap:VE(a),createRequiredOptionContracts:QE(i),extensionContracts:s,mergedExtensionContracts:jE(s.filter(c=>Ia(n,c.command,s))),extensionFlagMap:$g(o.flagRegistrations)}}function Tg(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Ca.has(e.selectedAction)||e.selectedCommand!==void 0&&fn.has(B(e.selectedCommand)))}function oA(e,t){let n=KE(t,{includePackageOwnedActions:Tg(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Bm);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(i=>i.action===o.action)?.tier??gi(o.action))!=="internal"))}return Tg(e)&&e.selectedCommand!==void 0&&fn.has(B(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:IE(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function iA(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 aA(e,t){return[...new Set([...Qs.filter(n=>!fn.has(B(n))),...[...ro.keys()].filter(n=>!fn.has(B(n))),...e.flatMap(n=>n.command_path?Tt(n.command_path).filter(r=>n.provider==="extension"||!fn.has(B(r))||t.some(o=>o.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let o=Te.find(i=>i.alias===r||i.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>ke(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function sA(e,t){let n=t.slice(0,EE),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,AE),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 cA(e,t){return new l(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm package 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 package install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm package install ${t} --project`],recovery:{suggested_retry:`pm package install ${t} --project`}})}function lA(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 dA(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 sA(e.selectedCommand,n);let r=Rg.get(B(e.selectedCommand));throw r?cA(e.selectedCommand,r):lA(e.selectedCommand)}function mA(e,t){let n=oA(e,t.mergedExtensionContracts);iA(e,n);let r=aA(n,t.mergedExtensionContracts);dA(e,r);let o=e.selectedCommand?xg.get(B(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(m=>o?m.action===o:RE(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=>zE(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 pA(e){return new Set(oo(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 uA(e){let t=Wu,n=oo(t),r=pA(t),o=e.filter(i=>!r.has(i.action)).map(i=>UE(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function Cg(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?xE(n,e.selectedAction):e.selectedCommand?sl(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):sl(n,r);return e.runtimeOnly&&!e.selectedAction?sl(o,new Set(t.actions)):o}function fA(e,t,n){let r=uA(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?ZE(Cg(e,n,r),t.createRequiredOptionContracts):Cg(e,n,r);return{mergedSchema:r,filteredSchema:o}}function _A(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?OE(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Mg(e,t){return t.find(n=>B(n.command)===B(e))?.tier??gi(e)}function Ia(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||Mg(t,n)!=="internal"}function hA(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(tn.filter(o=>o.hidden&&(o.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(o=>o.alias));if(e.summary&&!e.fullOutput)for(let o of ll.keys())r.add(o);return t.filter(o=>!r.has(o)&&Ia(e,o,n))}function Dg(e){let t=Te.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":ll.get(n)??n}var gA=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"]]),yA=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function wA(e,t){let n=wg.get(B(e))??(e.includes(" ")?void 0:wg.get(Dg(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>Tt(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=gA.get(i),c=yA.get(e)??a;return{intent:s===void 0||a.length===0?`Run ${e}.`:`${s} ${c}.`,intent_source:"generated"}}function vA(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(ke))].filter(i=>i.length>0).sort((i,a)=>i.localeCompare(a)).map(i=>{let a=gc(i,{generateFallback:!0}),s=i.split(" ")[0],c=ll.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),m=new Set([...Fg(i).map(f=>f.flag),...t.filter(f=>Tt(f.command).some(h=>B(h)===B(i))).flatMap(f=>f.flags.map(h=>h.flag))]),p=(yg.get(B(i))??yg.get(c)??SE).filter(f=>m.has(f)),u=wA(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 bA(e){return e.map(t=>({budget:gc(t,{generateFallback:!0}),envelope:tf(t)}))}function kA(e){let t=new Map;for(let n of e){let r=Xu(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 SA(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>Tt(r.command).some(o=>B(o)===B(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>Tt(o.command).some(i=>r.has(i)))}return t.extensionContracts.filter(r=>Ia(e,r.command,t.extensionContracts))}function EA(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 AA(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=nf);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:[...Mm],services:[...Dm],policy_modes:[...Um],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...qm],trust_modes:[...Gm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...jm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Sm],create_modes:[...Em],close_validation_modes:[...Am],workflow_enforcement_modes:[...Tm]},e.relationship_kind_contracts=[...xm,...(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 TA(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 CA(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=YE(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(cp).filter(([a])=>i.has(a)).map(([a,s])=>({command:a,default:s,brief_fields:[...sp,"priority"],compact_fields:[...ap]}))}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 IA(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=XE();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function RA(e,t,n,r){e.command_summaries=vA(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Ru],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(ke))].filter(o=>Nu(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...Lu(o).keys()]}))}:{}},e.grammar_contracts={nouns:nn.nouns,shared_verbs:nn.shared_verbs,scope_before_verb:nn.scope_before_verb,visible_top_level_ceiling:nn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:nn.ceiling_raise_requires_pm_item,positional_shape_budget:nn.positional_shape_budget,positional_shape_count:new Set(oc.map(({slots:o})=>dp(o))).size,positional_action_count:rc.length,positional_action_parents:[...new Set(rc.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:oc}:{}}}async function dl(e,t){let n=eA(e);tA(n);let r=A(process.cwd(),t.path),o=await rA(t,r,n),i=mA(n,o),a=fA(n,o,i),s=_A(n,i),c=hA(n,s,o.extensionContracts),m=EA(n,a,i,c),p=SA(n,o,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&RA(m,c,p,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return m;let f=JE(i.commandCatalog.filter(h=>Ia(n,h,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||AA(m,o,n),TA(m,n,a,p),CA(m,n,o,c,f),IA(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...g_],gate_triggers:[...h_]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=Po.map(h=>({...h,reason:h.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=gg(),m.context_intents=Du(),m.read_output_dimensions=xu,m.error_codes=Qu,m.command_output_contracts=bA(c),m.diagnostic_output_contracts=Ou,m.command_exit_contracts={vocabulary:Ju,command_sets:kA(c)}),m}(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 Ug(e,t,n=Mu){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 OA}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]="971103f5-a101-5e45-a607-ebebbaafe7f5")}catch{}})();function ml(e){let t=Nm();for(let n of e)t.register(n);return t}function xA(e,t,n=[]){if(n.length===0)return e;let r=JSON.parse(e),o=JSON.parse(Dc(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 ae(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
2
- `}function Gg(e,t,n,r){return{fitOutputEnvelope:v_,client:t,isItemNotFoundError:o=>Uc(o)&&o.exitCode===d.NOT_FOUND,getItemAt:(o,i)=>w_(o,i,{pmRoot:e}),readSettingsSection:(o,i)=>Zf(e,o,i),writeSettingsSection:(o,i,a)=>e_(e,o,i,{author:n,...a}),openRelationshipEventStore:o=>k_.open({pmRoot:e,nodes:o.nodes,registry:ml(o.definitions),...o.relativePath===void 0?{}:{relativePath:o.relativePath}}),createRelationshipGraph:o=>new Lm(o.nodes,o.edges,ml(o.definitions)),analyzeRelationshipImpact:(o,i,a)=>S_(o,i,a),validateRelationshipEvents:o=>{let i=new b_(o.nodes,{registry:ml(o.definitions)});return o.events.map(a=>i.append({...a,expectedVersion:i.version}))},commitWorkspaceTransaction:o=>E_({...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 Fr(e,()=>E(e)):await E(e);try{let a=await Fi({pmRoot:e,filePath:ie(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${OA("sha256").update(r).digest("hex").slice(0,16)}:${o.operationId}`,author:T(n,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=qi(c);if(!m.success)throw new l("Workspace settings mutation requires a valid initialized settings.json.",d.USAGE);let p=Mc(m.data),u=await o.mutate(structuredClone(p));if(!qi(u).success)throw new l("Workspace settings mutation returned invalid settings.json.",d.USAGE);let f=ae(p,u)?s:Dc(u,{source:{raw:c,validated:m.data}});f=xA(f,u,o.replaceSubtrees);let h=qi(JSON.parse(f));if(!h.success)throw new l("Workspace settings mutation serialized invalid settings.json.",d.USAGE);return{raw:f,result:o.includePreview===!0?Mc(h.data):void 0}}});return a.changed&&o.dryRun!==!0&&await Y({path:ie(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{Df(e)}}}}import NA from"node:fs/promises";import Z from"node:path";import PA from"node:readline/promises";import{stdin as LA,stdout as je}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 ul=Symbol.for("pm.sdk.init-invocation-cwd");var $A=()=>PA.createInterface({input:LA,output:je});function FA(){return structuredClone(Pt)}var MA=["minimal","default","strict"];function qg(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: ${MA.join(", ")}`,d.USAGE)}function DA(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return fu(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${uu.join(", ")}`,d.USAGE)}}}function UA(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 pl(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:Z.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function GA(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||pl(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=Z.resolve(e,o),p=Z.join(m,".agents","pm");return{pmRoot:p,prefixArg:n,target:{mode:"workspace-path",tracker_root:p,workspace_root:m}}}if(t.path===void 0&&pl(n)){let m=Z.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let i=A(e,t.path),a=Z.join(Z.resolve(e),".agents","pm"),s=Z.dirname(Z.dirname(i)),c=Z.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:Z.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function jA(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(pl(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&&jt(e)!==jt(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 ${jt(e)}`,`pm init --id-prefix ${jt(t)}`]});return t}function qA(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: ${V_.join(", ")}`,d.USAGE)}function KA(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Kg(e,t){let n=Rm[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function zA(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function HA(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(zA).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function BA(e,t,n){let r=ci(t.schema),o=wt(e,r.files.types,yt.types),i=mu(await X(o)),a=[],s=[];for(let c of _u(n)){let m=pu(i,c);i=m.file,(m.replaced?s:a).push(m.definition.name)}return await Qe({pmRoot:e,filePath:o,raw:ai(i),op:"init:type-preset",author:T(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 WA(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",Z.join(".agents","pm")];for(let n of t)if(await z(Z.join(e,n)))return!0;return!1}async function VA(e,t,n){if(!t||n||await z(Z.join(e,"settings.json"))||!await WA(e))return;let r=Z.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 zg(e,t){let n=[],r=[];for(let o of t){let i=o?Z.join(e,o):e,a=await z(i);await NA.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 YA(e,t){let n=$A();try{je.write(`pm init setup wizard (agent-optimized)
3
- `),je.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
4
-
5
- `),je.write(`1/3 Item ID prefix
6
- `),je.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?jt(r):e;je.write(`
8
- 2/3 Governance preset
9
- `),je.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
10
- `),je.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
11
- `),je.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=qg(a)}catch{je.write(`Unrecognized governance preset "${a}"; using minimal.
13
- `)}je.write(`
14
- 3/3 Project telemetry
15
- `),je.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=KA(m,t);return je.write(`
17
- `),{prefix:o,preset:s,telemetry_enabled:p}}finally{n.close()}}function JA(e){return{presetFromOption:qg(e.preset),useDefaults:e.defaults===!0,authorFromOption:UA(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:qA(e.agentGuidance),typePreset:DA(e.typePreset)}}function XA(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 QA(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 ZA(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&&(Kg(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 eT(e){let t=await E(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=XA({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return QA(e.settingsPath,n,e.options.force===!0,e.target),ZA({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Oe(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function tT(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 YA(t,Pt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let i=n??"minimal",a=FA();a.id_prefix=t,Kg(a,i);let s=Oc()?.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 Oe(e.pmRoot,a),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function jg(e){return e.settingsExists?await eT(e):await tT({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function nT(e){let t=await Y_({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 Oe(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function rT(e,t){let n=[],r=[],o=await wu(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 oT(e){if(e.typePreset===void 0)return;let t=await BA(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 iT(e){let t=P(e.settings,R()).folders.filter(r=>!Vs.includes(r)),n=await zg(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function aT(e){let t=Z.resolve(e.tracker_root),n=Z.dirname(t);return Z.basename(t)==="pm"&&Z.basename(n)===".agents"?Z.dirname(n):e.workspace_root}async function sT(e,t,n,r){if(!e)return;let o=await Bn("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let i=HA(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 cT(e){let t=r=>Q([...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 lT(e,t,n,r=R_){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 dT(e,t,n,r){if(e==null||n==="status")return;let o=await zc(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function io(e,t,n={}){let r=t[ul],o=typeof r=="string"?r:process.cwd(),i=GA(o,t,e,n.workspace),a=i.pmRoot;e=jA(i.prefixArg,n.idPrefix);let s=JA(n);await VA(a,i.target.mode==="tracker-path",n.force===!0);let c=[],m=[],p=Z.join(a,"settings.json"),u=await z(p),f;u&&(f=await jg({pmRoot:a,settingsPath:p,settingsExists:u,normalizedPrefix:jt(e),prefixArg:e,options:n,normalizedOptions:s,warnings:m,target:i.target}));let h=await zg(a,Vs);c.push(...h.createdDirs),m.push(...h.warnings),f??=await jg({pmRoot:a,settingsPath:p,settingsExists:u,normalizedPrefix:jt(e),prefixArg:e,options:n,normalizedOptions:s,warnings:m,target:i.target});let{settings:_}=f,g=aT(i.target),y=await Zi(g??Z.dirname(a)),w=g??y,b=await nT({pmRoot:a,cwd:w??o,agentGuidanceMode:s.agentGuidanceMode,settings:_,warnings:m}),k=await rT(a,_);c.push(...k.createdDirs),m.push(...k.warnings);let I=await oT({pmRoot:a,settings:_,typePreset:s.typePreset,warnings:m});I&&(_=await E(a)),await iT({pmRoot:a,settings:_,createdDirs:c,warnings:m}),await dT(w,a,s.agentGuidanceMode,m),!u&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await lT(a,y,m);let C=await sT(s.installBundledPackages,t,a,m),N=cT({installBundledPackages:s.installBundledPackages,registeredTypePreset:I,agentGuidanceNextSteps:b.next_steps,target:i.target});return{ok:!0,path:a,target:i.target,settings:_,created_dirs:c,warnings:m,governance_preset:_.governance.preset,wizard_used:f.wizardUsed,...I?{registered_type_preset:I}:{},...C?{installed_packages:C}:{},next_steps:N,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 Hg(e,t){let n=A(t??process.cwd(),e),r=await E(n);return ye(n,r.item_format,P(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 mT={"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 Bg(e){return Object.fromEntries(zm.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Wg={ctx:{action:"context"},...mT,...Bg("extension"),...Bg("package"),...Object.fromEntries(Hm.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 Vg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function pT(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 fl(e,t){let n=pT(t),r=n==="brief"?n:Vg(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:Vg(e.filters)?e.filters:{},projection:r}}}import{readFile as uT}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 _l(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",bt(e))??"",emptyFlag:"--add"};if(r)return Jr(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 Jr(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await uT(a,"utf8"),emptyFlag:"--file"}}catch(s){if(il(s)&&_t(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 fT(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 _l(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 _l(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 _l(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 Yg(e,t,n){let r=Ut(),o=await fT(t,r),i=o.mode==="add"||o.mode==="edit",a=o.value??"";return Xn(e,t,n,{input:{...o,rawValue:t.add??a,value:i?Jn(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 Jg=new Set(["item_format"]),Xg=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"]),_T=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"]),hT=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),gT={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function yT(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(Jg.has(t)||Xg.has(t)||_T.has(t)||t==="context")return t}function wT(e){let t=e.trim().toLowerCase();return gT[t]??e}function Qg(e,t){let n=yT(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."}:Jg.has(n)?{routable:!0,flag:"format",value:t}:Xg.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:hT.has(n)?wT(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 vT=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Zg(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 bT(e){let t=e?.trim().toLowerCase();if(!t||!vT.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function kT(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function ST(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 ET(e,t){let n=Zg(t.legacy_author),r=bT(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 AT(e,t){if(t.operation==="add")return ET(e,t);if(t.operation==="remove"){let r=Zg(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 hl(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function ey(e,t){let n=e?.version??1,r={...e?.aliases},o=AT(r,t),i={version:o?n+1:n,aliases:kT(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:ST(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]="e8446c93-c40c-572d-86fa-d78535a6f66e")}catch{}})();var ty=["project","global"],Ct={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"]},TT=Object.keys(Ct).map(e=>Ct[e][0]),CT=Object.fromEntries(Object.keys(Ct).flatMap(e=>Ct[e].map(t=>[t,e]))),IT={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)."},RT=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],OT=new Set(["metadata_required_fields",...RT]),xT=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),NT=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),PT=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),LT=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),$T=new Set(["governance_preset","governance_create_default_type"]),sy=e=>OT.has(e),FT=e=>PT.has(e),MT=e=>LT.has(e),DT=e=>$T.has(e);function gl(e){return e==="definition_of_done"||sy(e)}function UT(e){if(ty.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${ty.join(", ")}`,d.USAGE)}function GT(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 jT(e){let t=CT[e];if(t)return t;let n=sc.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${TT.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function qT(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 KT(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 cy(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 zT(e){return wl(e,"test-result-tracking")}function wl(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 ly(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 vl(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 dy(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 my(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 py(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 uy(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 fy(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 _y(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 hy(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 HT={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function ny(e,t){let n=HT[e];if(n)return wl(t,n);switch(e){case"history_missing_stream_policy":return cy(t);case"sprint_release_format_policy":return Fc(t);case"parent_reference_policy":case"governance_parent_reference_policy":return Mi(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return vl(t);case"governance_preset":return dy(t);case"governance_ownership_enforcement":return my(t);case"governance_create_mode_default":return py(t);case"governance_close_validation_default":return uy(t);case"governance_require_close_reason":return hy(t);case"governance_workflow_enforcement":return fy(t);case"governance_force_required_for_stale_lock":return _y(t);case"telemetry_tracking":return ly(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var ry={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"},BT=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function WT(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=>ry[i]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${BT.join(", ")}`,d.USAGE);return[...new Set(r.map(i=>ry[i]))].sort((i,a)=>i.localeCompare(a))}function VT(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 ${Ct[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${Ct[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function YT(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function JT(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 jT(t)}function gy(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var XT={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=>hl(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,next_ranking_policy:e.context.next_ranking_policy,sections:{...e.context.sections}})};function bl(e,t){return XT[t](e)}function xe(e,t){return t.length===0?e:{...e,warnings:t}}async function QT(e,t){let n=process.cwd(),r=e==="project"?A(n,t.path):ht(n),o=ie(r);return e==="project"&&await O(r),{pmRoot:r,settingsPath:o}}function ZT(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 oy(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 eC(e,t,n,r,o){let i=!1,a=e.context,s=[];if(t.defaultDepth!==void 0){let m=t.defaultDepth.trim().toLowerCase();if(!Ws.includes(m))throw new l(`Context --default-depth must be one of ${Ws.join("|")}`,d.USAGE);s.push("context.default_depth"),a.default_depth!==m&&(a.default_depth=m,i=!0)}if(t.activityLimit!==void 0){let m=oy(t.activityLimit,"--activity-limit");s.push("context.activity_limit"),a.activity_limit!==m&&(a.activity_limit=m,i=!0)}if(t.staleThresholdDays!==void 0){let m=oy(t.staleThresholdDays,"--stale-threshold-days");s.push("context.stale_threshold_days"),a.stale_threshold_days!==m&&(a.stale_threshold_days=m,i=!0)}let c=[["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[m,p]of c){let u=ZT(p);if(u!==void 0){let f=m;s.push(`context.sections.${m}`),a.sections[f]!==u&&(a.sections[f]=u,i=!0)}}return(i||Un(e))&&(await Oe(n.pmRoot,e,"config:set:context",{assignedPaths:s}),i=!0),xe({scope:r,key:"context",context_settings:{default_depth:a.default_depth,activity_limit:a.activity_limit,stale_threshold_days:a.stale_threshold_days,next_ranking_policy:a.next_ranking_policy,sections:{...a.sections}},settings_path:n.settingsPath,changed:i},o)}function tC(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 nC(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 tC(t,o,i);gy(n);let a=Qg(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&&ny(n,i.policy)!==ny(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 rC(e){let t=Object.keys(Ct).map(r=>({key:r,aliases:Ct[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":gl(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:gl(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:IT[r],value:bl(e.settings,r)})),n=sc.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:cc(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 oC(e){let t=Object.fromEntries(Object.keys(Ct).map(n=>[n,bl(e.settings,n)]));return xe({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function iC(e,t){let n=bl(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 aC(e,t,n,r){if(t==="get"){let s=cc(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=Su(n,o);if(!i.ok)throw new l(i.error.message,d.USAGE);let a=di(e.settings,n,i.parsed.value)||Un(e.settings);return a&&await Oe(e.target.pmRoot,e.settings,`config:set:${n.path}`,{assignedPaths:[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 ee(e,t,n,r=[]){(t||Un(e.settings))&&(await Oe(e.target.pmRoot,e.settings,n,{assignedPaths:r}),Un(e.settings)&&(e.fallbackRepairWritten=!0))}function iy(e,t,n){return e!==n||t!==n}function he(e,t,n,r){return xe({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function yl(e,t,n,r){return xe({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function ay(e,t,n){let r=P(t,R()),o=await Xf(e,n,"config:set:item_format:migrate",r.type_to_folder,t.schema);return{target_format:o.target_format,scanned:o.scanned,migrated:o.migrated,removed:o.removed,warnings:o.warnings}}async function sC(e,t){let n=KT(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){e.settings.item_format=n;let i={assignedPaths:["item_format"]};Un(e.settings)?(await Oe(e.target.pmRoot,e.settings,"config:set:item_format",i),e.fallbackRepairWritten=!0,o=await ay(e.target.pmRoot,await E(e.target.pmRoot),n)):(o=await ay(e.target.pmRoot,e.settings,n),await Oe(e.target.pmRoot,e.settings,"config:set:item_format",i))}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 cC(e,t,n){if(t==="history_missing_stream_policy"){let i=cy(n.policy),a=e.settings.history.missing_stream!==i;return e.settings.history.missing_stream=i,await ee(e,a,"config:set:history_missing_stream_policy",["history.missing_stream"]),he(e,t,e.settings.history.missing_stream,a)}if(t==="sprint_release_format_policy"){let i=Fc(n.policy),a=e.settings.validation.sprint_release_format!==i;return e.settings.validation.sprint_release_format=i,await ee(e,a,"config:set:sprint_release_format_policy",["validation.sprint_release_format"]),he(e,t,e.settings.validation.sprint_release_format,a)}if(t==="parent_reference_policy"){let i=Mi(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 ee(e,a,"config:set:parent_reference_policy",["validation.parent_reference","governance.preset","governance.parent_reference"]),he(e,t,e.settings.validation.parent_reference,a)}let r=vl(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 ee(e,o,"config:set:metadata_validation_profile",["validation.metadata_profile","governance.preset","governance.metadata_profile"]),he(e,t,e.settings.validation.metadata_profile,o)}async function lC(e,t,n){if(t==="metadata_required_fields"){let a=WT(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 ee(e,s,"config:set:metadata_required_fields",["validation.metadata_required_fields"]),yl(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=VT(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 ee(e,i,`config:set:${t}`,[`validation.${t}`]),yl(e,t,[...r],i)}async function dC(e,t,n){if(t==="governance_preset"){let c=dy(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await ee(e,m,"config:set:governance_preset",["governance.preset"]),he(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 ee(e,c,"config:set:governance_create_default_type",["governance.create_default_type"]),he(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=P(e.settings,R()),a=Ae(o,i);if(!a)throw new l(Ft(o,i.types,Mt(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 ee(e,s,"config:set:governance_create_default_type",["governance.create_default_type"]),he(e,t,e.settings.governance.create_default_type,s)}async function mC(e,t,n){if(t==="governance_ownership_enforcement"){let i=my(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 ee(e,a,"config:set:governance_ownership_enforcement",["governance.preset","governance.ownership_enforcement"]),he(e,t,e.settings.governance.ownership_enforcement,a)}if(t==="governance_create_mode_default"){let i=py(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 ee(e,a,"config:set:governance_create_mode_default",["governance.preset","governance.create_mode_default"]),he(e,t,e.settings.governance.create_mode_default,a)}let r=uy(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 ee(e,o,"config:set:governance_close_validation_default",["governance.preset","governance.close_validation_default"]),he(e,t,e.settings.governance.close_validation_default,o)}async function pC(e,t,n){if(t==="governance_parent_reference_policy"){let i=Mi(n.policy),a=e.settings.governance.preset!=="custom"||iy(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 ee(e,a,"config:set:governance_parent_reference_policy",["governance.preset","governance.parent_reference","validation.parent_reference"]),he(e,t,e.settings.governance.parent_reference,a)}if(t==="governance_metadata_validation_profile"){let i=vl(n.policy),a=e.settings.governance.preset!=="custom"||iy(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 ee(e,a,"config:set:governance_metadata_validation_profile",["governance.preset","governance.metadata_profile","validation.metadata_profile"]),he(e,t,e.settings.governance.metadata_profile,a)}let r=fy(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await ee(e,o,"config:set:governance_workflow_enforcement",["governance.workflow_enforcement"]),he(e,t,e.settings.governance.workflow_enforcement,o)}async function uC(e,t,n){if(t==="governance_require_close_reason"){let i=hy(n.policy)==="enabled",a=e.settings.governance.require_close_reason!==i;return e.settings.governance.require_close_reason=i,await ee(e,a,"config:set:governance_require_close_reason",["governance.require_close_reason"]),he(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",a)}let r=_y(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 ee(e,o,"config:set:governance_force_required_for_stale_lock",["governance.preset","governance.force_required_for_stale_lock"]),he(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function fC(e,t,n){if(t==="test_result_tracking"){let i=zT(n.policy)==="enabled",a=e.settings.testing.record_results_to_items!==i;return e.settings.testing.record_results_to_items=i,await ee(e,a,"config:set:test_result_tracking",["testing.record_results_to_items"]),he(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",a)}if(t==="untrusted_linked_test_execution"){let i=wl(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 ee(e,a,"config:set:untrusted_linked_test_execution",["testing.allow_untrusted_linked_tests"]),he(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",a)}let r=ly(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 ee(e,o,"config:set:telemetry_tracking",["telemetry.enabled","telemetry.first_run_prompt_completed"]),he(e,t,e.settings.telemetry.enabled?"enabled":"disabled",o)}async function _C(e,t,n){let r=qT(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 ee(e,o,"config:set:definition_of_done",["workflow.definition_of_done"]),yl(e,t,[...e.settings.workflow.definition_of_done],o)}function hC(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 gC(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 yC(e,t){let{operation:n,dryRun:r}=hC(t.policy),o=gC(n,t.value),i;try{i=ey(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 ee(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${i.preview.version_after}`,["agent_identity"])),xe({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:hl(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 wC(e,t,n){let r=await vC(e,t,n);return e.fallbackRepairWritten===!0?{...r,changed:!0}:r}async function vC(e,t,n){if(n.clearCriteria===!0&&!gl(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?sC(e,n):t==="context"?eC(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?yC(e,n):t==="definition_of_done"?_C(e,t,n):sy(t)?lC(e,t,n):xT.has(t)?fC(e,t,n):NT.has(t)?uC(e,t,n):FT(t)?mC(e,t,n):MT(t)?pC(e,t,n):DT(t)?dC(e,t,n):cC(e,t,n)}async function yy(e,t,n,r,o,i){let a=UT(e),s=GT(t),c=s==="get"||s==="set"?li(n):void 0,m=c?void 0:JT(s,n),p=nC(s,n,m,c,i,r),u=await QT(a,o),{settings:f,metadata:h,warnings:_}=await Gf(u.pmRoot),g={scope:a,target:u,settings:f,metadata:h,warnings:YT(_)};return c?aC(g,s,c,p):s==="list"?rC(g):s==="export"?oC(g):(gy(m),s==="get"?iC(g,m):wC(g,m,p))}import vy from"node:fs/promises";import by 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 bC(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 kC(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 wy(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return bC(t.ids,n,t.minEntries)}return kC(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 SC(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=Gn(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 EC(e,t){let n=Or(),r=Or();for(let o=0;o<e.length;o+=1){let i=e[o];n=jn(n,i.patch,o+1,i.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function AC(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:Tf.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&Lc(Pr(e.document),r,St(n.hash_algorithm)).includes(n.after_hash))}}function TC(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 CC(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 IC(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=EC(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Gn(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],a=Ue({hashAlgorithm:St(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:mt(Or()),after:mt(t),message:CC(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:Cf(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),s=[If({...a,before_hash:Lc(Or(),i.item_hash_version??1,St(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...r];return e.dryRun||s.push(Ue({nowIso:S(),author:e.author,op:"history_compact",before:mt(n),after:mt(n),message:TC(e.options,e.boundary)})),{rewrittenEntries:s,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function kl(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await qr(n.path),a=await an(r,e,o,i.type_to_folder);return na({pmRoot:r,subject:a,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:s=>RC(a,t,s)})}function RC(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=SC(t.before,o),s=a.compactCount>0,c=!!t.dryRun,m=n.author,p=[];s||p.push("history_compact_noop_before_boundary");let u=AC(n.loadedItem,o);u.matchedChainBefore===!1&&p.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:h,auditEntryAdded:_}=IC({historyEntries:o,boundary:a,changed:s,dryRun:c,author:m,options:t}),g=Gn(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:h,audit_entry_added:_,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((k,I)=>k.localeCompare(I)),generated_at:S()})}}var OC=3;function xC(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=Oi(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:Ri(t)}}function ky(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 NC(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function PC(e){let t=F(e.settings.schema),n=Ji(t),r=await ye(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=by.join(e.pmRoot,"history"),a=[],s=[];if(!await z(i))return{candidates:a,preselectionErrors:s};let c=(await vy.readdir(i)).filter(m=>m.endsWith(".jsonl")).sort((m,p)=>m.localeCompare(p));for(let m of c){let p=by.join(i,m),u=m.slice(0,-6);try{let f=await vy.readFile(p,"utf8");await Nn({path:p,scope:"project"}),a.push({id:u,entries:NC(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 LC(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 kl(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 Sy(e,t){let n=xC(e),{pmRoot:r,settings:o,typeRegistry:i}=await qr(t.path),{candidates:a,preselectionErrors:s}=await PC({pmRoot:r,settings:o,typeToFolder:i.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??OC,p=o.history.compact_policy,u=c==="scan"&&e.allOver===void 0&&p.enabled,f=e.allOver??(u?p.max_entries:void 0),h=wy(a,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),_=!!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 h){let b=await LC({row:w,options:n,dryRun:_,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:_,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:u},totals:y,results:g,generated_at: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]="feb8c44f-a6bd-5a7e-9600-eb5c45c0a5b4")}catch{}})();function Ey(e){let t=e.options.all===!0,n=e.id??v(e.options,"id");return gh(n,t),t?ra(e.options,e.global):Ht(n,e.options,e.global)}function Ay(e){let t=e.options.ids,n=Oi(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:Ri(n),o=Ge(e.options.allOver??e.options.all_over,"history-compact allOver"),i=Ge(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 ky(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?kl(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):Sy({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 Sl 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 Ty(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function $C(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function FC(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=$C(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 MC(e,t){let n=[...new Set(Ty(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),r=[...new Set(Ty(t).map(i=>i.trim()))].filter(i=>i.length>0).map(FC),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 DC(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 UC(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 Iy(e,t,n){let r=e,o=0;for(let i of t){let a=i.kind==="literal"?DC(r,i.value,n):UC(r,i,n);r=a.value,o+=a.replacements}return{value:r,replacements:o}}function Ra(e,t,n){if(typeof e=="string")return Iy(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(o=>{let i=Ra(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=Ra(a,t,n);r+=s.replacements,o[i]=s.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function Cy(e,t,n){let r=0;return{patch:e.map(o=>{if(!Object.prototype.hasOwnProperty.call(o,"value"))return o;let i=Ra(o.value,t,n);return r+=i.replacements,i.replacements>0?{...o,value:i.value}:o}),replacements:r}}function GC(e){let t=structuredClone(Pc),n=0,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];xr(t,void 0,St(i.hash_algorithm))!==i.before_hash&&(n+=1),t=jn(t,i.patch,o+1,i.op),xr(t,void 0,St(i.hash_algorithm))!==i.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function jC(e,t,n){let r=0,o=!1,i=!1,a=e.message;if(typeof e.message=="string"){let m=Iy(e.message,t,n);a=m.value,r+=m.replacements,m.replacements>0&&(o=!0)}let s=Cy(e.patch,t,n);r+=s.replacements,o||=s.replacements>0;let c=e.reanchor_evidence?.map(m=>{let p=m.patch?Cy(m.patch,t,n):{patch:void 0,replacements:0},u=m.record?Ra(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:h,record:_,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 qC(e,t,n){let r=structuredClone(Pc),o=0,i=0,a=[];for(let s=0;s<e.length;s+=1){let c=e[s],m=Rf(c);if(!m.ok)throw new l(`history-redact refuses invalid immutable record ${s+1} (${m.error}).`,d.GENERIC_FAILURE);let p=jC(c,t,n);i+=p.replacements,p.changed&&(o+=1);let u=xr(r,void 0,St(c.hash_algorithm));r=jn(r,p.entry.patch,s+1,p.entry.op);let f=xr(r,void 0,St(c.hash_algorithm));a.push(Of(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 KC(e){return Object.keys(e.metadata).length>0}function zC(e){if(!KC(e.finalDocument))return{raw:null,path:null,document:null};let t=Et(mt(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:gt(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:dt(t,{format:"toon",schema:e.settings.schema})}}function HC(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 BC(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??mt(e.rewritten.finalDocument);return t.push(Ue({nowIso:S(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function WC(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await Kt(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 oe(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await Sl.rm(e.currentItem.path,{force:!0}),await oe(e.subject.historyPath,xf(e.rewrittenEntries))}catch(c){try{await VC(e.subject.historyPath,n,o,i)}finally{await Nc(e.subject.historyPath)}throw c}await Nc(e.subject.historyPath);let s=e.nextItem.path??e.currentItem.path;s&&(t=await zt({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 YC(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function VC(e,t,n,r){t===null?await Sl.rm(e,{force:!0}):await oe(e,t);for(let o of n){let i=r.get(o);i===void 0?await Sl.rm(o,{force:!0}):await oe(o,i)}}async function YC(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 Ry(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await qr(n.path),a=t.replacement??"",s=a.length===0,c=s?"[redacted]":a,m=MC(t.literal,t.regex),p=await an(r,e,o,i.type_to_folder);return na({pmRoot:r,subject:p,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>JC({pmRoot:r,subject:p,settings:o,typeRegistry:i,options:t,rules:m,replacement:c,replacementIsDefault:s},u)})}function JC(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:i,options:a,rules:s,replacement:c,replacementIsDefault:m}=e,p=t.entries,u=GC(p),f=qC(p,s,c),h=u.hashMismatchesBefore+u.hashMismatchesAfter,_=!!a.dryRun,g=f.replacements>0,y=[];h>0&&y.push(`history_redact_preexisting_hash_mismatches:${h}`),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=zC({pmRoot:n,subject:r,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),k=(w.path??null)!==(b.path??null)||(w.raw??null)!==(b.raw??null),I=t.author,C=HC(a,f),{rewrittenEntries:N,auditEntryAdded:L}=BC({rewritten:f,dryRun:_,changed:g,nextItemDocument:b.document,author:I,message:C});return{changed:g,rewrittenEntries:N,...WC({pmRoot:n,subject:r,settings:o,typeRegistry:i,currentItem:w,nextItem:b,author:I,rewrittenEntries:N}),report:({verification:D,warnings:J})=>({id:r.id,dry_run:_,changed:g,patterns:{literal_count:s.filter(H=>H.kind==="literal").length,regex_count:s.filter(H=>H.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:h,audit_entry_added:L,verify_ok:D.ok,verify_errors:D.errors},item:{existed_before:w.path!==null,exists_after:b.path!==null,path_before:w.path,path_after:b.path,changed:k},warnings:[...new Set([...y,...J])].sort((H,pe)=>H.localeCompare(pe)),generated_at: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]="f7317758-33fb-52ee-a94b-1b97c4920773")}catch{}})();async function Oy(e,t,n){return Xn(e,t,n,{input:await fa(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Jn(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]="28dd911b-487d-5ada-8fa5-527798ceb36e")}catch{}})();async function xy(e,t,n){if(mf(t),lt(e,"append","id"),t=sf(t),t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=Ut(),o=A(process.cwd(),n.path);await O(o);let i=await E(o),a=T(t.author,i.author_default),s=(await r.resolveValue(t.body,"--body",lf(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 _e({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
-
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]="f68bdee1-bdeb-58f0-a081-4f0d47a51b71")}catch{}})();function XC(e,t,n){let r={...t.metadata,body:t.body},o={...n.metadata,body:n.body};for(let i of new Set([...Object.keys(r),...Object.keys(o)])){if(i==="updated_at"||i==="pm_format_version")continue;let a=r[i],s=o[i];if(ae(a,s))continue;let c=e.get(i);if(c&&!ae(c.after,a))throw new l(`Rollback conflict on ${i}: the batch effects contain an intervening edit. Inspect pm history before resolving it.`,d.CONFLICT);e.set(i,{field:i,before:c?c.before:a,after:s})}}function QC(e,t,n){let r=new Map;for(let[o,i]of e.entries()){if(i.context?.bulk_checkpoint!==t)continue;let a=Nr(qn(e,o-1),{schema:n}),s=Nr(qn(e,o),{schema:n});XC(r,a,s)}return[...r.values()].filter(o=>!ae(o.before,o.after))}function ZC(e,t){let n={...e.metadata,body:e.body},r=t.filter(o=>!ae(n[o.field],o.after));if(r.length>0)throw new l(`Rollback conflict on ${r.map(o=>o.field).join(", ")}: a later edit changed a batch field. Inspect pm get/history and reconcile it explicitly before retrying.`,d.CONFLICT);for(let o of t)o.field==="body"?e.body=o.before:o.before===void 0?delete e.metadata[o.field]:e.metadata[o.field]=structuredClone(o.before);return t.map(o=>o.field)}async function Oa(e,t,n){if(t.record.rollback_strategy!=="guarded_inverse")throw new l("This legacy checkpoint has no attributable inverse effects. Inspect pm history and use an explicit pm restore only after reviewing later edits.",d.CONFLICT);let r=await E(e);return of(t.items,async o=>{let i=await Vf({pmRoot:e,settings:r,id:o,op:"restore",author:T(n.author,r.author_default),message:n.message,force:n.force,skipNoop:!0,historyContext:{bulk_rollback:t.id},async mutate(a){let s=await $i(Be(e,o),o);if(!y_(s,a).ok)throw new l(`Cannot safely roll back ${o}: item/history verification failed. Inspect pm history --verify before recovery.`,d.CONFLICT);return s.some(c=>c.context?.bulk_rollback===t.id)?{changedFields:[]}:{changedFields:ZC(a,QC(s,t.id,r.schema))}}});return{changed_fields:i.changedFields,warnings:i.warnings,skipped:i.changedFields.length===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]="1430dcf8-9363-556d-aa33-184cea5421f9")}catch{}})();var e0=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function Ny(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 ao(e,t){return El(e,t,{operation:"close"})}function El(e,t,n){let r=Ny(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 Al(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]="3445f237-469f-5713-bcd1-826fda836efd")}catch{}})();var t0=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function n0(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 Py(e){let t=[];for(let n of t0){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function Ly(e,t,n={}){let r=Py(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=[...t,"update",e.id,...r.flatMap((s,c)=>[i[c],o[s.key]?.trim()||"<value>"])];return{missing:i,suggested_retry:Q(a),suggested_retry_args:a}}async function r0(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 o0(e){return typeof e!="string"||e.trim().length===0}async function i0(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=P(t,R()),a=new Map,s=async m=>{if(a.has(m))return a.get(m)??null;let p=await j(e,m,t.id_prefix,t.item_format,i.type_to_folder);if(!p)return a.set(m,null),null;let{document:u}=await ne(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 r0(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 a0(e,t,n){return e.filter(r=>r.parent===t&&!ce(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function s0(e,t,n){let r=new Map(e.map(s=>[s.id.trim().toLowerCase(),s])),o=u_(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&&ce(m.status,n)})).map(({item:s,blockerIds:c})=>({id:s.id,blocker_ids:c})).sort((s,c)=>s.id.localeCompare(c.id))}async function c0(e,t,n,r,o,i){let a=s0(n,r,i),s=[];for(let c of a)try{let m=await _e({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(_=>{let g=_.id.trim().toLowerCase();return _.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 h=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==u.length&&h.push("dependencies"),{changedFields:h}}});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 l0(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 d0(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)o0(e[o])&&(e[o]=i,n.push(o));return n}function m0(e,t,n,r){let o=[];if(t!=="off"){let i=Py(e);if(i.length>0){let a=i.map(s=>s.label);if(t==="strict"){let s=i.map(m=>`--${m.key.replaceAll("_","-")}`),c=[...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:Q(c),suggested_retry_args: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 p0(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function u0(e){let t=["assignee","claim_principal"].filter(n=>e[n]!==void 0);for(let n of t)delete e[n];return[...t]}function f0(e,t){if(ce(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:Ly(e,t.commandScope,t.options)});let n=l0(e,t.options),r=d0(e,t.duplicateOf),o=m0(e,t.validateCloseMode,t.activeChildIds,t.commandScope);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"]:[],...p0(e,t.closeReason),...n];if(Qf(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(...u0(e));let s=Al(e,t.lifecyclePolicy);return a.push(...s.changedFields),o.push(...s.warnings),{changedFields:a,...o.length>0?{warnings:o}:{}}}async function $y(e,t,n,r){let o=A(process.cwd(),r.path),i=Pn(r);await O(o);let a=await E(o),s=F(a.schema),c=T(n.author,a.author_default),m=P(a,R()).type_to_folder,p=await j(o,e,a.id_prefix,a.item_format,m);if(!p)throw await et(o,e,a.id_prefix,m);let u=await i0(o,a,n.duplicateOf,p.id),f={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??a.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},h=ao({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},f.requireCloseReason).closeReason,_=n0(n.validateClose)??a.governance.close_validation_default,g=await ye(o,a.item_format,m,void 0,a.schema),y=a0(g,p.id,s),w=S(),b=n.completedAt===void 0?w:te(n.completedAt,new Date(w),"completed-at"),k={timestamp:b,source:n.completedAt===void 0?"close_time":"asserted",...n.completedAt===void 0?{hint:`completed_at defaults to the close time. If work finished earlier, correct it with ${Q([...i,"update",p.id,"--completed-at","<ISO>"])}.`}:{}},I=await Kn({pmRoot:o,settings:a,id:p.id,op:"close",author:c,message:n.message,force:n.force,resolveHistoryContext:()=>({completion:{timestamp:k.timestamp,source:k.source}}),mutate(N){return n.completedAt===void 0&&N.metadata.completed_at!==void 0&&(k={timestamp:N.metadata.completed_at,source:"existing"}),f0(N.metadata,{pmRoot:o,commandScope:i,statusRegistry:s,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:h,closedAt:w,completedAt:b,lifecyclePolicy:f})}}),C=_==="warn"?Ly(I.item,i):void 0;return{item:I.item,changed_fields:I.changedFields,...C?{follow_up:{kind:"complete_close_evidence",missing:C.missing,suggested_command:C.suggested_retry,suggested_command_args:C.suggested_retry_args}}:{},warnings:[...I.warnings,...await c0(o,a,g,p.id,c,s)],completion:k}}function It(e,t,n,r){return $y(e,t,n,r)}(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]="da095c39-4e7a-5c52-9b33-aa85d6e12e2d")}catch{}})();var My=2,Tl="close-many",_0=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function h0(e,t){return Br(e,t,{includePagination:!1})}function g0(e,t){return Br(e,t)}function y0(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 w0(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 v0(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 b0(e,t){let n=F(t.schema),r=P(t,R()),o=await ye(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),ce(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 Fy(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 k0(e){let t=await ki(e.pmRoot,Tl,e.rollbackId,My),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Oa(e.pmRoot,t,{author:e.options.author,message:n,force:e.options.force}),o=r.rows.filter(i=>i.status==="skipped").length;return{...on({applied:r.restored_ids.length,skipped:o,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,skipped_count:o,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function S0(e,t,n,r,o){return e.map(i=>{let a=(t.get(i.id)??[]).filter(c=>!n.has(c)),s=!Dy(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 E0(e){let t=await bi(e.pmRoot,Tl,e.checkpointId,{schema_version:My,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:T(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 A0(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 Ki({pmRoot:e.pmRoot,itemId:r.id,checkpointId:e.checkpointId},()=>It(r.id,e.reason,e.closeOptions,e.global));t.push({id:r.id,status:"closed",completion:o.completion,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:Lt(o)})}}return{rows:t,closedIds:n}}function T0(e){return wi(e.rollback)}function C0(e){if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(g0(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function I0(e){if(!h0(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${_0}). Refusing to match every item.`,d.USAGE)}function R0(e,t){let n=new Map;return[...e].sort((r,o)=>{let i=Fy(o.id,t,n)-Fy(r.id,t,n);return i!==0?i:r.id.localeCompare(o.id)})}function Dy(e,t,n){return n||!ce(e.status,t)}function O0(e,t,n){return new Set(e.filter(r=>Dy(r,t,n)).map(r=>r.id))}async function x0(e){I0(e.options);let t=F(e.settings.schema),n=v0(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await At(e.options.status,w0(e.options.list),e.global),{childrenByParent:i,parentByChild:a}=await b0(e.pmRoot,e.settings),s=R0(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 At(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,p=new Set(m.map(f=>f.id)),u=O0(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:S0(s,i,u,t,r)}}function N0(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 P0(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 E0({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 Uy(e,t){let n=T0(e),r=A(process.cwd(),t.path);await O(r);let o=await E(r),i=e.dryRun===!0;if(y0(e.list),n!==void 0)return C0(e),k0({pmRoot:r,rollbackId:n,options:e,global:t});let a=await x0({pmRoot:r,settings:o,options:e,global:t});if(i)return N0(a);let s=new Set(a.planRows.filter(w=>w.action==="close").map(w=>w.id)),c=S(),m=vi(Tl,c),p=await P0({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:h}=await A0({pmRoot:r,checkpointId:m,matched:a.matched,closableIds:s,reason:a.reason,closeOptions:u,global:t}),_=f.filter(w=>w.status==="closed").length,g=f.filter(w=>w.status==="skipped").length,y=f.filter(w=>w.status==="failed").length;return{...on({applied:_,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:_,skipped_count:g,failed_count:y,rows:f,ids:h,...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 L0(e,t){return[...new Set([...Co.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 $0(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Cl(e,t,n){let r=A(process.cwd(),n.path);await O(r);let o=await E(r),i=P(o,R()),a=await j(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await et(r,e,o.id_prefix,i.type_to_folder);let s=await ne(a,{schema:o.schema}),c=s.document.metadata,m=S(),p=T(t.author,o.author_default),u=await Lr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:i.type_to_folder,probeExisting:!1}),f=F(o.schema),h=t.title?.trim();if(h!==void 0&&h.length===0)throw new l("Copy --title must not be empty",d.USAGE);let _={...c,id:u,title:h??c.title,status:f.open_status,created_at:m,updated_at:m};delete _.closed_at,delete _.completed_at,delete _.close_reason,delete _.test_runs;let g=Ye(R()),y=Et({metadata:_,body:s.document.body},{schema:o.schema,extensionFieldNames:g}),w=await Wn({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=L0(y.metadata,y.body),k=gt(r,y.metadata.type,u,o.item_format,i.type_to_folder),I=Be(r,u),C=await ct(r,u,o.locks.ttl_seconds,p,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),N={metadata:{},body:""},L,D;try{let J=await Kt(r,p,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await Wn({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 H=await j(r,u,o.id_prefix,o.item_format,i.type_to_folder);if(H)throw new l(`Cannot copy to ${u}: an item with that id already exists at ${H.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${u} already exists at ${H.itemPath}.`,recovery:{suggested_retry:`pm copy ${a.id}`}});await oe(k,dt(y,{format:o.item_format,schema:o.schema,extensionFieldNames:g}));try{let pe=Ue({nowIso:m,author:p,op:"create",before:N,after:y,message:$0(a.id,t.message)});await Gt(I,pe)}catch(pe){throw await An(k),pe}D=await zt({pmRoot:r,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:k,document:y})}finally{await J()}L=[...await Y({path:k,scope:"project",op:"create",item_id:y.metadata.id,item_type:y.metadata.type,before:N,after:y,changed_fields:b}),...await Y({path:I,scope:"project",op:"create:history",item_id:y.metadata.id,item_type:y.metadata.type,before:N,after:y,changed_fields:b})],xn({id:y.metadata.id,op:"create",item_type:y.metadata.type,status:y.metadata.status,current:rn(y.metadata,b),changed_fields:b})}finally{await C()}return{source_id:a.id,item:structuredClone(y.metadata),changed_fields:b,warnings:[...ea(w),...D,...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]="b653115b-596b-5c07-b1f7-541fa1f04a33")}catch{}})();var F0="hierarchy-integrity";async function xa(e){let t=e.required?await ct(e.pmRoot,F0,e.ttlSeconds,e.author,!1,!1,e.waitMs,{waitPolicy:"progress"}):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 Na(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Pa(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function La(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(js.includes(t))return t;let n=ge(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 $a(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 Gy=[["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]="48513c82-4195-51fc-bd68-480148a54d10")}catch{}})();var M0=["documentAnnotationSnapshot","runtimeFieldCommands","ownershipMetadataBypass","ownershipDependencyBypass"];function Fa(e){let t=Gy.find(([r])=>r===e)?.[1]??e.replaceAll(/_([a-z])/gu,(r,o)=>o.toUpperCase()),n=[["update",wc],["create",yc]].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.`]}}var qy={create:{name:"create",usage:"pm create",sdkScope:"create options"},update:{name:"update",usage:"pm update <id>",sdkScope:"update options"},update_many:{name:"update-many",usage:"pm update-many <selection flags>",sdkScope:"update options of the update-many request"}};function jy(e){return e.flatMap(t=>[t.flag,...t.short===void 0?[]:[t.short],...t.aliases??[]])}function Ky(e){if(e==="update_many"){let o=Ky("update"),i=jy(Me("update-many"));return{options:new Set([...o.options,...i.map(a=>Tc(a))]),flags:new Set([...o.flags,...i])}}let t=e==="update"?wc:yc,n=jy([...Me(e),...In]),r=[...t.flatMap(o=>[o.target,...o.keys]),...n.map(o=>Tc(o)),...e==="update"?M0:[]];return{options:new Set(r),flags:new Set(n)}}function D0(e,t){let n=qy[t];return e===void 0?`SDK: every option name for this field is shared with another declared field or an option of pm ${n.name}; no SDK option sets it alone.`:`SDK: pass ${e} in the ${n.sdkScope}.`}function U0(e,t,n,r){return e.definitions.some(o=>o.metadata_key===t.metadata_key&&o.commands.includes(n)&&gf(r,o)!==void 0)}function Ma(e,t,n){let r=qy[t],o=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([i])=>i!=="field"));return i=>{let a=gu(i),s=e.definitions.filter(h=>h.metadata_key===a||h.key===a),c=s.find(h=>h.commands.includes(t))??s[0];if(c===void 0)return;let m=`Inspect the value contract with: pm schema show-field ${c.key}`;if(!c.commands.includes(t))return{recovery:{provided_fields:[i]},nextSteps:[`The project schema declares "${c.key}" for ${c.commands.join(", ")} only; ${r.name} cannot set it.`,m]};if(o!==void 0&&U0(e,c,t,o))return{recovery:{provided_fields:[i]},nextSteps:[`This invocation already sets "${c.key}" through a declared flag or option; drop the --field ${i} assignment so the field receives one value.`,m]};let p=Ky(t),u=hf(c,e,p,t),f=u===void 0?`Every CLI spelling of "${c.key}" is shared with another declared field or an option of pm ${r.name}; give it a distinct cli_flag in the project schema.`:`Use the declared project-schema flag: ${r.usage} ${Ac(u)} <value>`;return{recovery:{provided_fields:[i],...u===void 0?{}:{suggested_flags:[Ac(u)]}},nextSteps:[f,D0(_f(c,e,p.options,t),t),m]}}}(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]="202cbe4e-7d36-5b12-be9d-d35608a6b36d")}catch{}})();var G0=new Set(["none","null"]);function Da(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 nt(e){return e===void 0?!1:G0.has(e.trim().toLowerCase())}function Ua(e,t,n){if(!nt(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Ne(e,t,n){if(!e||e.length===0||De(e)||!e.some(o=>nt(o)))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Ga(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);if(De(r))continue;let o=r;if(o.some(i=>nt(i))){if(o.filter(i=>!nt(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 j0=new Set(["event","meeting","reminder","milestone","decision","adr"]);function zy(e,t,n,r){if(j0.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=vt("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]="528a6201-58cb-544b-a831-5ce3bff3bbc2")}catch{}})();var ja=["close_reason","close-reason"],Il=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Rl=[{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"}],Hy=[...Il,...Rl],qa=[{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 Ol(e,t){return e.flatMap(n=>n.includes(",")&&t(n)?[n]:n.split(","))}function Ka(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};let r=Ol(e.raw,o=>e.resolveDefinition(o.trim().toLowerCase())!==void 0);for(let o of r){let i=o.trim().toLowerCase();if(!i)throw new l("--unset values must not be empty; name each field once, for example --unset parent,release",d.USAGE);if(nt(i))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let a=e.resolveDefinition(i);if(!a)throw new l(`Unsupported --unset field "${o}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(a.metadataKey),n.add(a.optionKey)}return{metadataKeys:t,optionKeys:n}}function za(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 Wy(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 xl(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function rt(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 Vy=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function q0(e,t){return t==="defined"?e!==void 0:!!e}function By(e,t,n){if(!q0(e,n))return;let r=ge(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function K0(e,t,n){let r=e?te(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 z0(e){return Array.from(new Set(xl(e).map(t=>rt(t.toLowerCase(),Im,"event weekday")))).sort((t,n)=>qs(t)-qs(n))}function H0(e){return Array.from(new Set(xl(e).map(t=>{let n=ge(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 B0(e,t){return Array.from(new Set(xl(e).map(n=>te(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Yy(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=rt(o.toLowerCase(),Cm,"event recurrence frequency"),f=By(i,"recur_interval",r),h=By(a,"recur_count",r),_=K0(s,t,n),g=z0(c),y=H0(m),w=B0(p,n);return{freq:u,interval:f,count:h,until:_,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 so(e,t=tt()){let n=t.resolve(e);if(n)return n.kind;let r=new Set(To),o=[...To,...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 co(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 lo(e,t,n=tt()){for(let r of t??[])try{Pm(e,r.id,r.kind,n)}catch(o){throw new l(Lt(o),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Jy(e,t){return(await ne(e,{schema:t})).document.metadata.created_at}async function W0(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await j(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Jy(n,t.schema)}function V0(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 Y0(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 Jy(n.get(o),e.context.schema)])));for(let o of e.holders){let i=await W0(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 V0({holder:o,dependency:a,sourceCreatedAt:i,targetCreatedAt:s,registry:e.registry})}}}async function _n(e){let t=e.registry??tt(),n=(e.dependencies??[]).filter(a=>!qu(a.source_kind)),r=[...new Set(n.map(a=>a.id))],o=await Promise.all(r.map(async a=>({target:a,located:await j(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 Y0({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 J0={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 X0(e){return J0[e]}function Nl(e){return X0(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 Xy="--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.",Q0="--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).",Z0=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,eI=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Zy=1e3,Pl=60*Zy,tI=60*Pl;function Qy(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 nI(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=Z0.exec(r);if(i){let c=i[1]==="-"?-1:1,m=Number.parseInt(i[2],10)*c;return Qy(n.getTime()+m*Pl,r)}let a=eI.exec(r);if(a){let[,c,m,p,u]=a;if(m||p||u){let f=c==="-"?-1:1,h=Number.parseInt(m??"0",10),_=Number.parseInt(p??"0",10),g=Number.parseInt(u??"0",10),y=h*tI+_*Pl+g*Zy;return Qy(n.getTime()+f*y,r)}}let s=o.startsWith("+")||o.startsWith("-")?o:`+${o}`;return te(s,n,"event.duration")}function ew(e,t,n,r){if(t&&n)throw new l(Q0,d.USAGE);if(n){let i=nI(e,n);if(i<e)throw new l(Xy,d.USAGE);return i===e?void 0:i}if(!t)return;let o=te(t,r,"event.end");if(o<e)throw new l(Xy,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 rI=["at","date","text","title"],oI=["start","date","end","duration","title","description","location","timezone","all_day",...Vy],iI=["key","value"];function tw(e,t){return t==="trimmed"?e?.trim():e}function aI(e,t){return t==="defined"?e!==void 0:!!e}function Ha(e,t,n){return e.map(r=>{let o=fe(r,"--reminder");Xe(o,"--reminder",rI);let i=tw(o.at??o.date,n.valueMode),a=tw(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:te(i,t,"reminder.at"),text:s}})}function Ba(e,t,n){return e.map(r=>{let o=fe(r,"--event");Xe(o,"--event",oI);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=te(i,t,"event.start"),s=o.end?.trim(),c=o.duration?.trim(),m=ew(a,s,c,t),p=o.title,u=o.description,f=o.location,h=o.timezone,_=p?.trim(),g=u?.trim(),y=f?.trim(),w=h?.trim(),b=[["title",p,_],["description",u,g],["location",f,y],["timezone",h,w]];for(let[N,L,D]of b)if(L!==void 0&&!D)throw new l(`--event ${N} must not be empty`,d.USAGE);let k=o.all_day?.trim(),I=Yy(o,a,t,n.recurrenceEmptyNumericGuard),C=aI(k,n.allDayEmptyGuard)?Wy(k,"--event all_day"):void 0;return{start_at:a,end_at:m,title:_,description:g,location:y,all_day:C,timezone:w,recurrence:I}})}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=fe(r,"--type-option");Xe(a,"--type-option",iI),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]="dfc60af7-26bb-552f-a517-ae0dd5442d4f")}catch{}})();var sI=["strict","progressive"],cI=["lightweight"],iw=new Set(["Reminder","Meeting","Event"]),lI=new Set(["author","created_at","text"]),$l=[...Hy,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...qa],dI=(()=>{let e=new Map;for(let t of $l)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Va=new Map($l.map(e=>[e.optionKey,e.canonical])),mI=$l.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function pI(e,t){let n=se(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function uI(e,t){let n=e.default_status;if(n!==void 0){let r=se(n,t);if(r)return r}return t.open_status}function Ll(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 fI=Da();function aw(e){if(De(e))return 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};nt(t.template)&&(t.template=void 0);let r=new Set([...Va.keys(),"rank"]);for(let o of r){if(De(e,o))continue;let i=t[o];if(typeof i!="string"||!nt(i))continue;let a=o==="rank"?"order":Va.get(o)??o;n(a),t[o]=void 0}return de(e,Ga(t,fI))}function Se(e){if(e!==void 0)return e}function _I(e,t){return Ka({raw:e,supportedFields:mI,resolveDefinition:n=>dI.get(n)??za(n,"create",t)})}var nw=["id","kind","type","author","created_at","source_kind"],Ya=["path","scope","note"];function hI(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let i=o.trim(),a=Ja(i,nw);co(i,a);let s=a?fe(o,"--dep"):{id:i,kind:"related"};a&&Xe(s,"--dep",nw);let c=Se(s.id),m=gI(Se(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=Gr(Se(s.source_kind)),u=Se(s.author);return{id:jr(c,n,p),kind:so(m),created_at:Ll(s.created_at,t),author:u??r,source_kind:p??"cli:create:dep",author_source:u?"asserted":"detected"}}),explicitEmpty:!1})}function gI(e){return typeof e=="string"?tt().resolve(e)?.kind??e.trim():e}function Ja(e,t){return af(e,t)?!0:Ai(e)}function gn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Ne(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=fe(o,e)}catch(m){if(e==="--comment"||e==="--note"||e==="--learning")return a();throw m}if(Object.keys(s).filter(m=>!lI.has(m)).length>0)return{created_at:Ll(s.created_at,n),author:Se(s.author)??r,text:i};let c=s.text??"";if(c==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:Ll(s.created_at,n),author:Se(s.author)??r,text:c}}),explicitEmpty:!1})}function Fl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--file","Use --clear-files to clear linked files."),{values:e.map(t=>{let n=t.trim(),r=Ja(n,Ya);bc(n,"--file","file path",r);let o=r?fe(t,"--file"):{path:n};if(r&&Xe(o,"--file",Ya),!o.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:o.path,scope:rt(o.scope??"project",ft,"file scope"),note:Se(o.note)}}),explicitEmpty:!1})}function Ml(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(t=>{let n=t.trim(),r=Ja(n,kt);bc(n,"--test","test command",r);let o=r?Ii(fe(t,"--test"),"--test"):{command:n},i=Se(o.command),a=Se(o.path);if(!i)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let s=Se(o.timeout_seconds),c=Se(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:rt(o.scope??"project",ft,"test scope"),timeout_seconds:m?ge(m,"timeout_seconds"):void 0,pm_context_mode:va(o.pm_context_mode,"--test"),workspace_context_mode:pn(o.workspace_context_mode,"--test"),env_set:Zr(o.env_set,"--test"),env_clear:eo(o.env_clear,"--test"),shared_host_safe:wa(o.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:un(o.assert_stdout_contains),assert_stdout_regex:nr(o.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:un(o.assert_stderr_contains),assert_stderr_regex:nr(o.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:ba(o.assert_stdout_min_lines,"--test"),assert_json_field_equals:ka(o.assert_json_field_equals,"--test"),assert_json_field_gte:Sa(o.assert_json_field_gte,"--test"),note:Se(o.note)}}),explicitEmpty:!1})}function Dl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(t=>{let n=t.trim(),r=Ja(n,Ya),o=r?fe(t,"--doc"):{path:n};if(r&&Xe(o,"--doc",Ya),!o.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:o.path,scope:rt(o.scope??"project",ft,"doc scope"),note:Se(o.note)}}),explicitEmpty:!1})}function yI(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Ha(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function wI(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--event","Use --clear-events to clear linked events."),{values:Ba(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function vI(e,t,n,r=[]){let o=[...Co.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 bI(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function rw(e,t,n){let r=hr("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function kI(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 sw(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 SI(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(rw(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(rw(r,e.name,"required_create_repeatables"));return n}function EI(e,t,n,r){for(let o of e)if(!(!sw(t,o)&&!n.has(o)))throw new l(`Option ${Ie("create",o)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function AI(e,t,n){if(t!=="strict")return;let r=e.filter(i=>n.has(i)&&!Nl(i));if(r.length===0)return;let o=[...new Set(r.map(i=>Ie("create",i)))].sort((i,a)=>i.localeCompare(a));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset cannot satisfy a required scalar option (only repeatable options accept an explicit --clear-* empty set)`,d.USAGE)}function TI(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Wa(e),explicitEmpty:!1})}async function CI(e){return await Ti(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 II(e){return bt(e)?await CI(e):e}function RI(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: ${sI.join(", ")}`,d.USAGE)}function OI(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: ${cI.join(", ")}`,d.USAGE)}function xI(e,t,n){let r=RI(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 NI(e,t,n,r,o){let i=e.name,a=kI(t),s=SI(e,n),c=Tn(e,"create",s);if(c.errors.length>0)throw new l(c.errors.join("; "),d.CONFLICT);EI(c.disabled,a,r,i),AI(c.required,n,r);let m=u=>u==="author"&&o!=="unknown"||u==="status"&&e.default_status!==void 0||r.has(u)&&Nl(u)?!0:sw(a,u),p=c.required.filter(u=>!m(u));return[...new Set(p.map(u=>Ie("create",u)))].sort((u,f)=>u.localeCompare(f))}var cw=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function PI(e,t){let n=[];for(let r of e){let o=r.match(cw);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function LI(e,t){return e.filter(n=>{let r=n.match(cw);return!r||r[2]!==t})}function $I(e,t,n,r){let o=LI(e,t);if(o.length===0)return;let i=lw(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 FI(e,t){let n=e.options.find(r=>r.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function MI(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 lw(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=mw[c];o.push(...m?[m]:MI(c,e.name,r)),s.add(c)}for(let c of n){let m=FI(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 DI(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 de(t,n)}function UI(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function GI(){let e=R();return e?e.commands.some(t=>t.action==="templates-show"||UI(t.command)==="templates show"):!1}function jI(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 qI(e,t,n){if(!GI())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await pi({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled)throw Object.hasOwn(r,"cause")?yi("templates show",r):new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.`,d.USAGE);return jI(r.result,e)}function W(e,t,n){return e.has(t)||n===void 0?void 0:Se(n)}function hn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var KI=new Set(["milestone","meeting","reminder","event"]);function dw(e,t,n,r){let o=t!==void 0,i=n!==void 0&&n.length>0,a=r!==void 0&&r.length>0;return KI.has(e.toLowerCase())&&!o&&!i&&!a}function zI(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`),dw(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 HI(e,t,n,r){if(t.inheritFocus!==!0||e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await Pi(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function BI(e,t,n,r,o,i){let a=Xi(Di(o),t.id_prefix);if(_i(a))return{parent:a,warnings:[]};if(Gi(r,a,t.id_prefix),await j(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:Ui(s,i).warnings}}async function WI(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await BI(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function VI(e){if(e.explicitId===void 0)return Lr(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});lt(e.explicitId,"create","id");let t=e.explicitId.trim();if(t.length===0||$f(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 ow(e,t,n,r,o){let i=W(e,t,n);if(i===void 0)return{value:void 0,warnings:[]};let a=ji(r,i,o);return{value:a.value,warnings:a.warnings}}async function YI(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 j(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:p,status:a};if((p??[]).some(_=>_.id===f.id&&_.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 h=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((_,g)=>_.localeCompare(g))[0]??o.open_status;return{dependencyValues:p,status:h}}function JI(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&&Ae(r,n)){e.type=r;return}Ae("Task",n)&&(e.type="Task")}function XI(e,t){return e.options.filter(n=>hr("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 QI(e,t,n,r,o){let i=e,a=[];if(i.template!==void 0){let _=i.template.trim();if(_.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let g=await qI(_,t,n);i=aw(Cr("create",DI(g,i)))}if(i.type===void 0&&JI(i,r,o),i.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let s=Ae(i.type,o);if(!s){let _=Mf(i.type),g=_?Ae(_,o):void 0;if(g)a.push(`type_coercion:${i.type.trim()}:${g}`),i.type=g,s=g;else throw new l(Ft(i.type,o.types,Mt(n,r.schema)),d.USAGE)}let c=Oo(s,o);if(!c)throw new l(`Invalid type value "${i.type}"`,d.USAGE);let m=c.name,p=XI(c,i),u=p.map(_=>`${_.key}=${String(i[_.key])}`);if(u.length>0){i.typeOption=[...u,...i.typeOption??[]];for(let _ of p)delete i[_.key]}let f=OI(i.schedulePreset);if(f!==void 0&&!iw.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let h=xI(i.createMode,f,r.governance.create_mode_default);return{resolvedOptions:i,typeDefinition:c,type:m,schedulePreset:f,createMode:h,warnings:a}}function ZI(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 eR(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 ${Ie("create",r)}`,d.USAGE)}}function tR(e){if(De(e))return;let t=(n,r)=>{if(De(e,r))return;let o=Va.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;Ua(n,Ie("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 nR(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 mw={"--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 rR(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(_=>{let g=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${g}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),p=[lw(n,r,o,i),...m.map(_=>_.example)].join(" "),u=[`Run "pm create --help --type ${a}" for type-aware required option guidance.`,...t.filter(_=>_==="--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".'),iw.has(a)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&u.push(`Required custom field formats: ${m.map(_=>_.description).join("; ")}.`);let f=[...new Set(t.flatMap(_=>{let g=_.split(" ",1)[0],y=mw[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 h=t.length===1?`Missing required option ${t[0]} for type "${a}"`:`Missing required options ${t.join(", ")} for type "${a}"`;throw new l(h,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${a}" in one invocation.`,examples:[...f.map(_=>`pm create --type ${a} ${_} ...`),p],nextSteps:u,recovery:s==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function oR(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?Dt(t.tags):[];return Fn(n,t.addTags)}function iR(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=hn(e,"order",n,o=>ge(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function aR(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:te(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:El(s,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:a,warnings:[]}}async function sR(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:h,allowDuplicate:_}=e,g=gt(t,n,r,o.item_format,i.type_to_folder),y=Be(t,r),w=tt(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(N=>ca(N.kind,w)),k=await xa({pmRoot:t,author:a,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:b}),I=b,C=[];try{let N=await ct(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 ye(t,o.item_format,i.type_to_folder,void 0,o.schema):void 0,D=await j(t,r,o.id_prefix,o.item_format,i.type_to_folder);if(D)throw new l(`Item "${r}" already exists`,d.CONFLICT,{code:"item_already_exists",id:D.id,path:D.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 ${D.id}.`]});if(L){la(L,[...L,c.metadata],w);let ue=F(o.schema);Qi(L,[...L,c.metadata],r,$e=>ce($e,ue),w)}let J=await Mr({pmRoot:t,settings:o,operation:"create",author:a,before:null,after:c});await mi({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:zi({pmRoot:t,settings:o,typeToFolder:i.type_to_folder})});let H=await Kt(t,a,{required:o.governance.duplicate_detection_mode==="strict"&&_!==!0}),pe=[];try{o.governance.duplicate_detection_mode==="strict"&&_!==!0&&await Wn(h,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await oe(g,dt(c,{format:o.item_format,schema:o.schema,extensionFieldNames:s}));try{let ue=Ue({nowIso:f,author:a,op:"create",before:m,after:c,message:p,context:J.decisions.length===0?void 0:{workflow_policies:J.decisions}});await Gt(y,ue)}catch(ue){throw await An(g),ue}I&&(await k(),I=!1),pe=await zt({pmRoot:t,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:g,document:c})}finally{await H()}C=[...J.warnings,...L?sa(L,[...L,c.metadata],r):[],...pe,...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})],xn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:rn(c.metadata,u),changed_fields:u})}finally{await N()}}finally{I&&await k()}return C}async function Wt(e,t){e=Cr("create",e);let n=aw(await II(e)),r=A(process.cwd(),t.path);await O(r);let o=await E(r),i=F(o.schema),a=Je(o.schema),s=P(o,R()),c=await QI(n,t,r,o,s);n=c.resolvedOptions;let{typeDefinition:m,type:p,createMode:u}=c,f=_I(n.unset,a),{explicitUnsets:h,clearOptionKeys:_}=ZI(n,f);eR(n,f),tR(n);let g=T(Se(n.author),o.author_default),y=NI(m,n,u,_,g),w=S(),b=hI(n.dep,w,o.id_prefix,g),k=gn("--comment",n.comment,w,g),I=gn("--note",n.note,w,g),C=gn("--learning",n.learning,w,g),N=Fl(n.file),L=Ml(n.test);L.values=await Yn(L.values,g,w);let D=Dl(n.doc),J=yI(n.reminder,w),H=wI(n.event,w),pe=TI(n.typeOption),ue=gr(p,pe.values,s),$e=R(),Ve=Ye($e),G=Io(n.field,$e,Fa,Ma(a,"create",n)),re=yf(n,a,p),mr=new Set(re.missing_required_flags),pr=a.definitions.filter(V=>mr.has(`--${V.cli_flag}`));nR(G,re,f);let ur=PI(ue.errors,p),Xt=ur.map(V=>`--type-option ${V}=<value>`),bo=[...new Set([...y,...Xt,...re.missing_required_flags])].sort((V,Ms)=>V.localeCompare(Ms));rR({combinedMissingFlags:bo,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:ur,openStatus:i.open_status,type:p,createMode:u,missingRequiredRuntimeFields:pr}),$I(ue.errors,p,m,i);let He=await VI({pmRoot:r,settings:o,typeRegistry:s,explicitId:n.id}),xt=n.status!==void 0?pI(n.status,i):uI(m,i),ko=n.priority!==void 0?qt(n.priority):2,x=f.metadataKeys,Qt=oR(x,n),En=hn(x,"deadline",n.deadline,V=>te(V,new Date(w),"deadline")),Nt=hn(x,"estimated_minutes",n.estimatedMinutes,V=>Mn(V,"estimated-minutes")),Os=W(x,"acceptance_criteria",n.acceptanceCriteria),st=W(x,"definition_of_ready",n.definitionOfReady),xs=iR(x,n),So=W(x,"goal",n.goal),qk=W(x,"objective",n.objective),Kk=W(x,"value",n.value),zk=W(x,"impact",n.impact),Hk=W(x,"outcome",n.outcome),Bk=W(x,"why_now",n.whyNow),Wk=W(x,"assignee",n.assignee),Vk=x.has("author")?void 0:Se(n.author)??g,Yk=W(x,"parent",n.parent),mm=await HI(Yk,n,x,r),Ns=mm.parent,Jk=mm.parentSource,Xk=W(x,"reviewer",n.reviewer),Qk=hn(x,"risk",n.risk,V=>rt(Na(V),fr,"risk")),Zk=hn(x,"confidence",n.confidence,V=>La(V)),eS=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,pm=o.validation.sprint_release_format,Zt=[...c.warnings,...zI(p,He,En,J.values,H.values)],um=await WI({itemId:He,parent:Ns,pmRoot:r,settings:o,typeRegistry:s,policy:eS});Ns=um.parent,Zt.push(...um.warnings);let fm=ow(x,"sprint",n.sprint,"sprint",pm),tS=fm.value;Zt.push(...fm.warnings);let _m=ow(x,"release",n.release,"release",pm),nS=_m.value;Zt.push(..._m.warnings);let hm=W(x,"blocked_by",n.blockedBy),gm=await YI({pmRoot:r,settings:o,typeRegistry:s,statusRegistry:i,blockedBy:hm,dependencyValues:b.values,status:xt,statusExplicit:n.status!==void 0,nowValue:w,author:g}),Ps=gm.dependencyValues;lo(He,Ps),Zt.push(...await _n({pmRoot:r,dependencies:Ps,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:s.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:He,createdAt:w}],schema:o.schema})),xt=gm.status;let rS=W(x,"blocked_reason",n.blockedReason),oS=W(x,"unblock_note",n.unblockNote),iS=W(x,"reporter",n.reporter),aS=hn(x,"severity",n.severity,V=>rt(Pa(V),_r,"severity")),sS=W(x,"environment",n.environment),cS=W(x,"repro_steps",n.reproSteps),ym=W(x,"resolution",n.resolution),lS=W(x,"expected_result",n.expectedResult),dS=W(x,"actual_result",n.actualResult),mS=W(x,"affected_version",n.affectedVersion),pS=W(x,"fixed_version",n.fixedVersion),uS=W(x,"component",n.component),fS=hn(x,"regression",n.regression,V=>$a(V)),_S=W(x,"customer_impact",n.customerImpact),Ls=Ul(n.title,"--title"),$s=n.description??"",Eo=n.body??"",wm=await Wn({title:Ls,description:$s,body:Eo},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Zt.push(...ea(wm));let Fs=aR(xt,i,o,n,ym,w),hS=Fs.closeReason,gS=xt===i.close_status?w:void 0,yS=Fs.completedAt;Zt.push(...Fs.warnings);let Ao=Rc({id:He,title:Ls,description:$s,type:p,type_options:ue.normalized,status:xt,closed_at:gS,completed_at:yS,close_reason:hS,priority:ko,tags:Qt,created_at:w,updated_at:w,deadline:En,assignee:Wk,author:Vk,estimated_minutes:Nt,acceptance_criteria:Os,definition_of_ready:st,order:xs,goal:So,objective:qk,value:Kk,impact:zk,outcome:Hk,why_now:Bk,parent:Ns,reviewer:Xk,risk:Qk,confidence:Zk,sprint:tS,release:nS,blocked_by:hm,blocked_reason:rS,unblock_note:oS,reporter:iS,severity:aS,environment:sS,repro_steps:cS,resolution:ym,expected_result:lS,actual_result:dS,affected_version:mS,fixed_version:pS,component:uS,regression:fS,customer_impact:_S,dependencies:Ps,comments:k.values,notes:I.values,learnings:C.values,files:N.values,tests:L.values,docs:D.values,reminders:J.values,events:H.values,...G,...re.values});try{Ro(Ao,$e)}catch(V){throw new l(V instanceof Error?V.message:"Invalid extension item field values",d.USAGE)}let wS=Et({metadata:Ao,body:Eo},{schema:o.schema,extensionFieldNames:Ve}),vS={metadata:{},body:""},vm=[...h].sort((V,Ms)=>V.localeCompare(Ms)),bS=bI(n.message,vm),bm=vI(Ao,Eo,vm,[...Object.keys(G),...Object.keys(re.values??{})]),kS=await sR({pmRoot:r,type:p,id:He,settings:o,typeRegistry:s,author:g,extensionFieldNames:Ve,afterDocument:wS,beforeDocument:vS,historyMessage:bS,changedFields:bm,nowValue:w,similarityCandidate:{title:Ls,description:$s,body:Eo},allowDuplicate:n.allowDuplicate}),km=structuredClone(Ao);u==="strict"&&h.has("dependencies")&&(km.dependencies=[]);let SS=zy(He,p,xt,i);return dw(p,En,J.values,H.values)&&ju(`[pm] warning: ${p} '${He}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${He} --deadline <ISO>' or 'pm update ${He} --event "start=<ISO>,end=<ISO>"'.`),{item:km,changed_fields:bm,warnings:[...Zt,...kS],...Object.fromEntries([["parent_source",Jk],["next_transition",SS],["similarity_advisory",wm]].filter(V=>V[1]!==void 0))}}import Xa 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 Gl(e,t,n){let r=A(process.cwd(),n.path);await O(r);let o=await E(r),i=T(t.author,o.author_default),a=await Yf({pmRoot:r,settings:o,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),s=a.targetPath?Xa.relative(r,a.targetPath).split(Xa.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:Xa.relative(r,Be(r,a.item.id)).split(Xa.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 cR(e){await O(e)}async function jl(e,t,n){let r=A(process.cwd(),n.path);if(await cR(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 E(r),u=Dn(T(void 0,p.author_default));return await kf(r),await Zc({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 Pi(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 lR(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 E(r),i=P(o,R()),a=await j(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await et(r,e,o.id_prefix,i.type_to_folder);let s=Ze(a.id,o.id_prefix),c=await ne(a,{schema:o.schema}),m=pw(c.document.metadata.title);return await bf(r,s),await Zc({pmRoot:r,settings:o,principal:Dn(T(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 lR(e,t){let n=await E(e),r=P(n,R()),o=await j(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let i=await ne(o,{schema:n.schema});return pw(i.document.metadata.title)}function pw(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]="d510588a-e45d-54ba-b9c0-153940bb6677")}catch{}})();var uw="terminal_state_unchanged";function fw(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function dR(e,t){return se(e,t)===t.close_status}function mR(e){let t=n=>ja.includes(n.trim().toLowerCase());return Ol(e.unset??[],t).some(t)}function _w(e){!e.settings.governance.require_close_reason||!mR(e.options)||ao({explicit:e.options.closeReason},!0)}function ql(e,t,n,r=!1){if(!dR(e.status,n))return!1;let o=fw(t.closeReason);return r&&t.closeReason!==void 0&&o===void 0||o!==void 0&&o!==fw(e.close_reason)?!1:t.completedAt===void 0||te(t.completedAt,new Date,"completed-at")===e.completed_at}async function hw(e){let t=await j(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await et(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ne(t,{schema:e.settings.schema});return n.metadata}async function gw(e,t,n,r,o){if(n.length===0)return{item:t,changed_fields:[],warnings:[...e.workflowTransitionWarnings,uw]};let i=de(e.options,{...e.options,status:void 0,closeReason:void 0,completedAt:void 0}),a=await r(e.id,i,e.global);return ql(a.item,e.options,e.statusRegistry,e.settings.governance.require_close_reason)?{item:a.item,changed_fields:a.changed_fields,warnings:[...e.workflowTransitionWarnings,...a.warnings,uw]}:o(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]="85fab88c-0aee-5257-8dce-a1f288b9866e")}catch{}})();var Bl=[...Il,{canonical:"close-reason",aliases:ja,optionKey:"closeReason",metadataKey:"close_reason"},...Rl,...qa],pR=(()=>{let e=new Map;for(let t of Bl)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Qa=new Map(Bl.map(e=>[e.optionKey,e.canonical])),uR=Bl.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),fR=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),_R=Da({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Tw(e){if(De(e))return 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([...Qa.keys(),"rank"]);for(let o of r){if(De(e,o))continue;let i=t[o];if(typeof i!="string"||!nt(i))continue;let a=o==="rank"?"order":Qa.get(o)??o;n(a),t[o]=void 0}return de(e,Ga(t,_R))}function Wl(e,t,n,r=["update"]){return[...Vl([...e],t,n,r).metadataKeys]}function Vl(e,t,n=[],r=["update"]){return Ka({raw:e,supportedFields:uR,resolveDefinition:o=>{let i=n.find(a=>{let s=a.toLowerCase();return s===o||s.replaceAll("_","-")===o||s.replaceAll("-","_")===o});return pR.get(o)??r.map(a=>za(o,a,t)).find(a=>a!==void 0)??(i?{optionKey:"field",metadataKey:i}:void 0)}})}var yw=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 ww(e){let t=e.disallowedFlags.flatMap(r=>{let o=yw.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=yw.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 hR(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 ww({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=>fR.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(a.push(...s),a.length>0)throw ww({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 gR(e,t){let n=se(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function yR(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:Cw(e)}function Cw(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 rr(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var wR=["id","kind","type","author","created_at","source_kind"],vR=["id","kind","type","author","created_at","source_kind"];function Iw(e){return e.startsWith("```")||e.includes(`
22
- `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Ai(e)}function Rw(e){return typeof e=="string"?tt().resolve(e)?.kind??e.trim():e}function es(e,t,n,r){return e?(Ne(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=Iw(i);co(i,a);let s=a?fe(o,"--dep"):{id:i,kind:"related"};a&&Xe(s,"--dep",wR);let c=s.id?.trim(),m=Rw((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=Gr(rr(s.source_kind)),u=rr(s.author);return{id:jr(c,t,p),kind:so(m),created_at:yR(s.created_at,n),author:u??r,source_kind:p??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function bR(e,t){return e?(Ne(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=Iw(r);if(co(r,o,"--dep-remove"),o){let i=fe(r,"--dep-remove");Xe(i,"--dep-remove",vR);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=Rw(rr(i.kind??i.type)),c=Gr(rr(i.source_kind)),m=rr(i.author),p=rr(i.created_at);return{id:jr(a,t,c),kind:s?so(s):void 0,source_kind:c,author:m,created_at:p?Cw(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 Za(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function kR(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 SR(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 ER(e,t,n,r,o,i){if(e===void 0||t)return{};let a=e.trim();if(a.length===0)return{};let s=await j(n,Ze(a,r),r,o,i);return s?{id:s.id}:{unresolved:a}}function AR(e,t,n,r,o){let i=SR(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 TR(e){return`${e.path}::${e.scope}`}function CR(e){return`${e.path}::${e.scope}`}function IR(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function Ow(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 vw(e,t){let n=hr("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function RR(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=Vl(e.unset,t,n,e.runtimeFieldCommands);for(let a of i.optionKeys)o(a,!0)}return r}function OR(e,t,n,r,o){let i=Oo(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=RR(t,r,o);for(let c of a.disabled)if(s.has(vw(c,e)))throw new l(`Option ${Ie("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of a.required)if(!s.has(vw(c,e)))throw new l(`Missing required option ${Ie("update",c)} for type "${e}"`,d.USAGE)}var xR=new Set(["order","rank"]),NR=Xs.filter(e=>!xR.has(e)),xw=["tags","closeReason",...NR],PR=["title","description","body","status","closeReason","completedAt","priority","type",...Xs,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],LR=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>te(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Mn(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"}],$R=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>rt(Na(e),fr,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>La(e)}],FR=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>rt(Pa(e),_r,"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=>$a(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Hl(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(`${Ie("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 MR(e){return Tw(await Ti(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 Yl(e){return e=Cr("update",e),bt(e)?await MR(e):Tw(e)}function DR(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 Kl(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 Jl(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);Kl({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Kl({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Kl({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function UR(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 GR(e){let t={};for(let n of xw)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function jR(e,t){let n=GR(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=Qa.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Ie("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 qR(e){if(De(e))return;let t=(n,r)=>{if(De(e,r))return;let o=Qa.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;Ua(n,Ie("update",r),i)};for(let n of xw)t(e[n],String(n));t(e.order??e.rank,"order"),Ne(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Ne(e.event,"--event","Use --clear-events to clear linked events.")}function KR(e,t){let n={};for(let r of PR)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 zR(e){let t=await j(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await et(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ne(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function HR(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return ye(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function BR(e){e.before&&(la(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Qi(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>ce(t,e.statusRegistry),tt()))}function WR(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 VR(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Xi(Di(e.options.parent),e.settings.id_prefix);if(_i(t))return{resolvedParentValue:t,warnings:[]};if(Gi(e.id,t,e.settings.id_prefix),await j(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:Ui(n,e.parentReferencePolicy).warnings}}function YR(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function JR(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await j(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await et(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ne(t,{schema:e.settings.schema}),r=e.options.type!==void 0?Ae(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=Qn({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function XR(e){if(!e.fieldFlags.status||se(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;_w(e);let t=Object.entries(e.fieldFlags).filter(([o,i])=>i&&o!=="status"&&o!=="closeReason"&&o!=="completedAt").map(([o])=>o),n=await hw(e);if(ql(n,e.options,e.statusRegistry,e.settings.governance.require_close_reason))return gw(e,n,t,ot,o=>bw(e,o));let r;if(t.length>0){let o=de(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0});r=await ot(e.id,o,e.global)}return bw(e,r)}async function bw(e,t){let n=await It(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),r=[...e.workflowTransitionWarnings,...t?.warnings??[],...n.warnings,"auto_routed_from_update_to_close"];return{item:n.item,changed_fields:[...t?.changed_fields??[],...n.changed_fields],warnings:r}}function QR(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")),se(e.metadata.status,n)??e.metadata.status}var ZR=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function eO(e,t){for(let n of ZR)e[n]!==void 0&&(delete e[n],t.push(n))}function tO(e,t,n,r,o){let i=gR(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}!ce(i,t.statusRegistry)&&ce(r,t.statusRegistry)&&eO(e.metadata,o)}function nO(e,t,n,r){if(t.options.status!==void 0&&tO(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!ce(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=te(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function rO(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&&ce(n,t.statusRegistry)&&!ce(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function oO(e,t,n,r){nO(e,t,n,r),rO(e,t,n,r)}function iO(e,t,n){let r=Ae(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=qt(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=Ae(t.options.type,t.typeRegistry);if(!o)throw new l(Ft(t.options.type,t.typeRegistry.types,Mt(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=o,r=o,n.push("type")}return OR(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),aO(e,t,r,n),r}function aO(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=gr(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=gr(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 sO(e,t){let n=new Set(t.map(o=>Za(o))),r=new Set;return e.filter(o=>{if(!n.has(Za(o)))return!0;let i=kR(o);return r.has(i)?!1:(r.add(i),!0)})}function cO(e,t,n){let r=t.filter(o=>!e.some(i=>Ow(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 lO(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=sO(r,t.dependencyUpdates.additions);let o=new Set(r.map(i=>Za(i)));for(let i of t.dependencyUpdates.additions){let a=Za(i);o.has(a)||(r.push(i),o.add(a))}}t.dependencyRemovals.length>0&&(cO(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(i=>Ow(o,i)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function dO(e,t,n){zl(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),zl(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),zl(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function zl(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 mO(e,t,n){kw(e,"files",t.options.file,t.fileUpdates.values,TR,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),pO(e,t,n),kw(e,"docs",t.options.doc,t.docUpdates.values,CR,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function kw(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 pO(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Sw(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Sw([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Sw(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=IR(r);n.has(o)||(t.push(r),n.add(o))}return t}function uO(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?Dt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Ei(Fn(a,r),o),n.changedFields.push("tags")}Hl(LR,t.options,n),_O(e,t,n.changedFields)}function fO(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=Si($n(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 _O(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=ge(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function hO(e,t,n,r){gO(e,t,n.changedFields),yO(e,t,n.changedFields),Hl($R,t.options,n),Ew(e,t,"sprint",r,n.changedFields),Ew(e,t,"release",r,n.changedFields),wO(e,t,n.changedFields),Hl(FR,t.options,n)}function gO(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 yO(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 Ew(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=ji(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=i.value,r.push(...i.warnings)}o.push(n)}}function wO(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)&&AR(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function vO(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Ha(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=Ba(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function bO(e,t,n){Aw(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),Aw(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)}ae(e[o],i)||(e[o]=i,n.push(o))}let r=Io(t.options.field,t.extensionRegistrations,Fa,Ma(t.runtimeFieldRegistry,(t.options.runtimeFieldCommands??[]).includes("update_many")?"update_many":"update",t.options));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))ae(e[o],i)||(e[o]=i,n.push(o))}function Aw(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function kO(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)||!ae(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 SO(e,t){kO(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,o=[],i=[],a=QR(e,t.options,t.statusRegistry,o),s=e.metadata,c={metadataRecord:s,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};oO(e,t,a,o),iO(e,t,o),lO(e,t,o),dO(e,t,o),mO(e,t,o),uO(e,t,c),fO(e,t,c),hO(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"))&&lo(e.metadata.id,e.metadata.dependencies),se(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),vO(e,t,o),bO(s,t,o);try{Ro(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:!ae(n[u],m[u]));return t.options.acceptanceCriteria!==void 0&&p.includes("acceptance_criteria")&&i.push(`acceptance_criteria_replaced:${$n(n.acceptance_criteria).length}:${$n(m.acceptance_criteria).length}`),{changedFields:p,warnings:i}}async function Nw(e,t,n,r={}){lt(e,"update","id"),t=await Yl(t);let o=A(process.cwd(),n.path);await O(o);let i=await E(o),a=F(i.schema),s=Je(i.schema),c=R(),m=Ye(c),p=P(i,c),u=i.governance.workflow_enforcement??"off",f=u==="off"?[]:On(i.schema),h=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][i.validation.parent_reference],_=Vl(t.unset,s,m,t.runtimeFieldCommands),g=new Set(_.optionKeys),y=new Set(_.metadataKeys);Jl(t),UR({definitions:DR(t),options:t,clearOptionKeys:g,clearItemMetadataKeys:y}),hR(e,t,y),jR(t,_),qR(t);let w=T(t.author,i.author_default),b=new Date,k=b.toISOString(),I=es(t.dep,i.id_prefix,k,w);lo(e,I.additions);let C=await _n({pmRoot:o,dependencies:I.additions,idPrefix:i.id_prefix,itemFormat:i.item_format,typeToFolder:p.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:i.schema}),N=bR(t.depRemove,i.id_prefix),L=gn("--comment",t.comment,k,w),D=t.ownershipMetadataBypass===!0&&L.values?{...L,values:L.values.map(x=>({...x,author:w}))}:L,J=gn("--note",t.note,k,w),H=gn("--learning",t.learning,k,w),pe=Fl(t.file),ue=Ml(t.test);ue.values=await Yn(ue.values,w,k);let $e=Dl(t.doc),Ve=[],G=await VR({id:e,options:t,unsetTargets:_,pmRoot:o,settings:i,typeRegistry:p,parentReferencePolicy:h}),re=await ER(t.blockedBy,y.has("blocked_by"),o,i.id_prefix,i.item_format,p.type_to_folder),mr=re.id,pr=[...G.warnings,...YR(re)],ur=xi(t,s,t.runtimeFieldCommands),Xt=KR(t,ur);if(!Object.values(Xt).some(Boolean))return zR({pmRoot:o,id:e,settings:i,typeRegistry:p});Ve.push(...await JR({options:t,fieldFlags:Xt,workflowEnforcement:u,typeWorkflows:f,statusRegistry:a,typeRegistry:p,pmRoot:o,id:e,settings:i}));let bo=await XR({options:t,fieldFlags:Xt,statusRegistry:a,workflowTransitionWarnings:Ve,global:n,id:e,pmRoot:o,settings:i,typeRegistry:p});if(bo)return bo;WR(t);let He=tt(),xt=Xt.parent&&!y.has("parent")||I.additions.some(x=>ca(x.kind,He)),ko=await xa({pmRoot:o,author:w,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:xt});try{let x=await HR({fieldFlags:Xt,clearedMetadataKeys:y,pmRoot:o,settings:i,typeToFolder:p.type_to_folder}),Qt,En,Nt=await Kn({pmRoot:o,settings:i,typeToFolder:p.type_to_folder,id:e,op:EO(t,r),author:w,message:t.message,resolveHistoryContext:()=>En,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(st){Qt=AO({document:st,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:a}),En=Qt?{recurrence:Qt}:void 0,x=x?.map(So=>So.id===st.metadata.id?structuredClone(st.metadata):So);let xs=SO(st,{options:t,settings:i,typeRegistry:p,statusRegistry:a,runtimeFieldRegistry:s,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:y,dependencyUpdates:I,dependencyRemovals:N,commentUpdates:D,noteUpdates:J,learningUpdates:H,fileUpdates:pe,testUpdates:ue,docUpdates:$e,resolvedParentValue:G.resolvedParentValue,resolvedBlockedByDependencyId:mr,runtimeFieldUpdates:ur,nowValue:b,nowIso:k,author:w,pmRoot:o});return BR({before:x,document:st,statusRegistry:a}),xs}});await ko();let Os=x?sa(x,x.map(st=>st.id===Nt.item.id?Nt.item:st),Nt.item.id):[];return{item:Nt.item,changed_fields:Nt.changedFields,warnings:[...Ve,...pr,...C,...Os,...Nt.warnings],...Qt===void 0?{}:{lifecycle_transition:Qt}}}finally{await ko()}}function EO(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function AO(e){if(e.recurrenceReason===void 0)return;let t=se(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!ce(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=se(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 ot(e,t,n){return Nw(e,t,n)}async function Pw(e,t,n,r){lt(r,"reopen","reason");let o=await Nw(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]="72dfe5b1-a1dd-573a-9f38-e66bf4e88100")}catch{}})();async function Xl(e,t,n,r){lt(e,"reopen","id"),lt(t,"reopen","reason"),pf(n);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=A(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 E(i)).schema),c=s.open_status,m=Zn(s),p=n.status??c,u=se(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 Pw(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:Q(["--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]="09bc9af5-45aa-5935-b627-cdef92af2acf")}catch{}})();async function Ql(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 Zl(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 E(A(process.cwd(),n.path)),o=Zn(F(r.schema)),i=await Xr(e,t.force===!0,n,pt(t,{},["start"])),a=i.item.id,s=await Ql(a,"claim",()=>ot(a,pt(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:a,action:"start_task",claim:i,update:s}}async function ed(e,t,n){let r=await E(A(process.cwd(),n.path)),o=F(r.schema);_a({...t,pause:!0},o);let i=o.open_status,a=await ot(e,pt(t,{status:i},["assignee","pause"]),n),s=a.item.id,c=await Ql(s,"update",()=>Qr(s,t.force===!0,n,t));return{id:s,action:"pause_task",update:a,release:c}}async function td(e,t,n,r){let o=await It(e,t,n,r),i=o.item.id,a=await Ql(i,"close",()=>Qr(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]="513b9fa5-5887-5d96-a137-ddf961f37dc8")}catch{}})();async function Lw(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options),o=e.force===!0||r.force===!0,i={...e.args,...r},a=r.next===!0,s=e.id??v(r,"id");if(i.start===!0){if(s)return yn(e,"start_task");ng(s,a,!0)}let c=a?await rg(o,e.global,i,i):await Xr(mo(e,r),o,e.global,i);return Ce(c,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function mo(e,t){let n=e.id??v(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function nd(e,t){return v(e.args,"reason")??v(e.args,"text")??v(t,"reason")??v(t,"text")}async function $w(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options);return r.releaseAssignment===!0?yn(e,"close_task"):Ce(await It(mo(e,r),nd(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function yn(e,t){let{changedFields:n,idOnly:r,runnerOptions:o}=we(e.args,e.options),i=mo(e,o),a=pt(o,{force:e.force===!0||o.force===!0}),s=t==="start_task"?await Zl(i,a,e.global):t==="pause_task"?await ed(i,a,e.global):await td(i,nd(e,o),a,e.global);return Ce(s,{changedFields:n,idOnly:r,compactEnvelope:n==="compact"&&!r})}async function Fw(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options),o=pt(r,{message:v(Object.hasOwn(r,"message")?r:e.args,"message")});if(o.pause===!0)return yn({...e,options:o},"pause_task");let i=await Qr(mo(e,o),e.force===!0||o.force===!0,e.global,o);return Ce(i,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function Mw(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options);return Ce(await Xl(mo(e,r),nd(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 ts(e,t){let n=Q(["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 ${Cu(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]="164daf80-c7f0-5707-bd7d-df96b52a1904")}catch{}})();var TO=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Gw="plan-step-",cd="draft",sd=["bug-investigation","feature-implementation","refactoring-sprint"],Dw={"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 CO(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(Dw,t)?Dw[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${sd.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${sd[0]}`]});return n.map(r=>({...r}))}function IO(e,t){return t>0?Math.round(e/t*100):0}function jw(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 We(e){return Array.isArray(e)?e.flatMap(t=>zn(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?zn(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 qw(e,t=cd){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ks.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${Ks.join(", ")}`,d.USAGE);return r}function ld(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=zs.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${zs.join(", ")}`,d.USAGE);return r}function Kw(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 RO(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Hs.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${Hs.join(", ")}`,d.USAGE);return n}function OO(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=nc.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${nc.join(", ")}`,d.USAGE);return n}function xO(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 rd=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function NO(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(!rd.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 ${[...rd].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...rd].join(",")}`}});return r}function dd(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 md(e){let t=dd(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 pd(e){let t=dd(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 ud(e){let t=dd(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 PO(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=IO(t.completed,t.total),t}function LO(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${Gw}${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 or(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 Uw(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 $O(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=Uw(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=or(e,a);if(i.has(s.id))continue;i.add(s.id);let c=Uw(s);if(c){o.push({from_step:s.id,...c});continue}r.push(s)}return{targets:r,skipped:o}}function FO(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 MO(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function DO(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 qe(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((a,s)=>a.order-s.order),r=PO(n),o=MO(n),i={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??cd,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:DO(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 Ke(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&&!Gc(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function zw(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 UO(e){let t=A(process.cwd(),e.path);await O(t);let n=await E(t);return{pmRoot:t,settings:n}}async function Hw(e,t){let n=P(e.settings,R()),r=await j(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 ne(r,{schema:e.settings.schema});return zw(o.document.metadata),{document:o.document,itemId:r.id}}function GO(e){let t=[];for(let n of We(e.related))t.push(`id=${n},kind=related`);for(let n of We(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of We(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function jO(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 qO(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||We(e.dependsOn).length>0||We(e.link).length>0}function KO(e){let t=e.stepTitle?.trim()||void 0,n=jw(e.step),r=e.template?.trim()?CO(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function zO(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 ${sd[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 HO(e,t){let n=ld(e.stepStatus,"pending"),r=fd(e,"depends_on"),o=Pe(e.file).map(md),i=Pe(e.test).map(pd),a=Pe(e.doc).map(ud),s=S();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 BO(e){let t=KO(e),n=qO(e);if(zO(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[HO(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=S();return{steps:t.stepTitles.map((o,i)=>({id:`${Gw}${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 Bw(e,t,n=[]){de(e,t),n.length>0&&cf(t,n)}async function WO(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=qw(e.mode,cd),i=RO(e.harness),a=e.fromSearch?.trim(),s=jO(e),{steps:c,hasPerStepDetailOptions:m}=BO(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?T(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:T(e.author,n.settings.author_default),blockedBy:void 0,dep:GO(e),message:e.message??(a?`plan create (search: ${a})`:"plan create")};Bw(e,f);let h=await Wt(f,t),_=await _e({pmRoot:n.pmRoot,settings:n.settings,id:h.item.id,op:"plan_create_metadata",author:T(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 k=e.resumeContext?.trim();return k&&(y.metadata.plan_resume_context=k,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=qe(_.item,"brief");return{action:"create",plan:g,step:c[0],next_actions:Ke(h.item.id,g),warnings:[...h.warnings],generated_at:S()}}async function VO(e,t,n){let r=OO(t.depth),o=xO(t.fields),{document:i,itemId:a}=await Hw(n,e),s=qe(i.metadata,o===null?r:"deep");return{action:"show",plan:o===null?s:NO(s,o),next_actions:Ke(a,s),warnings:[],generated_at:S()}}function YO(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 ut(e){let t=T(e.options.author,e.ctx.settings.author_default),n,r=await _e({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){zw(o.metadata);let i=F(e.ctx.settings.schema);if(ce(o.metadata.status,i)||Gc(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=YO(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 JO(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let o=ld(t.stepStatus,"pending"),i=t.allowMultipleActive===!0,{document:a,resultStep:s,itemId:c}=await ut({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(p){let u=p.length+1;Ww(p,void 0,o,i);let f=XO(p,t,{order:u,title:r,status:o});return p.push(f),{changedSteps:[f.id],resultStep:f}}}),m=qe(a.metadata,"standard");return{action:"add-step",plan:m,step:s,next_actions:Ke(c,m),warnings:[],generated_at:S()}}function Ww(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 XO(e,t,n){let r=fd(t,"depends_on"),o=Pe(t.file).map(md),i=Pe(t.test).map(pd),a=Pe(t.doc).map(ud),s=S();return{id:LO(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 fd(e,t){let n=We(e.dependsOn).map(p=>({id:p,kind:t})),r=We(e.related).map(p=>({id:p,kind:"related"})),o=We(e.blocks).map(p=>({id:p,kind:"blocks"})),i=We(e.blockedBy).map(p=>({id:p,kind:"blocked_by"})),a=We(e.link),s=Kw(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 od(e,t,n,r){let{document:o,resultStep:i,itemId:a}=await ut({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let p=or(c,r.stepRef),u=S(),f=r.finalStatus??ld(t.stepStatus,p.status),h=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return Ww(c,p.status==="in_progress"?p.id:void 0,f,h),QO(p,t,f,u),m.metadata.updated_at=u,{changedSteps:[p.id],resultStep:p}}}),s=qe(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:Ke(a,s),warnings:[],generated_at:S()}}function QO(e,t,n,r){ZO(e,t,n),ex(e,t),e.status=n,e.updated_at=r,tx(e,n,r)}function ZO(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 ex(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(md),o=Pe(t.test).map(pd),i=Pe(t.doc).map(ud);r.length>0&&(e.files=id(e.files,r)),o.length>0&&(e.tests=id(e.tests,o)),i.length>0&&(e.docs=id(e.docs,i))}function id(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 tx(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function nx(e,t,n,r,o){let{document:i,itemId:a,resultStep:s}=await ut({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(m){let p=or(m,r),u=m.filter(h=>h.id!==p.id),f=Math.max(1,Math.min(o,u.length+1));return u.splice(f-1,0,p),u.forEach((h,_)=>{h.order=_+1,h.updated_at=S()}),m.length=0,m.push(...u),{changedSteps:[p.id],resultStep:p}}}),c=qe(i.metadata,"standard");return{action:"reorder-step",plan:c,step:s,next_actions:Ke(a,c),warnings:[],generated_at:S()}}async function rx(e,t,n,r){let{document:o,itemId:i,resultStep:a}=await ut({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(c){let m=or(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=qe(o.metadata,"standard");return{action:"remove-step",plan:s,step:a,next_actions:Ke(i,s),warnings:[],generated_at:S()}}async function ox(e,t,n,r){let o=fd(t,Kw(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 ut({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(p,u){let f=or(p,r),h=f.linked_items??[],_=y=>`${y.kind}:${y.id}`,g=new Set(h.map(_));for(let y of o){let w=_(y);g.has(w)||(h.push(y),g.add(w))}if(f.linked_items=h,f.updated_at=S(),i){let y=u.metadata.dependencies??[],w=k=>`${k.kind}:${k.id}`,b=new Set(y.map(w));for(let k of o){let I=k.kind==="depends_on"?"blocked_by":k.kind,C={id:k.id,kind:I,created_at:S(),author:T(t.author,n.settings.author_default)};b.has(w(C))||(y.push(C),b.add(w(C)))}u.metadata.dependencies=y}return{changedSteps:[f.id],resultStep:f}}}),m=qe(a.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ke(s,m),warnings:[],generated_at:S()}}async function ix(e,t,n,r){let o=We(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 ut({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let p=or(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=S(),{changedSteps:[p.id],resultStep:p}}}),c=qe(i.metadata,"standard");return{action:"unlink",plan:c,step:s,next_actions:Ke(a,c),warnings:[],generated_at:S()}}async function ad(e,t,n,r){let o=FO(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=T(t.author,n.settings.author_default),{document:a,itemId:s}=await ut({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,p){let u=S();if(r==="decision"){let h=p.metadata.plan_decisions??[];return h.push({ts:u,author:i,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),p.metadata.plan_decisions=h,{changedSteps:[]}}if(r==="discovery"){let h=p.metadata.plan_discoveries??[];return h.push({ts:u,author:i,text:o}),p.metadata.plan_discoveries=h,{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=qe(a.metadata,"deep");return{action:r,plan:c,next_actions:Ke(s,c),warnings:[],generated_at:S()}}async function ax(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 ut({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=qe(o.metadata,"brief");return{action:"resume",plan:a,next_actions:Ke(i,a),warnings:[],generated_at:S()}}async function sx(e,t,n){let r=qw(t.mode??"approved","approved"),{document:o,itemId:i}=await ut({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=qe(o.metadata,"brief");return{action:"approve",plan:a,next_actions:Ke(i,a),warnings:[],generated_at:S()}}function Vw(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function cx(e,t){let n=qe(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ke(e.itemId,n),warnings:Vw(t),generated_at:S()}}function lx(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 dx(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:lx(e.parent,e.planItemId,o)};Bw(e.options,i,["description",...Object.keys(n)]);let a=await Wt(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 mx(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=S()}}async function px(e,t,n){let r=We(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=P(n.settings,R()),a=Ae(o,i);if(!a)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let s=t.materializeParent?.trim()||e,c=t.materializeTags,m=await Hw(n,e),p=(m.document.metadata.plan_steps??[]).slice(),{targets:u,skipped:f}=$O(p,r);if(u.length===0){if(f.length>0)return cx(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let h=await dx({targets:u,parent:s,planItemId:m.itemId,resolvedTypeName:a,tags:c,options:t,pmRoot:n.pmRoot}),{document:_,itemId:g}=await ut({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(w){return mx(w,u,h),{changedSteps:u.map(b=>b.id)}}}),y=qe(_.metadata,"standard");return{action:"materialize",plan:y,materialized:h,...f.length>0?{materialize_skipped:f}:{},next_actions:Ke(g,y),warnings:Vw(f),generated_at:S()}}function ux(e){if(e.subcommand==="create")return e;let t=jw(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:de(e.options,{...e.options,stepTitle:t[0]})}:e}function Rt(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function wn(e,t){let n=Rt(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function fx(e){let t=wn(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 _x={create:(e,t)=>WO(e.options,e.global,t),show:(e,t)=>VO(Rt(e,"show"),e.options,t),"add-step":(e,t)=>JO(Rt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=wn(e,"update-step");return od(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=wn(e,"complete-step");return od(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=wn(e,"block-step");return od(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=fx(e);return nx(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=wn(e,"remove-step");return rx(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=wn(e,"link");return ox(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=wn(e,"unlink");return ix(n.id,e.options,t,n.stepRef)},decision:(e,t)=>ad(Rt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>ad(Rt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>ad(Rt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>ax(Rt(e,"resume"),e.options,t),approve:(e,t)=>sx(Rt(e,"approve"),e.options,t),materialize:(e,t)=>px(Rt(e,"materialize"),e.options,t)};function hx(e){let t=_x[e];if(!t)throw Re({command_path:"plan",token:e,allowed:TO});return t}async function Yw(e){let t=await UO(e.global),n=ux(e),r=await hx(n.subcommand)(n,t);return r.action==="show"?r:{...r,mutation_receipt:ts(r,t.pmRoot)}}import gx from"fast-json-patch";import _d 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]="f3145f17-e911-571b-9da3-f014e6fdde1c")}catch{}})();async function Jw(e,t,n){let r=await Bf(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:Xw(n),recovered:!0}}function yx(e,t){return jf(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Xw(e){let t=qn(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Et(mt(t))}async function wx(e,t,n,r){let o=await an(e,t,n,r),i=o.located?await Nf({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function vx(e,t){let n=Pr(e),r=Pr(t),o=gx.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 bx(e){let t=await hh({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>Jw(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function kx(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Xw(t),originalRaw:null}}function Sx(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 Ex(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await oe(e.existingItemPath,e.resolvedOriginalRaw),await _d.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await oe(e.existingItemPath,e.resolvedOriginalRaw);return}await _d.rm(e.restoredItemPath,{force:!0})}async function Ax(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 hd(e,t,n,r){let o=A(process.cwd(),r.path);await O(o);let i=await E(o),a=P(i,R()),s=await wx(o,e,i,a.type_to_folder),c=s.id,{raw:m,entries:p}=await Sf(s.historyPath,c);if(p.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let u=yx(t,p),f=qf(qn(p,u.historyIndex),u),h=Nr(f,{schema:i.schema});if(h.metadata.id!==c)throw new l(`Restore target resolved to item ${h.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let _=(s.located?await Jw(s.located,i,p):null)?.raw??null,g=T(n.author,i.author_default),y=await Ar(o,c,i.locks.ttl_seconds,g,!!n.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms,{waitPolicy:"progress"}),w=y.release;try{let{loadedItemUnderLock:b,existingItemPath:k}=await bx({pmRoot:o,subject:s,settings:i,typeRegistry:a,historyRawBeforeLock:m,currentItemRawBeforeLock:_,history:p}),I="toon",C=kx(b,p);Kf(o,C.document),h.metadata.pm_format_version=Cc(Math.max(Ni(h.metadata),Ni(C.document.metadata))),zf(xo(o),Ni(h.metadata));let N=Sx({document:C.document,author:g,force:n.force,enforcement:i.governance.ownership_enforcement,resolvedId:c}),L=vx(C.document,h),D=await Mr({pmRoot:o,settings:i,operation:"restore",author:g,before:C.document,after:h});await mi({pm_root:o,operation:"restore",before:C.document,after:h,changed_fields:L,sdk:zi({pmRoot:o,settings:i,typeToFolder:a.type_to_folder})});let J=dt(h,{format:I,schema:i.schema}),H=gt(o,h.metadata.type,c,I,a.type_to_folder),pe=await y.fence(async()=>{let G=await Kt(o,g),re;try{await oe(H,J),k&&H!==k&&await _d.rm(k);let mr=Ue({nowIso:S(),author:g,op:"restore",before:C.document,after:h,message:n.message,context:D.decisions.length===0?void 0:{workflow_policies:D.decisions}});try{await Gt(s.historyPath,mr)}catch(pr){throw await Ex({existingItemPath:k,resolvedOriginalRaw:C.originalRaw,restoredItemPath:H}),pr}re=await zt({pmRoot:o,preferredFormat:i.item_format,typeToFolder:a.type_to_folder,schema:i.schema,itemPath:H,previousItemPath:k??void 0,document:h})}finally{await G()}return re}),ue=await Ax({restoredItemPath:H,historyPath:s.historyPath,before:C.document,after:h});xn({id:h.metadata.id,op:"restore",item_type:h.metadata.type,previous_status:C.document.metadata.status,status:h.metadata.status,previous:rn(C.document.metadata,L),current:rn(h.metadata,L),changed_fields:L});let $e=p[u.historyIndex],Ve=Gn(p,!0);return{item:h.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:Ve===null?null:Ve+u.historyIndex+1,entry_ts:$e.ts,entry_op:$e.op},changed_fields:L,warnings:[...D.warnings,...b?.recovered?["restore_unreadable_item_recovered"]:[],...s.historyPolicyWarnings,...N,...pe,...ue]}}finally{await 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]="86acbe76-ed18-52be-b561-4819c648e88e")}catch{}})();var Zw=2,yd="update-many",Tx=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),Cx=["--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(", "),Ix={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"},Rx=[{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"}],ev=e=>{let t={};for(let[n,r]of Object.entries(e))Tx.has(n)||r!==void 0&&(t[n]=r);return t},Ox=e=>Object.keys(ev(e)).length>0,tv=e=>typeof e=="string"?e.trim():e,xx=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},gd=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},Nx=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??tv(e)},Px={priority:xx,estimatedMinutes:gd,order:gd,rank:gd,regression:Nx},Lx=(e,t)=>{if(t!==void 0)return(Px[e]??tv)(t)},ns=(e,t)=>ae(e,t),$x=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],Fx=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,Mx=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",Qw=(e,t)=>t===void 0?void 0:e[t],ir=e=>Array.isArray(e)?e.length:0,Dx=(e,t,n)=>{let r=n[e.addKey],o=Qw(n,e.removeKey),i=ir(r),a=ir(o),s=n[e.clearKey]===!0,c=Qw(n,e.replaceKey)===!0;if(![s,c,i>0,a>0].includes(!0))return;let m=$x(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:Mx({replace:c,clear:s,removeCount:a}),clear:s,replace:c,add_count:i,remove_count:a,before_count:Fx(e.field,m)}}},Ux=(e,t)=>{let n=[];for(let r of Rx){let o=Dx(r,e,t);o!==void 0&&n.push(o)}return n},Gx=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],jx=(e,t)=>{if(![t.tags!==void 0,ir(t.addTags)>0,ir(t.removeTags)>0].includes(!0))return;let n=Gx(e.tags),r=t.tags===void 0?n:Dt(t.tags),o=Fn(r,t.addTags),i=Ei(o,t.removeTags).slice().sort((s,c)=>s.localeCompare(c)),a=n.slice().sort((s,c)=>s.localeCompare(c));if(!ns(a,i))return{field:"tags",before:n,after:i}},qx=(e,t)=>{let n=e.acceptance_criteria,r=Si($n(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(!ns(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},Kx=(e,t,n)=>{for(let[r,o]of Object.entries(Ix)){let i=n[r];if(i===void 0)continue;let a=t[o],s=Lx(r,i);ns(a,s)||e.push({field:o,before:a,after:s})}},zx=(e,t,n,r)=>{let o=xi(n,r,["update_many"]);for(let[i,a]of Object.entries(o)){let s=t[i];ns(s,a)||e.push({field:i,before:s,after:a})}},Hx=(e,t,n,r)=>{if(n===void 0||n.length===0)return;let o=Wl(n,r,Ye(R()),["update_many"]);for(let i of o){let a=t[i];a!==void 0&&e.push({field:i,before:a,after:null})}},Bx=(e,t,n={})=>{let r=e,o=[],i=jx(r,n);if(i&&o.push(i),Kx(o,r,n),ir(n.addAc)>0||ir(n.removeAc)>0){let a=qx(r,n);a!==void 0&&o.push(a)}return o.push(...Ux(r,n)),zx(o,r,n,t),Hx(o,r,n.unset,t),{id:e.id,changes:o}},Wx=(e,t)=>Ff(e,t,{strict:!0,flagLabel:"--filter-status"}),Vx=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)},Yx=[({update:e})=>{e.priority!==void 0&&qt(e.priority)},({update:e,settings:t})=>{e.unset!==void 0&&e.unset.length>0&&Wl(e.unset,Je(t.schema),Ye(R()),["update_many"])},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=P(t,R());if(!Ae(e.type,r))throw new l(Ft(e.type,r.types,Mt(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!se(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid status value "${e.status}". Allowed: ${n.join(", ")}`,d.USAGE,{code:"invalid_argument_value",field:"status",value:e.status,allowed:n})}},({update:e})=>{e.deadline!==void 0&&te(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&Mn(e.estimatedMinutes,"estimated-minutes")}],Jx=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let i of Yx)i(o)},Xx=async e=>{let t=await ki(e.pmRoot,yd,e.rollbackId,Zw),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Oa(e.pmRoot,t,{author:e.options.update?.author,message:n,force:e.options.update?.force}),o=r.rows.filter(i=>i.status==="skipped").length;return{...on({applied:r.restored_ids.length,skipped:o,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,skipped_count:o,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},Qx=async e=>{let t={schema_version:Zw,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:T(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await bi(e.pmRoot,yd,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},Zx=(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))},wd=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},eN=async e=>{let t=A(process.cwd(),e.path);await O(t);let n=await E(t);return{pmRoot:t,settings:n,statusRegistry:F(n.schema),runtimeFieldRegistry:Je(n.schema)}},tN=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Br(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 Xx({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},nN=async e=>{Wx(e.options.status,e.runtime.statusRegistry);let t=await At(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=Bx(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?i:{...i,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await At(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:Zx(e.options.list?.ids,r)}},rN=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:[],...wd(e)}),oN=e=>({...on({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:[],...wd(e)}),iN=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=kc(de(e.options.update,{...e.options.update,message:r,runtimeFieldCommands:["update_many"]})),s=await Ki({pmRoot:e.pmRoot,itemId:i.id,checkpointId:e.checkpointId},()=>ot(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:Lt(a)})}}return{rows:t,updatedIds:n}},aN=async e=>{if(e.plan.actionable.length===0)return oN(e.plan);let t=S(),n=vi(yd,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 Qx({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 iN({pmRoot:e.runtime.pmRoot,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{...on({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,...wd(e.plan)}},nv=async(e,t)=>{let n=wi(e.rollback),r=await eN(t);n===void 0&&(e={...e,update:kc(await Yl(e.update))});let o=ev(e.update);if(Vx(e.list),n!==void 0)return tN({runtime:r,rollbackId:n,options:e,global:t,updateSummary:o});if(!Ox(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${Cx}), or pass --dry-run for a filter-only preview.`,d.USAGE);Jx(e.update,r.settings,r.statusRegistry,r.pmRoot),Jl(e.update);let i=await _n({pmRoot:r.pmRoot,dependencies:es(e.update.dep,r.settings.id_prefix,S(),T(e.update.author,r.settings.author_default)).additions,idPrefix:r.settings.id_prefix,itemFormat:r.settings.item_format,typeToFolder:P(r.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),a=await nN({options:e,global:t,runtime:r,updateSummary:o,dependencyWarnings:i});return await _n({pmRoot:r.pmRoot,dependencies:es(e.update.dep,r.settings.id_prefix,S(),T(e.update.author,r.settings.author_default)).additions,idPrefix:r.settings.id_prefix,itemFormat:r.settings.item_format,typeToFolder:P(r.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:a.listed.items.map(s=>({id:s.id,createdAt:s.created_at})),schema:r.settings.schema}),e.dryRun===!0?rN(a):aN({runtime:r,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 sN(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 cN(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 lN(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 rv(e,t,n){let r=sN(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:en(r),a=[t.since,t.eventType].some(_=>_!==void 0),s=lN(t.since),c=$r(t.limit),m=await Xn(e,{...t,...a?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,a].includes(!0)},n,{input:await fa(i===void 0?t:{add:i},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:_=>Jn(_),createEntry:_=>r===void 0?_:{..._,format:"json",data:r,event_type:cN(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(_=>{let g=[_.format==="json",_.data!==void 0].every(Boolean),y=[s===void 0,Date.parse(_.created_at)>=(s??Number.POSITIVE_INFINITY)].includes(!0),w=[!p,_.event_type===p].includes(!0);return[!a,[g,y,w].every(Boolean)].includes(!0)}),f=a?ol(u,c):u,h=f.filter(_=>_.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:h}:t.includeMeta===!0?{structured_event_count:h}:{}}}import kN from"node:path";import dN from"node:fs/promises";import ov 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]="4e476a2f-8735-53e9-88c3-b43bfc34e1f5")}catch{}})();var mN="templates",pN=".json",uN=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,fN=hi.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),_N=new Set(fN);function hN(e){let t=e.trim();if(!uN.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 iv(e){return ov.join(e,mN)}function av(e,t){return ov.join(iv(e),`${t}${pN}`)}async function gN(e){await O(e)}function sv(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function yN(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(n==="priority"){t[n]=String(qt(r));continue}if(_N.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 sv(t)}function wN(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 sv(r)}function vN(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=wN(r.options,t),i=S();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 bN(e,t){let n=await X(av(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return vN(n,t)}async function vd(e,t,n){let r=A(process.cwd(),n.path);await gN(r);let o=hN(e),i=yN(t);if(Object.keys(i).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let a=S(),s=av(r,o),c=a;await z(s)&&(c=(await bN(r,o)).created_at);let m={name:o,created_at:c,updated_at:a,options:i},p=await E(r);return await dN.mkdir(iv(r),{recursive:!0}),await Qe({pmRoot:r,filePath:s,raw:`${JSON.stringify(m,null,2)}
23
- `,op:"templates:save",author:T(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 mv=["list","show","apply","lint"],SN="schema-types",EN="schema-statuses",AN="schema-fields";function rs(){let e=R();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function pv(){let{profiles:e,warnings:t}=hu(rs());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:bu(n.definition)})),warnings:t,generated_at:S()}}function uv(e){let t;try{t=si(e,rs())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...ku(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function fv(e){let t;try{t=si(e,rs())}catch(o){throw new l(o instanceof Error?o.message:String(o),d.USAGE)}let{resolved:n}=t,r=Vu(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:S()}}function TN(e,t){return kN.join(e,"templates",`${t}.json`)}async function CN(e,t){let n=await X(TN(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 cv(e,t,n,r){let o=new Map;for(let i of r.templates){let a=await CN(e,i.name);a!==void 0&&o.set(i.name,a)}return{typesRaw:await X(wt(e,t.files.types,yt.types)),statusesRaw:await X(wt(e,t.files.statuses,yt.statuses)),fieldsRaw:await X(wt(e,t.files.fields,yt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function ar(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 lv(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:ar(t.types.changes),statuses:ar(t.statuses.changes),fields:ar(t.fields.changes),workflows:ar(t.workflows.changes.map(i=>({key:i.type,status:i.status}))),config:ar(t.config.changes),templates:ar(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:S()}}async function IN(e){await O(e)}function RN(e){try{let t=si(e,rs());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function _v(e,t,n){let r=A(process.cwd(),n.path);await IN(r);let o=RN(e),i=o.profile,a=o.warnings,s=t.dryRun===!0,c=await E(r),m=ci(c.schema);if(s){let w=await cv(r,m,c,i),b=dv(i,w);return lv(i,b,!1,!0,[...a])}let p=T(t.author,c.author_default),u=Uf(c),f=!!t.force,h=[...a],_=[],g=async w=>{_.push(await ct(r,w,c.locks.ttl_seconds,p,f,u.force_required_for_stale_lock,c.locks.wait_ms))},y;try{await g(SN),await g(EN),await g(AN);let w=await cv(r,m,c,i);if(y=dv(i,w),y.types.changed){let b=wt(r,m.files.types,yt.types);await Qe({pmRoot:r,filePath:b,raw:ai(y.types.file),op:"profile:apply-types",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let k=new Set(i.types.map(C=>du(C).name)),I=y.types.file.definitions.filter(C=>k.has(C.name));await $_(r,I,h,"profile:apply-type-folder"),h.push(...await Y({path:b,scope:"project",op:"profile:apply-types"}))}if(y.statuses.changed){let b=wt(r,m.files.statuses,yt.statuses);await Qe({pmRoot:r,filePath:b,raw:vu(y.statuses.file),op:"profile:apply-statuses",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),h.push(...await Y({path:b,scope:"project",op:"profile:apply-statuses"}))}if(y.fields.changed){let b=wt(r,m.files.fields,yt.fields);await Qe({pmRoot:r,filePath:b,raw:yu(y.fields.file),op:"profile:apply-fields",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),h.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 k=li(b.key);k!==void 0&&di(c,k,b.value)}c.schema.type_workflows=y.workflows.result,await Oe(r,c,"profile:apply-config")}for(let b of y.templates.changes)b.status!=="unchanged"&&await vd(b.name,{...b.options},n)}finally{for(let w of _.reverse())try{await w()}catch{}}return lv(i,y,y.changed,!1,h)}function dv(e,t){try{return Yu(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import FN from"node:fs/promises";import Sd 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 gv=10,vn="https://schema.unbrained.dev/pm/eval-query-set/v1";var os={schema:vn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},it=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},ON=new Set(["keyword","semantic","hybrid"]);function hv(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 xN(e,t,n){if(t.size===0)return 0;let r=e.map(s=>t.has(s)?1:0),o=hv(r,n),i=Array.from({length:t.size},()=>1),a=hv(i,n);return a===0?0:o/a}function NN(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 bd(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 PN(e,t,n){return n<=0?0:bd(e,t,n)/n}function LN(e,t,n){return t.size===0?0:bd(e,t,n)/t.size}function yv(e,t,n){return{ndcg:xN(e,t,n),mrr:NN(e,t,n),precision:PN(e,t,n),recall:LN(e,t,n),relevant_total:t.size,retrieved_relevant:bd(e,t,n)}}function wv(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 $N(e,t){if(typeof e!="object"||e===null)throw new it(`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 it(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new it(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(i=>typeof i!="string"))throw new it(`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 it(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!ON.has(n.mode)))throw new it(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.minimum===void 0?{}:{minimum:Bh(n.minimum)},...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function kd(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==vn)throw new it(`Unsupported eval query set schema; expected "${vn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new it('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new it("Eval query set must contain at least one query");return{schema:vn,queries:n.map((r,o)=>$N(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 MN=Sd.join("search","eval-queries.json"),Ed={schema:vn,examples:[JSON.stringify(os)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},DN=new Set(["keyword","semantic","hybrid"]),UN=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!DN.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},GN=e=>{if(e===void 0||e==="")return gv;let t=$m(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},jN=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},Vt=e=>Math.round(e*1e4)/1e4,qN=async e=>{try{return await FN.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Ed,examples:[`echo '${JSON.stringify(os)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},KN=(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,Ed)}},zN=e=>{try{return kd(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Ed)}},HN=async e=>zN(KN(await qN(e),e)),BN=async(e,t,n,r)=>{let o=e.mode??t,i=(await Vr(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(s=>s.id).filter(s=>typeof s=="string"),a=yv(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:Wh(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:Vt(a.ndcg),mrr:Vt(a.mrr),precision:Vt(a.precision),recall:Vt(a.recall)}}},WN=(e,t,n,r)=>{let o=wv(n);return{k:e,query_count:t.length,aggregate:{ndcg:Vt(o.ndcg),mrr:Vt(o.mrr),precision:Vt(o.precision),recall:Vt(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)}},vv=async(e,t)=>{let n=A(process.cwd(),t.path);await O(n);let r=GN(e.k),o=UN(e.mode),i=jN(e.failUnder),a=e.queries?Sd.resolve(process.cwd(),e.queries):Sd.join(n,MN),s=await HN(a),c=[],m=[];for(let p of s.queries){let{report:u,metrics:f}=await BN(p,o,r,t);m.push(f),c.push(u)}return WN(r,c,m,i)};import{readFile as VN,writeFile as Sv}from"node:fs/promises";import YN 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]="74f8a3ee-f0dc-568d-86d1-8c0b9649e2e2")}catch{}})();var bv=["item","history","relationship","json"];function JN(e){let t=e.trim().toLowerCase();if(bv.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${bv.join(", ")}.`,d.USAGE)}function XN(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 Ad(e,t){try{return await VN(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function QN(e){let t=A(process.cwd(),e.path);return await z(ie(t))?E(t):null}function ZN(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function kv(e,t){try{return e()}catch(n){if(n instanceof l&&n.context?.code==="item_identity_conflict"){let r=o=>o.endsWith(`
24
- `)?o:`${o}
25
- `;throw await Sv(t.outputPath,`<<<<<<< pm ours
26
- ${r(t.oursRaw)}||||||| pm base
27
- ${r(t.baseRaw)}=======
28
- ${r(t.theirsRaw)}>>>>>>> pm theirs
29
- `,"utf8"),new l(`Unresolved identity for ${t.itemPath}: both snapshots remain in conflict markers. ${n.message}`,n.exitCode,{...n.context,recovery:{suggested_retry:"git status --short"},nextSteps:["Preserve both source snapshots and establish item identity before resolving. Do not stage conflict markers as a completed merge; pm health and storage validation reject them."]})}throw n}}async function Ev(e,t){let n=JN(e.artifact),r=XN(e.prefer),o=YN.resolve(e.outputPath??e.oursPath),[i,a,s]=await Promise.all([Ad(e.basePath,"base"),Ad(e.oursPath,"ours"),Ad(e.theirsPath,"theirs")]),c,m,p=[],u={},f={baseRaw:i,oursRaw:a,theirsRaw:s,outputPath:o,itemPath:e.itemPath??o};if(n==="history"){let _=await kv(()=>rh(i,a,s),f);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 _=oh(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 QN(t),g=ZN(e.itemPath??o,_),y=Ye(R()),w=await kv(()=>ih(i,a,s,{format:g,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"}),f);if(c=w.merged,p.push(...w.conflict_fields),u.item={fields_from_theirs:w.fields_from_theirs,union_fields:w.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let b=vf(c,{format:g,schema:_?.schema,extensionFieldNames:y}),k=b.metadata,I=[...new Set([...w.fields_from_theirs,...w.union_fields,...w.conflict_decisions.map(C=>C.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:w.fields_from_theirs,unionFields:w.union_fields,mergedFieldHashes:Object.fromEntries(I.map(C=>[C,nh(C==="body"?b.body:k[C])])),decisions:w.conflict_decisions,operation:await sh(process.cwd(),e.itemPath,a)}}}else{let _=ah(i,a,s,{preferred:r});c=_.merged,p.push(..._.conflict_paths),u.json={paths_from_theirs:_.paths_from_theirs}}if(await Sv(o,c,"utf8"),m!==void 0){let _=await lh(m);_!==null&&(u.receipt=sn(_))}let h=[];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.`;h.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&&h.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:h,generated_at: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]="3fe6f853-6742-5305-b722-0cc74547f367")}catch{}})();async function Av(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await ch(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Ht(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Ht(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:[{...sn(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await ta(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as eP}from"node:fs/promises";import tP 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]="4d506b3c-f1c1-5642-a258-45d93ba64d81")}catch{}})();var nP=4;function Tv(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 rP(e,t){let n=[];for(let r of t){let o;try{o=await eP(tP.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=_h(a,r.item_id).find(c=>c.receiptId===r.receipt_id);s===void 0||!fh(s)||s.eventTimestamp===void 0||fi(s.eventTimestamp,uh)>=0||n.push({...r,original_event_ts:s.eventTimestamp})}return n}async function oP(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 Ht(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 iP(e){try{return{status:"fulfilled",value:await Ht(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 aP(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 sP(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=>ta(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}function cP(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 lP(e,t){if(e.force===!0)throw new l("Automatic staging cannot accept forced reconciliation.",d.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let n={...e,stage:!1},{stageLosslessMergeReconciliation:r,resolveMergeSettlementGlobal:o}=await import("./stage-4SQHVI3O.js"),i=await o(t),a=await is({...n,dryRun:!0},i);return r({preview:a,dryRun:e.dryRun===!0,global:i,apply:()=>is({...n,dryRun:!1},i)})}async function is(e,t){return e.stage===!0?lP(e,t):dP(e,t)}async function dP(e,t){let n=e.dryRun===!0,r=A(process.cwd(),t.path),o=await zr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=Tv(o),a=await rP(r,i.coordinates),s=await Zi(r),c=s??r,m=await dh(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"}});mh(m.receipts.map(G=>G.id),m,n);let p=await oP({candidates:a,options:e,global:t}),u=m.receipts,f=await Av({cwd:s,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),h=new Set(f),_=new Map;for(let G of u.filter(re=>!h.has(re.id))){let re=_.get(G.item_id)??[];re.push(G),_.set(G.item_id,re)}let g=Object.fromEntries([..._].map(([G,re])=>[G,{merge:{receipts:re.map(sn)}}])),y=Object.fromEntries([..._].map(([G,re])=>[G,{gitWorkspaceRoot:s,receipts:re}])),w=await ra({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(G=>G.id)),k=[..._.keys()].filter(G=>!b.has(G)),I=await W_(k,nP,G=>iP({id:G,dryRun:n,options:e,global:t,auditContext:g[G],mergeReceiptProof:y[G]}));aP({receiptOnlyIds:k,results:I,repair:w});let C=await sP({dryRun:n,pendingReceipts:u,repair:w,receiptWorkspaceRoot:c}),N=await aa({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),L=p===0?o:await zr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),D=Tv(L),J=N.checks.every(G=>G.status==="ok"),H=n?u.length===0:C+f.length===u.length,pe=[w.totals.failed===0,J,H,D.count===0,!D.truncated].every(Boolean),ue=i.truncated||D.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=cP(u.length,pe),Ve=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",ue,$e,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:pe?["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.",ue,$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(G=>G!==void 0);return{ok:pe,dry_run:n,repair:w,receipts:{pending_before:u.length,reconciled:C,abandoned:f.length,summaries:u.map(sn),unstaged_durable_receipt_ids:m.unstaged_durable_receipt_ids,missing_history_references_before:i.count,legacy_disposition_eligible:a.length,legacy_disposition_recorded:p,missing_history_references_after:D.count},validation:N,guidance:Ve,generated_at:N.generated_at}}import{createHash as mP}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]="c583f859-9204-565b-b143-59aba53c3e9c")}catch{}})();var Ov=1,xv=/^[A-Za-z0-9_-]+$/,pP=100,Cv=1e3;var CV=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function at(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 uP(e){return mP("sha256").update(en({type:at(e.type),author:at(e.author),item:at(e.item),harness:at(e.harness),agent_instance:at(e.agentInstance),provenance:at(e.provenanceFilter)})).digest("hex").slice(0,24)}function Iv(e,t){let n={version:Ov,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 fP(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Ov,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 _P(e,t){let n=e.trim();if(n.length===0||n.length>4096||!xv.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(!fP(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function hP(e){let t=e??pP;if(!Number.isSafeInteger(t)||t<0||t>Cv)throw new l(`Mutation event limit must be an integer from 0 to ${Cv}.`,d.USAGE,{code:"invalid_event_limit"});return t}function gP(e,t){let n=e?.trim();if(!n)return{};if(xv.test(n))return{cursor:_P(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 yP(e,t){if(t.verify)return Rv(e,t);let n=await xc(e,t),r=n.result;if(r===null&&n.repair_needed)try{await Ef(e,{lockWaitMs:0})&&(r=(await xc(e,t)).result)}catch{}return r===null?Rv(e,t):{...r,source:"derived_index"}}async function Rv(e,t){try{return{...await Af(e,t),source:"authoritative_history"}}catch(n){throw n instanceof l?n:new l("Mutation events are unavailable because authoritative history could not be read.",d.GENERIC_FAILURE,{code:"event_index_unavailable",why:Lt(n)})}}function wP(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 as(e={}){let t=A(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=hP(e.limit),r=wP(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 E(t),i=o.agent_identity.identity_vocabulary,a=Uh(o.agent_identity.harness_signals),s=Gh({provenance:e.provenanceFilter},a),c=at(e.harness),m=uP(e),{cursor:p,sinceTimestamp:u}=gP(e.since,m),f={verify:e.verify===!0,...p?{after_ts:p.ts,after_stream_id:p.stream_id,after_stream_offset:p.stream_offset}:u?{since_ts:u}:{},ops:at(e.type),authors:at(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,g])=>c.includes(g)).map(([g])=>g):void 0,agent_instances:at(e.agentInstance),provenance:[...s].map(([g,y])=>({dimension:g,values:[...y]})),stream_ids:at(e.item),limit:n},h=await yP(t,f),_=h.events.map(g=>({...r==="row"?{cursor:Iv(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:structuredClone(g.recorded_entry??g.entry)}:{},...e.provenance===!0?{provenance:jh(g.entry,i,{itemId:g.stream_id,version:g.stream_offset+1})}:{}}));return{integrity:e.verify===!0?"verified":"unverified",...h.verified_streams===void 0?{}:{verified_streams:h.verified_streams},events:_,count:_.length,has_more:h.has_more,cursor_mode:r,...h.events.length===0?{}:{next_cursor:Iv(h.events[h.events.length-1],m)},source:h.source,...e.provenanceSummary===!0?{provenance_summary:qh(h.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]="8e3b8e8c-5c05-5c68-bfe2-cb3ca0a17a20")}catch{}})();var vP="1h",bP="now",kP="+1d";function Yt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Nv(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,inheritFocus:n.inheritFocus,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return de(n,r)}async function Pv(e,t,n,r){let o=Nv(e,t,n),i=[];return Yt(i,"start",n.start??bP),n.end!==void 0?Yt(i,"end",n.end):Yt(i,"duration",n.duration??vP),Yt(i,"location",n.location),Yt(i,"timezone",n.timezone),n.allDay===!0&&Yt(i,"all_day","true"),o.event=[i.join(",")],Wt(o,r)}function Lv(e,t,n){return Pv("Meeting",e,t,n)}function $v(e,t,n){return Pv("Event",e,t,n)}function Fv(e,t,n){let r=Nv("Reminder",e,t),o=[];return Yt(o,"at",t.at??kP),Yt(o,"text",t.text??e),r.reminder=[o.join(",")],Wt(r,n)}import po from"node:crypto";import{cp as Mv,lstat as SP,mkdir as bn,readFile as cr,readdir as Cd,rename as Gv,rm as Rd,writeFile as ss}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]="66cb8c82-3760-5628-a1de-69e417cf0292")}catch{}})();var jv="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var qv=M.join("runtime","workspace-snapshots"),EP=new Set(["checkpoints","locks","runtime","search","transactions"]),AP=/^[a-z0-9][a-z0-9._-]*$/,sr="sdk-workspace-transaction",Td={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Kv={renameEntry:Gv,removeEntry:async e=>{await Rd(e,{recursive:!0,force:!0})}},Id=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=await Fu(this.lockPath,sr);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await cr(this.lockPath,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Workspace writer lock has invalid structure");let r=n;if(r.id!==sr||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await oe(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
30
- `)}finally{await t()}}};async function zv(e,t=""){let n=await Cd(M.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((i,a)=>i.name.localeCompare(a.name))){if(t.length===0&&EP.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 zv(e,i));else if(o.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function Hv(e){let t=await zv(e),n=po.createHash("sha256"),r=[],o=0;for(let a of t){let s=await cr(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:jv,fingerprint:i,files:t,bytes:o},contents:r}}function Dv(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
31
- `).filter(t=>t.trim().length>0).length}async function TP(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 cr(M.join(e,a))]));for(let[a,s]of i)n.set(a,s)}return n}function Od(e){if(!AP.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 Bv(e,t){return yr(`workspace_snapshot_${e}`,t,{codes:{capacity:Td.capacity.code,permission:Td.permission.code,resource:Td.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 kn(e){return M.join(e,qv)}function Wv(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 Vv(e,t){try{return JSON.parse(await cr(e,"utf8"))}catch(n){throw Fe(n)?Wv(t):n}}async function Uv(e,t,n){try{await Rd(e,{recursive:n})}catch(r){throw Fe(r)?Wv(t):r}}async function CP(e,t,n=Kv){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 IP(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 RP(e,t){return Od(t),/^[a-f0-9]{64}$/.test(t)?t:(await Vv(M.join(kn(e),"refs",`${t}.json`),t)).fingerprint}async function xd(e,t={}){if(t.name!==void 0&&(Od(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 Hv(e),o=kn(e),i=M.join(o,"objects",n.fingerprint),a=!1;try{a=(await SP(i)).isDirectory()}catch(s){if(!(s instanceof Error&&"code"in s&&Fe(s)))throw s}if(!a){let s=M.join(o,"objects",`.create-${process.pid}-${po.randomUUID()}`);await Bv("create_object",async()=>{await bn(M.join(s,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let p=M.join(s,"files",m);await bn(M.dirname(p),{recursive:!0}),await ss(p,r[c])}await ss(M.join(s,"manifest.json"),`${JSON.stringify(n,null,2)}
32
- `,"utf8"),await bn(M.dirname(i),{recursive:!0})}),a=await CP(s,i)}if(t.name!==void 0){let s={name:t.name,fingerprint:n.fingerprint},c=M.join(o,"refs");await bn(c,{recursive:!0});let m=M.join(c,`.ref-${process.pid}-${po.randomUUID()}`);await ss(m,`${JSON.stringify(s,null,2)}
33
- `,"utf8"),await Gv(m,M.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:a}}async function uo(e,t){let n=await RP(e,t),r=await Vv(M.join(kn(e),"objects",n,"manifest.json"),t);if(r.schema!==jv||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 Nd(e){let t=kn(e),n=await Cd(M.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&Fe(o))return[];throw o}),r=await Cd(M.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&Fe(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>uo(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await cr(M.join(t,"refs",o),"utf8"))))}}async function Pd(e,t){let n=await uo(e,t),{manifest:r,contents:o}=await Hv(e),i=new Map(r.files.map((u,f)=>[u,o[f]])),a=await TP(M.join(kn(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),h=a.get(u);f!==void 0&&h!==void 0&&f.equals(h)&&m.delete(u)}let p=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let f=Dv(i.get(u)),h=Dv(a.get(u));return{path:u,current_entries:f,target_entries:h,removed_entries:Math.max(0,f-h)}}).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 Yv(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 Ar(e,sr,o,r,!1,!1,i),s=a.release,c=new Id(No(e,sr),r,o);c.start(),await c.refreshNow();let m,p=!1,u=!1;try{let f=await Pd(e,t),h=await uo(e,t),_=await xd(e),g=h.fingerprint,y=kn(e),w=M.join(y,"objects",g,"files"),b=M.dirname(e),k=M.basename(e);m=M.join(b,`.${k}.restore-${po.randomUUID()}`);let I=M.join(b,`.${k}.backup-${po.randomUUID()}`);await Bv("restore_stage",async()=>{await bn(m,{recursive:!0}),await Mv(w,m,{recursive:!0,force:!1}),await bn(M.join(m,"runtime"),{recursive:!0}),await Mv(y,M.join(m,qv),{recursive:!0,force:!1})});let C=await Lf({pmRoot:m,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:f.changed_file_count,removed_file_count:f.removed_file_count,removed_item_count:f.removed_item_count,affected_history_stream_count:f.affected_history_stream_count,removed_history_entry_count:f.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:i}),N=M.relative(m,C.historyPath).replaceAll("\\","/");await c.stop(),u=!0;let L=No(m,sr),D=m;return await a.fence(async()=>{await bn(M.dirname(L),{recursive:!0}),await ss(L,await cr(No(e,sr)),{flag:"wx"}),p=!0,await IP(D,e,I,Kv,async()=>{c.start(),u=!1,await c.refreshNow()})}),await c.stop(),u=!0,{manifest:h,plan:f,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:N,audit_operation:"workspace_snapshot_restore"}}catch(f){throw m!==void 0&&!p&&await Promise.allSettled([Rd(m,{recursive:!0,force:!0})]),f}finally{try{u||await c.stop()}catch{}finally{await s()}}}async function Jv(e,t){Od(t);let n=kn(e);if(!/^[a-f0-9]{64}$/.test(t))return await Uv(M.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Nd(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Uv(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]="d755ad5c-14c7-567f-8467-63b3fce6796d")}catch{}})();function fo(e){let t={...e.args,...e.options};return de(e.options,t)}function Ot(e,t){let n=v(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function lr(e){return typeof e=="string"?[e]:be(e)}function Xv(e){return vv(fo(e),e.global)}function Qv(e){let t=fo(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 as({cwd:v(t,"cwd"),pmRoot:v(t,"path"),since:v(t,"since"),type:lr(t.type),author:lr(t.author),item:lr(t.item),limit:t.limit===void 0?void 0:Ge(t.limit,"limit"),full:t.full===!0,...t.verify===!0?{verify:!0}:{},...r===void 0?{}:{cursorMode:r},...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:lr(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:lr(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:lr(t.provenanceFilter)}})}function Zv(e){let t=fo(e),n=Ot(t,"subcommand");if(n==="install")return I_({dryRun:t.dryRun===!0,preCommitHook:t.preCommitHook===!0},e.global);if(n==="reconcile")return is({dryRun:t.dryRun===!0,author:v(t,"author"),message:v(t,"message"),force:t.force===!0,stage:t.stage===!0},e.global);if(n==="report")return ph({includeReconciled:t.includeReconciled===!0,cwd:v(t,"cwd")});if(n==="driver")return Ev({artifact:Ot(t,"artifact"),basePath:Ot(t,"basePath"),oursPath:Ot(t,"oursPath"),theirsPath:Ot(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 eb(e){let t=fo(e),n=Ot(t,"subcommand");if(n==="position")return Vh(e.global);if(n!=="snapshot")throw Re({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=v(t,"snapshotAction")??Ot(t,"snapshot_action"),o=A(process.cwd(),e.global.path);if(r==="create")return xd(o,{name:v(t,"name")});if(r==="list")return Nd(o);let i=Ot(t,"target");if(r==="inspect")return uo(o,i);if(r==="delete")return Jv(o,i);if(r==="restore")return t.dryRun===!0?Pd(o,i):Yv(o,i,{force:t.force===!0,author:v(t,"author"),message:v(t,"message"),lockTtlSeconds:Ge(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Ge(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 cs(e){let t=fo(e),n=Ot(t,"title");return e.action==="meet"?Lv(n,t,e.global):e.action==="event"?$v(n,t,e.global):Fv(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 tb(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:be(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 sL from"node:fs/promises";import yb 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 ls(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 OP(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)||(ls(f,a,u,o,"min")&&(a=f,o=u),ls(f,s,u,i,"max","max")&&(s=f,i=u))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:i}}function nb(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:h,raw:_})=>OP(h,_)),i=0,a=0,s=null,c=null,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY;for(let h of o){if(i+=h.lines,a+=h.bytes,h.oldest_ts!==null){let _=Date.parse(h.oldest_ts);ls(_,m,h.id,s?.id??null,"min")&&(m=_,s={id:h.id,ts:h.oldest_ts})}if(h.newest_ts!==null){let _=Date.parse(h.newest_ts);ls(_,p,h.id,c?.id??null,"max")&&(p=_,c={id:h.id,ts:h.newest_ts})}}let u=r===0?[]:[...o].sort((h,_)=>_.bytes-h.bytes||h.id.localeCompare(_.id)).slice(0,r),f=r===0?[]:[...o].sort((h,_)=>_.lines-h.lines||h.id.localeCompare(_.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 PP}from"node:child_process";import ib from"node:path";import{promisify as LP}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 rb=1;function xP(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 Ld(e){if(e===null)return{format_version:rb,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!==rb||!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(!xP(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 $P=LP(PP),FP=50,ob=1e3,MP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function ab(e){let t=e.trim().toLowerCase();if(!MP.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 DP(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 _o(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 UP(e){let t=e??FP;if(!Number.isSafeInteger(t)||t<0||t>ob)throw new l(`Improvement observation limit must be an integer from 0 to ${ob}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function sb(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 GP(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=ab(n.metric),o=DP(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 qP(e,n.revision),a=_o(n.source,"source"),s=_o(n.itemId,"itemId"),c=_o(n.unit,"unit"),m=_o(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:sb(n.observedAt??S(),"observedAt"),...i,author:T(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(en(p)).digest("hex").slice(0,24),...p}}function jP(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 qP(e,t){let n=_o(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await $P("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:xo(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function KP(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 cb(e,t={}){let n=A(process.cwd(),t.path);await O(n);let r=await E(n),o=await GP(n,r,e),i=ib.join(n,"improvement-ledger.json"),a=await Fi({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=Ld(s),m=jP(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:`${en(c)}
34
- `,result:o})}});return{changed:a.changed,observation:a.result,ledger_path:"improvement-ledger.json"}}async function lb(e={}){let t=A(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=e.metric===void 0?void 0:ab(e.metric),r=e.since===void 0?void 0:sb(e.since,"since"),o=UP(e.limit),i=Ld(await X(ib.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])=>KP(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]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();var zP=1e4,db=1e5,HP=1e3,BP=30,WP=["append","comment","docs","file","learning","note","test_run"];function VP(e){let t=e??zP;if(!Number.isSafeInteger(t)||t<1||t>db)throw new l(`History analytics event limit must be an integer from 1 to ${db}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function mb(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 YP(e){let t=e?.trim();if(!t)return new Date(Date.now()-BP*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 pb(e,t){let n=VP(t.eventLimit),r=YP(t.since),o=[],i=r,a=!1;for(;o.length<n;){let s=await as({pmRoot:e,since:i,limit:Math.min(HP,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 JP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function XP(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 QP(e){return WP.some(t=>e.startsWith(t))}function ub(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 ZP(e,t,n){let r=new Map,o=new Map,i=new Map;for(let a of t){let s=JP(a.entry,e),c=XP(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=ub(r,s);u.events+=1,QP(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 eL(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&&(ub(e,a).defectEscapes+=1)}}}function tL(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 nL(e,t,n,r,o,i){let{buckets:a,lastCloseValue:s}=ZP(e,t,r);return eL(a,s,n),{dimension:e,status:a.size===0?"unavailable":"available",rows:[...a].map(([c,m])=>tL(c,m,o,i)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function rL(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 oL(e,t,n){let r=og(t),o=ig(e,Rr,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 fb(e,t=Li,n={}){let r=mb(n.minimumSample);return{...oL(e.events.map(o=>o.entry),t,r),window:e.receipt}}function _b(e,t,n,r={}){let o=mb(r.minimumSample),i=rL(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(a=>nL(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 iL=32;function aL(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 ho(e,t){let n=aL(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 h=f.indexOf("="),_=f.slice(0,h).trim(),g=f.slice(h+1).trim();if(_==="unit"&&g.length>0)p=g;else if(_==="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,iL)}function hb(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 gb(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 cL(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function lL(e,t,n,r,o){let i=Ur(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=cL([...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 dL(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function mL(e){let t=yb.join(e,"history");if(!await z(t))return[];await Nn({path:t,scope:"project"});let n=(await sL.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,i)=>o.localeCompare(i)),r=[];for(let o of n){let i=yb.join(t,o),a=await X(i);a!==null&&(await Nn({path:i,scope:"project"}),r.push({id:o.slice(0,-6),raw:a}))}return r}async function pL(e,t){let n=[],r=S();for(let o of ho(t.observe,r))n.push(await cb({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 uL(e,t,n){let r={};return t.byAssignee&&(r.assignee=Ur(e,"assignee",n)),t.byTag&&(r.tag=Ur(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=Ur(e,"priority",n)),r}async function fL(e,t,n,r,o){let i={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},a=o.provenanceCoverage||o.fleetAttribution?await pb(e,i):void 0;return{provenanceCoverage:o.provenanceCoverage&&a?fb(a,n.agent_identity?.harness_signals,i):void 0,fleetAttribution:o.fleetAttribution&&a?_b(a,t,r,i):void 0}}function _L(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:S()}}async function $d(e,t={}){let n=A(process.cwd(),e.path);await O(n);let r=await E(n),o=await pL(e,t),i=P(r,R()),a=F(r.schema),s=t.fieldUtilization?await Wf(n,r.item_format,i.type_to_folder,void 0,r.schema):await ye(n,r.item_format,i.type_to_folder,void 0,r.schema);await Pf({pmRoot:n,settings:r,itemIds:s.map(k=>k.id),commandLabel:"stats"});let c=Ji(a),m=lL(s,i.types,a.definitions.map(k=>k.id),c,t.includeEmpty===!0),p=await mL(n),u=0;for(let k of p)u+=dL(k.raw);let f=t.storage?nb(p):void 0,h=t.metadataCoverage?f_(s,c):void 0,_=uL(s,t,c),g=t.fieldUtilization?__(s):void 0,y=t.measurements===!0||o.length>0?await lb({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:b}=await fL(n,s,r,a.terminal_statuses,t);return _L({items:s.length,history_streams:p.length,history_entries:u},m.byType,m.byStatus,m.omitted,{metadataCoverage:h,breakdowns:_,storage:f,fieldUtilization:g,improvementLedger:y,recordedObservations:o,provenanceCoverage:w,fleetAttribution:b})}import hL from"node:fs/promises";import Jt 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 Eb=Jt.join("runtime","telemetry","events.jsonl"),Ab=Jt.join("runtime","telemetry","state.json"),gL=Jt.join("runtime","telemetry"),yL=20,Tb=tn.filter(e=>e.lifecycle==="deprecated"),wb=["status","flush","stats","clear"],vb=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Fd=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,bb=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},wL=e=>({command:Fd(e.event.command,"<unknown>"),eventType:Fd(e.event.event_type,"unknown"),eventSchemaVersion:bb(e.event.schema_version),clientSchemaVersion:bb(e.client_schema_version)}),vL=()=>({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:{}}),bL=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},kL=e=>{let t=e?.command_resolution;return Fd(t,"")||void 0},Cb=(e,t)=>{e[t]=(e[t]??0)+1},SL=(e,t)=>{let n=bL(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=kL(t);r!==void 0&&Cb(e.resolution_counts,r)},EL=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,kb=(e,t)=>{t!==void 0&&e.add(t)},AL=(e,t)=>{let n=wL(t),r=e.get(n.command)??vL();r.count+=1,r.max_attempts=Math.max(r.max_attempts,EL(t.attempts)),Cb(r.event_type_counts,n.eventType),kb(r.event_schema_versions,n.eventSchemaVersion),kb(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&SL(r,t.event.payload),e.set(n.command,r)},TL=(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:vb(r,.5),duration_p95_ms:vb(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)}:{}}},CL=e=>{let t=(e??"status").trim().toLowerCase();if(wb.includes(t))return t;throw Re({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:wb,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Dd=()=>{throw new l("--limit must be a positive integer",d.USAGE)},Ib=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Dd():e,IL=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Dd():Ib(Number.parseInt(t,10))},RL=e=>e===void 0?yL:typeof e=="number"?Ib(e):typeof e=="string"?IL(e):Dd(),OL=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},xL=e=>{try{let t=JSON.parse(e);return OL(t)?t:void 0}catch{return}},NL=e=>e===null?[]:e.split(`
35
- `).map(t=>t.trim()).filter(t=>t.length>0),Rb=e=>{let t=NL(e),n=[],r=0;for(let o of t){let i=xL(o);i===void 0?r+=1:n.push(i)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},PL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),LL=e=>{try{let t=JSON.parse(e);return PL(t)?t:{}}catch{return{}}},Md=async e=>{let t=await X(e);return t===null||t.trim().length===0?{}:LL(t)};function $L(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 FL(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 Sb(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 Tb){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=FL(s.days,t,o);Object.keys(c).length>0&&(n[i.alias]={canonical:i.canonical,days:c})}return n}async function ML(e,t,n){let r=$L(n),o=await Md(t),i=Sb(o.alias_usage,r);if(JSON.stringify(o.alias_usage??{})===JSON.stringify(i))return i;try{await jc(async()=>{let a=await Md(t);if(a.alias_usage===void 0)return;let s=Sb(a.alias_usage,r);JSON.stringify(a.alias_usage)!==JSON.stringify(s)&&await oe(t,`${JSON.stringify({...a,alias_usage:s},null,2)}
36
- `)},e,250)}catch{}return i}var ds=e=>e??null,ms=async e=>{let t=await E(e),n=Jt.join(e,Eb),r=Jt.join(e,Ab),o=await X(n),i=Rb(o),a=await Md(r),s=Jf();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:ds(a.last_attempted_flush_at),last_successful_flush_at:ds(a.last_successful_flush_at),last_failed_flush_at:ds(a.last_failed_flush_at),last_failed_flush_error:ds(a.last_failed_flush_error)}},DL=e=>{let t=new Map;for(let n of e)AL(t,n);return[...t.entries()].map(([n,r])=>TL(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},UL=async(e,t)=>({action:"telemetry",subcommand:"status",status:await ms(t.globalPmRoot),generated_at:S()}),GL=async(e,t)=>{let n=await ms(t.globalPmRoot);await t_(t.globalPmRoot);let r=await ms(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:S()}},jL=async(e,t)=>{let n=RL(e.limit),r=await X(t.queuePath),o=Rb(r),i=DL(o.entries),a=i.slice(0,n),s=await E(t.globalPmRoot),c=await ML(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(h=>h.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:Tb.map(p=>p.alias).filter(p=>c[p]===void 0),alias_usage_retention_days:s.telemetry.retention_days,generated_at:S()}},qL=async(e,t)=>jc(async()=>{let n=await E(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 Oe(t.globalPmRoot,n,"telemetry:clear");let o=Jt.join(t.globalPmRoot,gL),i=await z(o);return await hL.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:i&&!await z(o),queue_exists_after:await z(t.queuePath),state_exists_after:await z(t.statePath),status:await ms(t.globalPmRoot),generated_at:S()}},t.globalPmRoot),KL={status:UL,flush:GL,stats:jL,clear:qL};async function Ob(e,t){let n=CL(e.subcommand),r=ht(process.cwd());return KL[n](e,{globalPmRoot:r,queuePath:Jt.join(r,Eb),statePath:Jt.join(r,Ab)})}(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 xb=20;function zL(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return xb;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?xb:t}function Ud(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=fi(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=zL();return t.length>n?t.slice(t.length-n):t}async function ps(e){await _e({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=Ud([...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 Nb(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 Gd(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=Nb(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]="626315a0-7ee9-500d-bb7a-9bcd33eae209")}catch{}})();var HL=[{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}],BL=[{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 us(e,t){let n=`${e}
37
- ${t}`;for(let r of HL)if(r.regex.test(n))return{code:r.code};return null}function Pb(e,t){for(let[n,r]of[["stdout",e],["stderr",t]]){let o=BL.find(i=>i.regex.test(r));if(o)return{code:o.receiptCode,stream:n}}}function Lb(e,t){return{trackerPath:e.path?.trim()||(process.env.PM_PATH?.trim()?t:void 0),noExtensions:e.noExtensions}}function $b(e,t={}){let n=t.trackerPath?.trim();return Q(["test",e,"--list",...t.noExtensions===!0?["--no-extensions"]:[],...n?["--pm-path",n]:[]],t.platform)}import{cp as QL,lstat as ZL,mkdir as e$,readlink as t$,realpath as Kd,stat as n$,symlink as Db}from"node:fs/promises";import{execFile as r$}from"node:child_process";import q from"node:path";import{promisify as o$}from"node:util";import{execFile as WL}from"node:child_process";import{readdir as VL,realpath as YL}from"node:fs/promises";import JL from"node:path";import{promisify as XL}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]="e67d1a06-77f7-5e86-8f15-bde8b6db0d5a")}catch{}})();var jd=XL(WL),Fb=".agents/pm/merge-receipts";async function Mb(e,t,n){let r=JL.join(n,"merge-receipts"),o=(await VL(r).catch(c=>{if(Fe(c))return[];throw c})).filter(c=>c.endsWith(".json")),{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-7XGVHYAO.js"),a=o.length===0?new Map:await i(e,r,o,C_,await YL(r),{failOnReadError:!0}),s={cwd:t,env:T_(),timeout:1e4,maxBuffer:1024*1024,windowsHide:!0};await jd("git",["rm","-q","-r","--cached","--ignore-unmatch","--",Fb],s);for(let[c,m]of a){let p=jd("git",["hash-object","-w","--stdin"],s),u=p.child.stdin;u!==null&&(u.on("error",()=>{p.child.kill()}),u.end(m));let f=(await p).stdout.trim();if(!/^(?:[a-f\d]{40}|[a-f\d]{64})$/u.test(f))throw new Error("Invalid snapshot receipt object identity.");await jd("git",["update-index","--add","--cacheinfo","100644",f,`${Fb}/${c}`],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]="6638f21c-6cf5-5dec-a0d9-91ae323afce3")}catch{}})();var i$=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),fs=o$(r$);async function a$(e,t){let n=await _s(q.join(e,".git"));if(!n||n.isDirectory()&&!await _s(q.join(e,".git/HEAD")))return!1;let r=Object.fromEntries(Object.entries(process.env).filter(([o])=>!o.toUpperCase().startsWith("GIT_")));await fs("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:r,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await fs("git",["-C",t,"remote","remove","origin"],{env:r,timeout:1e4,windowsHide:!0});try{await fs("git",["-C",t,"rev-parse","--verify","--quiet","HEAD"],{env:r,timeout:1e4,windowsHide:!0})}catch(o){if(o.code===1)return!0;throw o}return await fs("git",["-C",t,"read-tree","HEAD"],{env:r,timeout:1e4,windowsHide:!0}),!0}async function s$(e,t,n,r){await a$(e,t)&&n&&r!==!1&&await Mb(e,t,n)}function qd(e){return e.split(q.sep).some(t=>i$.has(t.toLowerCase()))}function go(e){return e===".."||e.startsWith(`..${q.sep}`)||q.isAbsolute(e)}async function _s(e){try{return await n$(e)}catch(t){if(!Fe(t))throw t;return}}async function hs(e){let t=[],n=e;for(;q.dirname(n)!==n;)try{return q.join(await Kd(n),...t)}catch(r){if(!Fe(r))throw r;t.unshift(q.basename(n)),n=q.dirname(n)}return q.join(await Kd(n),...t)}async function c$(e,t,n){let r=q.relative(t,await hs(e));if(!go(r))return r;let o=[],i=e;for(;q.dirname(i)!==i;){let a=await hs(i),s=n.find(([,c])=>c===a);if(s)return q.join(s[0],...o);o.unshift(q.basename(i)),i=q.dirname(i)}return r}async function Ub(e,t,n,r){let o=[],i=[],a=await Kd(e),s=await hs(q.resolve(t));if(![q.relative(a,s),q.relative(s,a)].every(go))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await e$(q.dirname(t),{recursive:!0}),await s$(a,t,n,r),await QL(a,t,{recursive:!0,force:!0,async filter(c){let m=q.relative(a,c);if(!m)return!0;if(qd(m))return!1;if(q.basename(c).toLowerCase()==="node_modules"){if((await _s(c))?.isDirectory()){let p=await hs(c),u=q.relative(a,p);if(!go(q.relative(p,a))||!go(u)&&(qd(u)||!u.split(q.sep).some(f=>f.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${m}`);o.push([m,p])}return!1}return(await ZL(c)).isSymbolicLink()?(i.push([m,q.resolve(q.dirname(c),await t$(c)),(await _s(c))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[c]of o)await Db(q.resolve(a,c),q.join(t,c),"junction");for(let[c,m,p]of i){let u=await c$(m,a,o);if(go(u)||qd(u))throw new Error(`Source symlink must target included workspace source: ${c}`);await Db(q.resolve(t,u),q.join(t,c),p)}}import{execFile as l$}from"node:child_process";import{constants as Gb}from"node:fs";import{access as d$,open as m$}from"node:fs/promises";import jb 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]="b42f8889-4b5a-5391-b8e4-b68084e20a49")}catch{}})();var u$=p$(l$);function f$(e){let t=e.match(/^\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([\w./\\:-]+))(?=\s|$)/u),n=t?.[1]??t?.[2]??t?.[3];return n&&!/[$`%&|<>^;]/u.test(n)?n:void 0}function _$(e,t,n){return process.platform==="win32"?(t===1||t===9009)&&n.split(/\r?\n/u).some(r=>r.trim()===`'${e}' is not recognized as an internal or external command,`):t!==126&&t!==127?!1:n.split(/\r?\n/u).some(r=>t===127&&(r.endsWith(`: ${e}: not found`)||r.endsWith(`: ${e}: command not found`))||t===126&&r.includes(`: ${e}: `)&&r.endsWith(": bad interpreter: No such file or directory"))}async function h$(e,t){let n=e.trim();if(!n||/[\r\n]/u.test(n))return!1;try{let r=await m$(jb.resolve(t,n),Gb.O_RDONLY|Gb.O_NONBLOCK),o;try{let a=Buffer.alloc(256),{bytesRead:s}=await r.read(a,0,a.length,0);if(o=a.toString("utf8",0,s),s===a.length&&!o.includes(`
38
- `))return!1}finally{await r.close()}let i=o.match(/^#![ \t]*(\/[^ \t\n]+)(?:[ \t\n]|$)/u)?.[1];if(!i)return!1;try{return await d$(i),!1}catch(a){return _t(a)}}catch{return!1}}async function qb(e,t,n,r){if(/[;&|<>()`$\r\n]/u.test(e))return!1;let o=f$(e);if(!o||!_$(o,t.exitCode,t.stderr))return!1;let i=process.platform==="win32",a=i?jb.join(n.SystemRoot??"C:\\Windows","System32","where.exe"):"/bin/sh",s=i?[o]:["-c",'command -v "$1"',"pm-linked-test-resolution",o];try{let{stdout:c}=await u$(a,s,{env:n,cwd:r,timeout:1e3,windowsHide:!0});return!i&&h$(c,r)}catch(c){let m=c;if(m.killed||m.signal)return!1;let p=m.code;return p===1||!i&&p===127}}import{spawn as ik}from"node:child_process";import{cp as zb,mkdir as Vd,mkdtemp as ak,open as Hd,readdir as Bd,rm as wo,symlink as g$}from"node:fs/promises";import{tmpdir as sk}from"node:os";import le 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 Kb(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"&&us(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:Q(i),suggested_retry_args:i}})}function zd(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,...n_(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: ${Q([...i,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${Q(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${Q(a)}`]}:{},recovery:{missing:["--run"],suggested_retry:Q(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]="c7e43b2c-eac0-57a2-84bb-33b474dc545c")}catch{}})();var ws=20*1024*1024,y$=3e3,w$=1e4,v$=5e3,Hb=120,b$=new Set(["locks","extensions","runtime"]),k$=new Set(["history","index","search","extensions","locks","runtime"]),S$=[/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],E$=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,A$=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,T$=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 Yd(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 C$(){return Yd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",y$)}function I$(){return Yd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",w$)}function R$(){return Yd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",v$)}function O$(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 x$(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 Jd(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 N$(e){let t=e??"project";if(!ft.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function bs(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(dn.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${dn.join(", ")}`,d.USAGE)}function ck(e){return pn(e??"source","--workspace-context")}function lk(e,t,n){return n?t:pn(e.workspace_context_mode,"linked test")??t}function dk(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:bs(e.pm_context_mode)}function mk(e,t){return e==="auto"?t?"tracker":"schema":e}function P$(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 L$(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 $$(e,t){let n={};if(!e)return n;for(let r of e){let o=Zr(r,t);if(o)for(let[i,a]of Object.entries(o))n[i]=a}return n}function F$(e,t){if(!e)return[];let n=[];for(let r of e){let o=eo(r,t);o&&n.push(...o)}return[...new Set(n)]}function M$(e){let t=ia(e);return oa(t).some(n=>Jc(n)!==null)}function pk(e){let t=ia(e);return oa(t).some(n=>{let r=Jc(n);if(!r)return!1;let o=Ch(r);return o?T$.has(o.subcommand):!1})}function gs(e){if(e)return kh.has(e.subcommand)?Vn(e.args,Sh)?.subcommand:e.subcommand}function Bb(e,t){if(e==="npx"||e==="bunx")return Xc(t)?.command;if(e==="pnpm")return gs(Vn(t,yh));if(e==="npm")return gs(Vn(t,wh));if(e==="yarn")return gs(Vn(t,vh));if(e==="bun")return gs(Vn(t,bh))}function ys(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function uk(e){let t=e.split(" ").filter(a=>a.length>0),n=Eh(t);if(n.length===0)return!1;let[r,...o]=n,i=Ih.get(r);if(i){let a=o.findIndex(s=>i.test(s));return a>=0&&uk(o.slice(a+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?D$(o):U$(r,o)}function D$(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function U$(e,t){return e==="npx"||e==="bunx"?ys(Xc(t)?.command):e==="pnpm"||e==="npm"?ys((e==="pnpm"?Ah(t):Th(t))?.command)||ys(Bb(e,t)):(e==="yarn"||e==="bun")&&ys(Bb(e,t))}function G$(e){if(Rh(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function j$(e){return e?e.map(q$):[]}function q$(e){let t=e.trim(),n=ff(t)?Ii(fe(e,"--add"),"--add"):{command:t},r=ve(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return Hr(r),{command:r,path:ve(n.path),scope:N$(n.scope),timeout_seconds:K$(ve(n.timeout_seconds),ve(n.timeout)),pm_context_mode:va(ve(n.pm_context_mode),"--add"),workspace_context_mode:pn(ve(n.workspace_context_mode),"--add"),env_set:Zr(ve(n.env_set),"--add"),env_clear:eo(ve(n.env_clear),"--add"),shared_host_safe:wa(ve(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:un(ve(n.assert_stdout_contains)),assert_stdout_regex:nr(ve(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:un(ve(n.assert_stderr_contains)),assert_stderr_regex:nr(ve(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:ba(ve(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:ka(ve(n.assert_json_field_equals),"--add"),assert_json_field_gte:Sa(ve(n.assert_json_field_gte),"--add"),note:ve(n.note)}}function ve(e){let t=e?.trim();return t&&t.length>0?t:void 0}function K$(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(ge(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function z$(e){return e?e.flatMap(t=>{let n=to(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);Hr(o)}return n}):[]}function H$(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=fe(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 B$(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 W$(e){try{e.stdin?.end()}catch{}}function fk(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=Hb?t:`${t.slice(0,Hb-3)}...`}function _k(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Wd(e){try{process.stderr.write(`${e}
39
- `)}catch{}}function V$(e,t){if(!_k(t))return null;let n=fk(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}"`)},I$());return o.unref?.(),o}function Y$(e,t,n,r){if(!_k(r))return;let o=fk(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 Wb(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=ik("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 J$(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function X$(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 Wb(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{Wb(r)},C$()),t.forceKillTimer.unref?.()}}function Q$(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)},R$()),r.unref?.())}),e.on("close",(i,a)=>{o({code:i,signal:a})})})}function Z$(e,t,n,r,o){return ik(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function Vb(e){let t=await Hd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,ws),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>ws}}finally{await t.close()}}async function eF(e,t,n,r,o,i=process.cwd()){let a=Date.now(),s=await ak(le.join(sk(),"pm-linked-test-output-"));try{let c=le.join(s,"stdout.log"),m=le.join(s,"stderr.log"),[p,u]=await Promise.all([Hd(c,"w"),Hd(m,"w")]),f;try{f=Z$(e,n,p.fd,u.fd,i)}catch(J){throw await Promise.all([p.close(),u.close()]),J}let h=Q$(f),_;f.on("error",J=>{_=J.message}),await Promise.all([p.close(),u.close()]),W$(f);let g={heartbeat:V$(r,o),forceKillTimer:null,timedOutTimer:null},y=X$(f,g),w=!1;g.timedOutTimer=setTimeout(()=>{w=!0,y()},t),g.timedOutTimer.unref?.();let{code:b,signal:k}=await h;J$(g);let[I,C]=await Promise.all([Vb(c),Vb(m)]),N=I.truncated||C.truncated,L=N?`
40
- [pm linked-test output truncated at ${ws} bytes per stream; the child process continued to completion]
41
- `:"";!_&&await qb(e,{exitCode:b,stderr:C.text},n,i)&&(_="Linked test executable was not found. Install the tool or update the linked command before retrying.");let D={stdout:`${I.text}${L}`,stderr:C.text,exitCode:b,signal:k,timedOut:w,maxBufferExceeded:!1,outputTruncated:N,spawnError:_};return Y$(r,D,a,o),D}finally{await wo(s,{recursive:!0,force:!0})}}function tF(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${ws} 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 nF(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
42
- `);return S$.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>E$.test(n)&&A$.test(n))}function rF(e){return nF(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function oF(){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 vo(e){let t=oF();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}function Yb(e,t){for(let[n,r]of Object.entries(t.env_set))mn.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)mn.has(n.toUpperCase())||delete e[n]}function iF(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 aF(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 hk(e,t,n){return{env_set:$$(e,"--env-set"),env_clear:F$(t,"--env-clear"),shared_host_safe:n===!0}}async function yo(e,t,n=!1,r=Vd){if(await z(e))try{await yr("seed_linked_test",async()=>{if(await r(le.dirname(t),{recursive:!0}),n){await zb(e,t,{recursive:!0,force:!0});return}await zb(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&&Fe(o))return;throw o}}async function Jb(e,t,n,r=!1){for(let[o,i]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let a=await X(ie(o));if(a!==null){let s=await E(i);await Qe({pmRoot:i,filePath:ie(i),raw:a,op:"settings:write",author:T(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 yo(ie(o),ie(i));await yo(le.join(n.projectPmRoot,"extensions"),le.join(e,"extensions"),!0),await yo(le.join(n.globalPmRoot,"extensions"),le.join(t,"extensions"),!0)}async function Xb(e,t){if(!await z(e))return;let n=await Bd(e,{withFileTypes:!0});for(let r of n){if(b$.has(r.name))continue;let o=le.join(e,r.name),i=le.join(t,r.name);if(r.isDirectory()){await yo(o,i,!0);continue}r.isFile()&&await yo(o,i)}}async function Qb(e,t){let n=await X(ie(e));if(n===null||await z($c(e)))return;let r=await E(t);await wo($c(t),{force:!0}),await wo(ie(t),{force:!0}),await Qe({pmRoot:t,filePath:ie(t),raw:n,op:"settings:write",author:T(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 dr(e){if(!await z(e))return 0;let t=0,n=await Bd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||k$.has(r.name))continue;let o=le.join(e,r.name),i;try{i=await Bd(o,{withFileTypes:!0})}catch{continue}for(let a of i)a.isFile()&&Fm.some(s=>a.name.toLowerCase().endsWith(s))&&(t+=1)}return t}function sF(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function cF(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 lF(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?ae(e,t):Object.is(e,t)}function dF(e,t,n){let r=[];r.push(...Zb("stdout",t,e.assert_stdout_contains)),r.push(...ek("stdout",t,e.assert_stdout_regex)),r.push(...Zb("stderr",n,e.assert_stderr_contains)),r.push(...ek("stderr",n,e.assert_stderr_regex)),r.push(...mF(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=Gd(a,s);if(!m.found){r.push(`assert_json_field_equals missing path "${s}"`);continue}let p=cF(c);lF(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=Gd(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 Zb(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function ek(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 mF(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 tk(e){let t=ia(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:oa(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&uk(n))}function pF(e){return{root:e,schemaProjectPmPath:le.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:le.join(e,"schema","global"),trackerProjectPmPath:le.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:le.join(e,"tracker","global"),workspaceSnapshotRoot:le.join(e,"workspace","project"),workspaceIsolatedRoot:le.join(e,"workspace","isolated")}}function uF(e,t,n){return e.some(r=>lk(r,t,n)==="snapshot")}async function fF(e,t){let n=le.join(e,".agents"),r=le.join(n,"pm");await Vd(n,{recursive:!0}),await wo(r,{recursive:!0,force:!0}),await g$(t,r,process.platform==="win32"?"junction":"dir")}async function _F(e,t=io,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 hF(e,t,n){t&&(await Jb(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await Jb(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Xb(t.projectPmRoot,e.trackerProjectPmPath),await Xb(t.globalPmRoot,e.trackerGlobalPmPath),await Qb(t.projectPmRoot,e.trackerProjectPmPath),await Qb(t.globalPmRoot,e.trackerGlobalPmPath)))}function gF(e,t,n){return e.some(r=>{let o=r.command??"",i=o.length>0&&pk(o),a=n?.autoPmContext===!0&&i?"auto":dk(r,t,n?.overrideLinkedPmContext===!0);return mk(a,i)==="tracker"})}async function yF(e,t){return{sourceProjectItemCount:t?await dr(t.projectPmRoot):0,sourceGlobalItemCount:t?await dr(t.globalPmRoot):0,schemaProjectItemCount:await dr(e.schemaProjectPmPath),schemaGlobalItemCount:await dr(e.schemaGlobalPmPath),trackerProjectItemCount:await dr(e.trackerProjectPmPath),trackerGlobalItemCount:await dr(e.trackerGlobalPmPath)}}function wF(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 vF(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?bs(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?M$(n):!1,o=r&&n?pk(n):!1,i=e.options?.autoPmContext===!0&&o,a=i?"auto":dk(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),s=mk(a,o),c=s==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await fF(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await Qc(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Qc(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:wF({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 nk(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function bF(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 kF(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 SF(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 kF(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 EF(e){if(!e.linkedTest.command)return nk(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=G$(e.linkedTest.command);return t?nk(e.linkedTest,e.executionContext,t):null}function AF(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?vs(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?vs(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 vs(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 TF(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=L$({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 vs(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 CF(e){return EF(e)||SF(e)||AF(e)||TF(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!P$(e.linkedTest)?vs(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function IF(e){let t=aF(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return Yb(n,e.runtimeDirectives),Yb(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&iF(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[Kr]):(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[Kr]="read_only"),n}function RF(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 rk(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 OF(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:sF(e.execution),failure_category:rF(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:tF(e.execution,e.timeoutMs)}}function xF(e){let t=Pb(e.execution.stdout,e.execution.stderr);if(e.options?.failOnEmptyTestRun===!0||tk(e.linkedTest.command??"")){let r=us(e.execution.stdout,e.execution.stderr);if(r)return rk({...e,emptyRunSignal:r});if(tk(e.linkedTest.command??"")&&!t)return rk({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let n=dF(e.linkedTest,e.execution.stdout,e.execution.stderr);return n.length>0?bF(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${n.join("; ")}`,e.execution):RF(e.linkedTest,e.executionContext,e.execution,t)}async function NF(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await eF(t,n,IF(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?xF({...e,execution:r}):OF({...e,execution:r,timeoutMs:n})}async function Xd(e,t,n){for(let g of e)Ir(g.command);let r=[],o=await ak(le.join(sk(),"pm-linked-test-")),i=pF(o),a=bs(n?.pmContext),s=ck(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=hk(n?.envSet,n?.envClear,n?.sharedHostSafe),p=n?.sourceRoots,u=xh(),f=gF(e,a,n),h=uF(e,s,n?.overrideLinkedWorkspaceContext===!0),_=await Oh(u);try{await _F(i,io,f),await Vd(i.workspaceIsolatedRoot,{recursive:!0}),await hF(i,p,f),h&&await Ub(u,i.workspaceSnapshotRoot,p?.projectPmRoot,f);let g=await yF(i,p);for(let y=0;y<e.length;y+=1){let w=e[y],b=lk(w,s,n?.overrideLinkedWorkspaceContext===!0),k=await vF({linkedTest:w,layout:i,counts:g,sourceRoots:p,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:s,workspaceContextMode:b,currentSourceRef:_,sourceWorkspaceRoot:u}),I=CF({linkedTest:w,executionContext:k.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:k.linkedOverridePmContextMode,options:n});if(I){r.push(I);continue}r.push(await NF({linkedTest:w,index:y,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:k.executionContext,options:n}))}}finally{await wo(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function PF(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,i=await j(n,t,r.id_prefix,r.item_format,o);if(!i)throw new l(`Item ${t} not found`,d.NOT_FOUND);let a=await ne(i,{schema:r.schema});return{itemId:i.id,tests:a.document.metadata.tests??[],testRuns:a.document.metadata.test_runs??[],changed:!1,removed:0}}function LF(e,t){let n=[...e];for(let r of t)n.some(o=>Ci(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 FF(e,t,n,r){return $F(LF(e,t),n,r)}function MF(e){return[e.timeout!==void 0,e.progress===!0,(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function gk(e){if(MF(e)&&e.run!==!0)throw new l("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, 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 DF(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 PF({id:t,pmRoot:r,settings:o,typeToFolder:i});let m=0,p=await _e({pmRoot:r,settings:o,id:t,op:a.length>0?"tests_add":"tests_remove",author:T(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let f=u.metadata.tests??[],h=FF(f,a,s,c);if(Sc(()=>yk(n,h.tests)),m=h.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(_=>`${_.kind}=${_.value}`),...c.map(_=>`index=${_}`)],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=h.tests,{changedFields:ae(f,h.tests)?[]:["tests"]}}});return{itemId:p.item.id,tests:p.item.tests??[],testRuns:p.item.test_runs??[],changed:p.changedFields.length>0,removed:m}}function yk(e,t){let n=bs(e.pmContext);ck(e.workspaceContext),hk(e.envSet,e.envClear,e.sharedHostSafe);let r={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:tr(e.onlyIndex),onlyLast:e.onlyLast},o=e.timeout===void 0?void 0:ge(e.timeout,"--timeout");if(o!==void 0&&o<=0)throw new l(`--timeout must be a positive number (got "${e.timeout}")`,d.USAGE);gk(e);let i=e.run===!0?cg(t,r):void 0;if(i)for(let a of i.selected)Ir(a.command);return{defaultTimeoutSeconds:o,pmContextMode:n,runSelection:i,testsToRun:i?.selected??t}}async function UF(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Xd(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:ht(process.cwd())}})}function GF(e,t){let n=[];if(e.run===!0&&e.checkContext===!0){let r=Jd(t);n.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}`)}return n}function jF(e){let t=x$(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=S(),i=ho(e.options.measure,o);return{run_id:O$("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 qF(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=jF({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 ps({pmRoot:n,settings:r,itemId:o,author:T(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 ok(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=hb(t,i,s)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:gb(t,e.metricDiff)}}async function KF(e,t,n){if(e.acknowledgeLinkedTests===!0)return Nh(t,n,S())}function zF(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:i,warnings:a,recording:s,measurementProjection:c,restoreScope:m}=e,p=o!==void 0&&o.selector!==null&&o.skipped_count>0,u=$b(t.itemId,m);return{ok:n.every(f=>f.status!=="failed"&&f.status!=="refused")&&i!==!0,id:t.itemId,tests:p?o.selected:t.tests,...p?{tests_omitted:{count:t.tests.length-o.selected.length,restore_with:u}}:{},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 ks(e,t,n){let r=mg(t);if(r)return pg(t),gk(t),zd(e,t,n,A(process.cwd(),n.path)),{...await fg(e,{...r,author:t.author,message:t.message,force:t.force},n),run_results:[],failure_categories:vo([])};let o=Ut(),i=A(process.cwd(),n.path);await O(i);let a=await E(i);zd(e,t,n,i),ho(t.measure,"validation"),ok(t,[],void 0);let s=P(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=[...j$(c),...z$(m)],f=await Yn(u,T(t.author,a.author_default),S())??[],h=H$(p),_=B$(t.removeIndex),g=await DF({id:e,options:t,pmRoot:i,settings:a,typeToFolder:s.type_to_folder,adds:f,removes:h,removeIndexes:_}),y=Sc(()=>yk(t,g.tests)),w=await KF(t,i,g.tests),b=t.run===!0?S():void 0,k=await UF({options:t,runOptions:y,pmRoot:i,untrustedLinkedTestsPolicyEnabled:a.testing.allow_untrusted_linked_tests});Kb(e,t,n,i,k);let I=vo(k),C=t.run===!0&&t.failOnSkipped===!0&&k.some(H=>H.status==="skipped"),N=GF(t,k);w&&N.push(`linked_test_trust_acknowledged:${w.acknowledged}`);let L=await qF({options:t,pmRoot:i,settings:a,itemId:g.itemId,runStartedAt:b,runResults:k,failOnSkippedTriggered:C,warnings:N}),D=L?.receipt.recorded?Ud([...g.testRuns,L.entry]):g.testRuns,J=ok(t,D,L?.entry);return zF({item:g,runResults:k,failureCategories:I,runSelection:y.runSelection,failOnSkippedTriggered:C,warnings:N,recording:L,measurementProjection:J,restoreScope:Lb(n,i)})}(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]="190a58ff-ffae-52cf-927f-286e10771bbc")}catch{}})();var HF=(e,t)=>{if(e===void 0)return;let n=se(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},BF=e=>{if(e===void 0)return;let t=ge(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},wk=(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},WF=e=>e instanceof Error?e.message:String(e),VF=()=>{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)}`},YF=e=>e.trim().replaceAll(/\s+/g," "),JF=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),XF=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),QF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},ZF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Ss=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),vk=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),eM=e=>typeof e=="number"?e:void 0,tM=e=>{let t={assert_stdout_contains:Ss(e.assert_stdout_contains),assert_stdout_regex:Ss(e.assert_stdout_regex),assert_stderr_contains:Ss(e.assert_stderr_contains),assert_stderr_regex:Ss(e.assert_stderr_regex),assert_stdout_min_lines:eM(e.assert_stdout_min_lines),assert_json_field_equals:vk(e.assert_json_field_equals),assert_json_field_gte:vk(e.assert_json_field_gte)};return JSON.stringify(t)},nM=e=>{let t=Qd(e.command);return t!==void 0?`command:${e.scope}:${YF(t)}`:`path:${e.scope}:${Qd(e.path)??""}`},bk=e=>{let t=JF(e.env_set),n=XF(e.env_clear),r=QF(e.pm_context_mode),o=ZF(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",a=tM(e);return`${nM(e)}:${t}:${n}:${r}:${o}:${i}:${a}`},rM=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,oM=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}},iM=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Es=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
43
- `)}catch{}},aM=async(e,t,n)=>{let r=[],o=0;for(let i of e){let a=await ks(i.id,{run:!1},{...t,path:n});o+=a.tests.length,r.push({item:i,tests:a.tests})}return{itemTests:r,linkedTests:o}},sM=async e=>{let t=F(e.settings.schema),n=P(e.settings,R()),r=HF(e.options.status,t),o=wk(e.options.limit,"--limit"),i=wk(e.options.offset,"--offset")??0,a=(await ye(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}},cM=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=bk(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,rM(t.get(o),r.timeout_seconds))}return t};function lM(e,t){try{Ir(e.command);return}catch(n){if(!(n instanceof l)||n.code!=="linked_test_command_not_executable")throw n;return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Linked test refused for ${t}: ${n.message}`}}}var dM=async(e,t)=>{let n=[],r=e.tests.map(p=>{let u=bk(p),f=lM(p,e.item.id);if(f)return{test:p,key:u,duplicate:!1,refusal:f};let h=t.seenTestKeys.has(u);if(!h){t.seenTestKeys.add(u);let _=t.effectiveTimeoutByKey.get(u);n.push(_===void 0?p:{...p,timeout_seconds:_})}return{test:p,key:u,duplicate:h,refusal:f}}),o=n.length>0?await Xd(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,refusal:h})=>{if(h)return h;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=oM(a),c=vo(a),m=await uM(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}}},mM=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),pM=e=>e?!0:void 0,uM=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=mM(t,r.options);await ps({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:S(),recorded_at:S(),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:pM(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}:${WF(o)}`]}return[]},fM=()=>{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},Qd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},_M=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:ht(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:cM(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:T(e.options.author,e.settings.author_default),trackingRunId:VF(),trackingAttempt:fM(),trackingResumedFrom:Qd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),hM=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:vo([]),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}},gM=async(e,t,n)=>{for(let[r,o]of e.entries()){Es(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let i=await dM(o,t);iM(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),Es(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}`)}},yM=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=Jd(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}`)},wM=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}),vM=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(" "),bM=async(e,t)=>{let n=A(process.cwd(),t.path);await O(n);let r=await E(n),o=await sM({pmRoot:n,settings:r,options:e}),i=BF(e.timeout),a=S(),s=await aM(o.filteredItems,t,n);return Es(e,vM({...o,linkedTests:s.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:s.itemTests,linkedTests:s.linkedTests,defaultTimeoutSeconds:i,runStartedAt:a}},kM=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}},kk=async(e,t)=>{let n=await bM(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=hM(e,n.linkedTests,n.filteredItems),i=_M({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await gM(n.itemTests,i,r),yM(e,r);let a=kM({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Es(e,`end status=${a.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),wM({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 Sk(e,t,n){let r;if(typeof e.lines=="string")r=Vc(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=Vc(`${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 Sn(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 SM(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:be(n)}}function EM(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=Sn({list:()=>D_(t.global),show:()=>U_(r,t.global),"show-status":()=>G_(r,t.global),"list-fields":()=>K_(t.global),"show-field":()=>z_(r,t.global),"remove-type":()=>L_(r,{author:o,force:i},t.global),"remove-field":()=>q_(r,{author:o,force:i},t.global),"remove-status":()=>M_(r,{author:o,force:i},t.global),"apply-preset":()=>H_(v(t.args,"typePreset")??v(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function AM(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 j_(n,{type:v(t.args,"fieldType")??v(t.options,"fieldType"),commands:a===void 0?void 0:be(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:be(s),author:r,force:o},t.global)}function TM(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,a=t.args.role??t.options.role;return F_(n,{role:a===void 0?void 0:be(a),alias:i,description:v(t.args,"description")??v(t.options,"description"),order:Ge(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function CM(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return P_(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 IM(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 x_(m,{migrationId:s,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function Ek(e){let t=SM(e);uf(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Cn.find(o=>o===t.subcommand);if(n)return O_(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=EM(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return IM(t);if(t.subcommand==="add-field")return AM(t);if(t.subcommand==="add-status")return TM(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?B_({minCount:Ge(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):CM(t);throw Re({command_path:"schema",token:t.subcommand,allowed:N_,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]="23d06544-9101-582d-92d4-bed8092d3cdb")}catch{}})();function As(e){return v(e.args,"target")??v(e.options,"target")}function Ee(e,t=e.options){return e.id??Le(t,"id")}async function RM(e){let t=Ln("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),fl(await At(v(e.args,"status")??v(t,"status"),t,e.global),t)}async function OM(e){let t=v(e.args,"query")??v(e.args,"keywords")??Le(e.args,"query"),n=Ln("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),fl(await Vr(t,n,e.global),n)}async function xM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options);return Ce(await Wt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function NM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(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 Ce(await Cl(Ee(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function PM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options);return Ce(await ot(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function LM(e){let t=ua(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")),Yg(Ee(e),t,e.global)}function Ak(e,t){return eh(Sk(e.options,t,Ge),e.global)}function $M(e){let t=be(e.options.lookupPath);if(t&&t.length>0)return Ak(e,t);let n=Ee(e);return e.options.discover===!0?Yc(n,Bi(e.options),e.global):Z_(n,Dr(e.options),e.global)}function FM(e){return Ob({subcommand:v(e.args,"subcommand")??v(e.options,"subcommand"),limit:a_(e.args,e.options)},e.global)}function MM(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),zr(e.global,t)}function DM(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 yy(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 UM(e){let t=e.options;return zh(Kh(t),e.global)}function GM(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 jM(e){let t=v(e.args,"subcommand")??Le(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=we(e.args,e.options),i=await Yw({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:qM(e),reorderTo:GM(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&r_(e.args)&&(i.mutation_receipt=ts(i,void 0)),t==="show"?i:Ce(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function qM(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function KM(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=Sn({list:()=>pv(),show:()=>uv(r),lint:()=>fv(r),apply:()=>_v(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:mv,exit_code:64});return o()}async function zM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options);return Ce(await xy(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function HM(e){let{changedFields:t,runnerOptions:n}=we(e.args,e.options);return Ce(await nv(Yi(n),e.global),{changedFields:t})}async function BM(e){let{changedFields:t,runnerOptions:n}=we(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),Ce(await Uy(Vi(o),e.global),{changedFields:t})}async function WM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options),o=v(r,"target")??Le(e.args,"target");return Ce(await hd(Ee(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function VM(e){let t={...e.args,...e.options};return th(Le(t,"subcommand"),v(t,"id")??e.id,v(t,"target"),m_(t),e.global)}function YM(e){return J_(A(process.cwd(),e.global.path),{...e.args,...e.options})}var Tk={init:e=>io(v(e.args,"prefix"),e.global,e.options),context:e=>el(Ln("context",e.options),e.global),next:e=>Wr(Ln("next",e.options),e.global),eval:Xv,events:Qv,merge:Zv,workspace:eb,meet:cs,event:cs,remind:cs,list:RM,get:e=>{let t=Ee(e);return nl(t,e.global,Ln("get",e.options,[t]))},search:OM,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:be(e.options.status);return Wc(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:Ge(e.options.limit,"limit")})},create:xM,copy:NM,focus:e=>jl(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:PM,"item-reopen":Mw,restore:WM,claim:Lw,release:Fw,"start-task":e=>yn(e,"start_task"),"pause-task":e=>yn(e,"pause_task"),"close-task":e=>yn(e,"close_task"),close:$w,comments:LM,notes:e=>rv(Ee(e),ua(e.options),e.global),learnings:e=>Oy(Ee(e),ua(e.options),e.global),files:$M,docs:e=>Q_(Ee(e),Dr(e.options),e.global),test:e=>ks(Ee(e),e.options,e.global),"test-all":e=>kk(e.options,e.global),telemetry:FM,validate:e=>aa(e.options,e.global,{runUpdate:(t,n,r)=>ot(t,n,r)}),health:MM,assurance:e=>Ph(e.args,e.options,e.global),contracts:e=>dl(e.options,e.global),config:DM,activity:UM,aggregate:e=>tl(e.options,e.global),extension:e=>Bn(As(e),e.options,e.global),package:e=>Bn(As(e),e.options,e.global),install:e=>Bn(As(e),{...e.options,install:!0},e.global),upgrade:e=>$h(As(e),e.options,e.global),delete:e=>Gl(Ee(e),e.options,e.global),deps:e=>X_(Ee(e),e.options,e.global),graph:VM,"files-discover":e=>Yc(Ee(e),e.options,e.global),"files-lookup":e=>Ak(e,be(e.options.paths)),history:e=>Hh(Ee(e),{...e.options,compact:e.options.full===!0||e.options.provenance===!0?!1:e.options.compact!==!1},e.global),"history-redact":e=>Ry(Ee(e),e.options,e.global),"history-repair":Ey,"history-compact":Ay,"history-attest":e=>Fh(e.options,e.global),"history-author-acknowledge":YM,plan:jM,schema:Ek,profile:KM,stats:e=>$d(e.global,tb(e.options)),append:zM,"update-many":HM,"close-many":BM,gc:e=>Lh(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 JM=new Map;function Zd(){JM.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]="5917df84-25e1-5ce2-9203-746f92bb4037")}catch{}})();var Ik=[{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:ef().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>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --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> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --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"]}],Ck=new Map;for(let e of Ik){Ck.set(e.id,e);for(let t of e.aliases)Ck.set(t,e)}function em(){return Ik.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 J8=[...Ds],X8=[...Us],tm=new Set(tn.filter(e=>e.hidden).map(e=>e.alias)),Rk=Zu("full").filter(e=>!e.includes(" ")&&!tm.has(e)),XM=$(Lo),QM=$($o),ZM=$(qo),eD=$(Wo),Ok=Tr("restore",Me("restore")),xk=Tr("history-attest",Me("history-attest")),tD=$(Vo),nD=$(Yp),rD=$(Jp),oD=$(Bo),iD=$(Qo),aD=$(Yo),sD=$(Jo),cD=$(jo),nm=[...new Set(Te.map(e=>e.canonical_argv[0]))],Nk=[...new Set(Te.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],Q8=new Set(Po.filter(e=>e.disposition==="package_owned").map(e=>B(e.command))),Pk=Te.filter(e=>e.canonical_argv[0]==="history"),lD=Pk.map(e=>e.canonical_argv[1]).join(" ");var dD=Pk.map(e=>({...e,flags:$(Me(e.alias))})),mD=$(Fo),pD=$(Mo,!1),uD=$(Xo),fD=$(Sr),_D=$(Er),hD=$(ni),gD=$(ei),yD=$(zo),wD=$(ti),vD=$(Zo),bD=$(ri),kD=$(Ko),SD=$(Ho),ED=$(Uo),AD=$(oi),TD=$(Do),rm=`${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 CD=$(ii),ID=`${CD} bash zsh fish`,om=Cs(em()),Ts="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",im=`${Ts} upgrade`,RD=$(Go),OD=$(br),xD=$(kr);var ND=$(Me("close")),PD=$(Me("close-task")),LD=$(Me("release")),$D=$(Me("claim"));var Lk=In.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),am=[...ui].join("|"),sm=[...ui].map(e=>`${e}=*`).join("|"),cm=[...Lk.split(" ").filter(e=>!ui.has(e)),"-h","-V"].join("|");function Cs(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]="8f625fcd-badb-5483-82b8-ce4a247d2186")}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]="81d4e33a-0a99-55ee-9d41-84e6e711eb80")}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]="7a7096c6-a9c3-5d8e-96e4-ed1b0218234e")}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]="28342969-40ca-52d3-aaa3-498442120ff4")}catch{}})();var dm=Symbol("pm.active-extension-host-context");function ze(e){return{fullChangedFields:!0,options:e}}var K=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[dm]=!0,n}run(t,n={}){return YD({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}async withItemTransactionContext(t,n=!1){let r=A(this.defaults.cwd??process.cwd(),this.defaults.path),o=async()=>{let a=await Fr(r,()=>E(r));return t({pmRoot:r,author:T(this.defaults.author,a.author_default)})};if(this.defaults[dm]===!0||Rs.getStore()===!0)return o();let i=()=>zD({...this.defaults,path:r},o);return n?Fr(r,i):i()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-PZ2FQ6B2.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-PZ2FQ6B2.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,r)=>this.withItemTransactionContext(async o=>(await import("./item-transaction-PZ2FQ6B2.js")).abandonItemTransaction({...r,...o,transactionId:n}));return{status:n=>this.withItemTransactionContext(async r=>(await import("./item-transaction-PZ2FQ6B2.js")).readItemTransaction(r.pmRoot,n),!0),abandon:t,supersede:(n,r,o)=>t(n,{...o,supersededBy:r})}}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Hg(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Bc(await this.list(Hc(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})}async append(t,n,r={}){return df(r,"append"),await this.runTyped("append",{id:t,...ze(pt(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:pt(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",ze(t))}update(t,n={}){return this.runTyped("update",{id:t,...ze(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,...ze(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...ze(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...ze(t)})}release(t,n={}){return this.runTyped("release",{id:t,...ze(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...ze(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...ze(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},...ze(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...ze(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...ze(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...ze(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 Q7(e={},t={}){return new K(t).context(e)}function Z7(e={},t={}){return new K(t).list(e)}function eJ(e={},t={}){return new K(t).listAllComplete(e)}function tJ(e,t={},n={}){return new K(n).search(e,t)}function nJ(e,t={},n={}){return new K(n).get(e,t)}function rJ(e={},t={}){return new K(t).next(e)}function oJ(e={},t={}){return new K(t).aggregate(e)}function iJ(e,t={},n={}){return new K(n).comments(e,t)}function aJ(e,t={},n={}){return new K(n).notes(e,t)}function sJ(e,t={},n={}){return new K(n).learnings(e,t)}function cJ(e,t={},n={}){return new K(n).files(e,t)}function lJ(e,t={},n={}){return new K(n).filesDiscover(e,t)}function dJ(e,t={},n={}){return new K(n).docs(e,t)}function mJ(e,t={},n={}){return new K(n).deps(e,t)}function pJ(e,t={},n={},r={}){return new K(r).graph(e,t,n)}function uJ(e,t,n={},r={}){return new K(r).append(e,t,n)}function fJ(e={},t={}){return new K(t).create(e)}function _J(e,t={},n={}){return new K(n).update(e,t)}function hJ(e,t,n={},r={}){return new K(r).reopen(e,t,n)}function gJ(e,t,n={},r={}){return new K(r).close(e,t,n)}function yJ(e,t={},n={}){return new K(n).claim(e,t)}function wJ(e={},t={}){return new K(t).claimNext(e)}function vJ(e,t={},n={}){return new K(n).release(e,t)}function bJ(e,t={},n={}){return new K(n).copy(e,t)}function kJ(e,t={},n={}){return new K(n).delete(e,t)}function SJ(e,t,n={},r={}){return new K(r).restore(e,t,n)}function EJ(e,t={},n={}){return new K(n).focus(e,t)}var Dk=Tu(),Rs=new KD;function Is(){dc(Wm()),mc(Vm()),pc(Ym()),uc(Jm()),fc(Xm()),_c(Qm()),hc(Zm())}async function Gk(e,t,n,r){return lc(()=>t===void 0?Dk.read(()=>Uk(e,n,r)):Dk.write(()=>WD(t,()=>Uk(e,n,r))))}async function zD(e,t){let n=e.cwd;if(Rs.getStore()===!0&&n===void 0&&e.noExtensions===!0){let o=A(process.cwd(),e.path);return lc(()=>ma({pmRoot:o},t))}let r=n??process.cwd();return Gk(Hi({path:e.path,noExtensions:e.noExtensions}),n,r,()=>Rs.run(!0,t))}function HD(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:rf(e);return typeof n=="string"?n:"Unknown failure"}catch{return"Unknown failure"}}async function Uk(e,t,n){let r=A(t,e.path);if(e.noExtensions)return Is(),ma({pmRoot:r},()=>n(null));if(!await z(ie(r)))return Is(),n(null);let o=null,i;try{let a=await E(r),s=await wr({pmRoot:r,settings:a,cwd:t,noExtensions:!1}),c=await vr({...s,loaded:s.loaded});i={loadResult:s,activationResult:c},dc(c.hooks),mc(c.commands),pc(c.parsers),uc(c.preflight),fc(c.services),_c(c.renderers),hc(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:",HD(a))}try{return await ma({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Is(),i&&await tc(i.loadResult,i.activationResult).catch(()=>{})}}function jk(e,t){let n=Hn(e);return t?.registrations.commands.find(r=>Hn(r.action)===n)?.command??t?.commands.handlers.find(r=>Hn(r.command)===n)?.command}async function BD(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let i=jk(e,o);if(!i)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let a=typeof n.author=="string"?n.author:r.author,s=await pi({command:Wi(i),args:be(n.args??t.args),options:Kc(t,n),global:{...r,author:a},pm_root:o.pmRoot,sdk:Gg(o.pmRoot,K.forActiveExtensionHost({pmRoot:o.pmRoot,author:a}),a,Wi(i))});if(!s.handled){if(Object.hasOwn(s,"cause"))throw yi(i,s);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 WD(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function VD(e){let t=Le(e,"action"),n=Hn(t),r=Sn(Wg,n),o=r?.action??n,i={...e,action:o};return r?.options!==void 0&&(i.options={...r.options,...Js(e.options)}),o==="package"&&(i.options={...Js(i.options),vocabulary:"package"}),{action:o,args:i}}async function YD(e){let t=VD(e),n=Hi(t.args);Iu(n);let r=l_(t.action),o=v(t.args,"cwd"),i=o??process.cwd();t.action==="init"&&(n[ul]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=A(i,n.path));try{return t.action==="history-attest"?await lm(t.action,t.args,n,null):e[dm]===!0||Rs.getStore()===!0?await lm(t.action,t.args,n,null):await Gk(n,o,i,a=>lm(t.action,t.args,n,a))}finally{r&&Zd()}}async function lm(e,t,n,r){let o=qc(t,e);if(e==="create"||e==="update"){let{assertNativeMutationOptions:p}=await import("./mutation-admission-XOOK6XFH.js");await p(e,t,o,n.path,s_[e])}let i=Sn(Tk,e),a=i?void 0:jk(e,r),s=a===void 0?e:`extension:${a}`;Pu(s,o),$u(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 BD(e,t,o,n,r);if(e==="history-attest")return m;{let p=Gu(s,o,m);return await Ug(A(process.cwd(),n.path),p),p}}var JD={closeManyOptionsFromFlat:Vi,extensionOptionsFromArgs:Kc,globalOptions:Hi,mutationListOptions:d_,normalizeActionName:Hn,normalizeCommandPath:Wi,normalizeMcpUpdateOptions:p_,normalizeMcpOptionsArrays:c_,optionsWithAuthor:qc,readRequiredString:Le,readScalarString:o_,readScalarStringAllowBlank:i_,readStringArray:be,updateManyOptionsFromFlat:Yi,withAddNoteOption:Dr,withFilesDiscoveryOptions:Bi,withMutationCompaction:we};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=JD);export{rl as a,DS as b,zS as c,og as d,BU as e,ig as f,WU as g,VU as h,fg as i,fE as j,K as k,Q7 as l,Z7 as m,eJ as n,tJ as o,nJ as p,rJ as q,oJ as r,iJ as s,aJ as t,sJ as u,cJ as v,lJ as w,dJ as x,mJ as y,pJ as z,uJ as A,fJ as B,_J as C,hJ as D,gJ as E,yJ as F,wJ as G,vJ as H,bJ as I,kJ as J,SJ as K,EJ as L,zD as M,YD as N};
44
- //# sourceMappingURL=chunk-MOY6KZGJ.js.map