@unbrained/pm-cli 2026.8.7 → 2026.8.9

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 (288) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +54 -0
  3. package/dist/cli/main.js +4 -3
  4. package/dist/cli/register-annotations.d.ts +11 -0
  5. package/dist/cli/register-annotations.js +195 -0
  6. package/dist/cli/register-history-author.js +7 -30
  7. package/dist/cli/register-mutation.js +25 -206
  8. package/dist/cli/runtime-compatibility-boundary.d.ts +17 -0
  9. package/dist/cli/runtime-compatibility-boundary.js +43 -0
  10. package/dist/cli-bundle/bundle-manifest.json +158 -694
  11. package/dist/cli-bundle/chunks/chunk-2DTCZXSD.js +13 -0
  12. package/dist/cli-bundle/chunks/chunk-5JO6R4BS.js +3 -0
  13. package/dist/cli-bundle/chunks/chunk-5KN4DZYV.js +194 -0
  14. package/dist/cli-bundle/chunks/chunk-EF43KODO.js +2 -0
  15. package/dist/cli-bundle/chunks/chunk-GMX5YOI3.js +77 -0
  16. package/dist/cli-bundle/chunks/chunk-HUV2Z7IS.js +28 -0
  17. package/dist/cli-bundle/chunks/chunk-MHBVCUF2.js +2 -0
  18. package/dist/cli-bundle/chunks/chunk-PYO5GZU6.js +5 -0
  19. package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +2 -0
  20. package/dist/cli-bundle/chunks/chunk-RJC7TPF4.js +8 -0
  21. package/dist/cli-bundle/chunks/chunk-YC3UF2IO.js +2068 -0
  22. package/dist/cli-bundle/chunks/{register-list-query-FJZCJ67O.js → register-list-query-BUE7PTCU.js} +8 -8
  23. package/dist/cli-bundle/chunks/register-mutation-FC3XLVIK.js +20 -0
  24. package/dist/cli-bundle/chunks/register-operations-YH2WAOXU.js +2 -0
  25. package/dist/cli-bundle/chunks/register-setup-UQDTNTLJ.js +2 -0
  26. package/dist/cli-bundle/focused-chunks/chunk-2VVP5RAA.js +153 -0
  27. package/dist/cli-bundle/focused-chunks/{chunk-4VJQTS3P.js → chunk-3GSFUDAI.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/chunk-3WVHTUAW.js +5 -0
  29. package/dist/cli-bundle/focused-chunks/chunk-4H6MVCK3.js +16 -0
  30. package/dist/cli-bundle/focused-chunks/{chunk-73JUDYXT.js → chunk-54TZJ4BM.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/chunk-5NK5TJ5D.js +2 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-HNL6IFGS.js → chunk-6DO4YQWZ.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-73FIJONU.js +2 -0
  34. package/dist/cli-bundle/focused-chunks/{chunk-TIKDBG4D.js → chunk-C3GCHDSQ.js} +29 -27
  35. package/dist/cli-bundle/focused-chunks/chunk-JGRSQZJT.js +18 -0
  36. package/dist/cli-bundle/focused-chunks/{chunk-YZEZAPJK.js → chunk-KNEHLPBF.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/chunk-MRWVJ3ZG.js +2 -0
  38. package/dist/cli-bundle/focused-chunks/chunk-NL57J7BZ.js +4 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-NBJKQP4S.js → chunk-P6BBIQRG.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-QHRTT7WT.js → chunk-PZAGVQNN.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-QDAO3XEK.js +14 -0
  42. package/dist/cli-bundle/focused-chunks/chunk-T4IGQCSY.js +2 -0
  43. package/dist/cli-bundle/focused-chunks/chunk-U46GQJNY.js +2 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-RPNYG5MO.js → chunk-VRXJSGIT.js} +6 -6
  45. package/dist/cli-bundle/focused-chunks/{chunk-R2LEMEV5.js → chunk-XC2ZW3CJ.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/chunk-ZG54B4XG.js +2 -0
  47. package/dist/cli-bundle/main.js +13 -13
  48. package/dist/cli-bundle/sdk-authoring.js +1 -1
  49. package/dist/cli-bundle/sdk-contracts.js +1 -1
  50. package/dist/cli-bundle/sdk-core.js +38 -38
  51. package/dist/cli-bundle/sdk-governance.js +1 -1
  52. package/dist/cli-bundle/sdk-graph.js +1 -1
  53. package/dist/cli-bundle/sdk-merge.js +1 -1
  54. package/dist/cli-bundle/sdk-query.js +1 -1
  55. package/dist/cli-bundle/sdk-runtime.js +1 -1
  56. package/dist/cli-bundle/sdk-testing.js +1 -1
  57. package/dist/cli-bundle/sdk.js +2 -1
  58. package/dist/cli.js +14 -4
  59. package/dist/core/diagnostics/remediation.js +12 -2
  60. package/dist/core/history/history.js +13 -4
  61. package/dist/core/item/actionability.d.ts +7 -1
  62. package/dist/core/item/actionability.js +71 -15
  63. package/dist/core/output/output.js +9 -2
  64. package/dist/core/sentry/helpers.d.ts +10 -0
  65. package/dist/core/sentry/helpers.js +59 -4
  66. package/dist/core/shared/author.d.ts +25 -0
  67. package/dist/core/shared/author.js +114 -9
  68. package/dist/core/shared/constants.d.ts +2 -0
  69. package/dist/core/shared/constants.js +4 -2
  70. package/dist/sdk/actionability.d.ts +1 -1
  71. package/dist/sdk/actionability.js +3 -3
  72. package/dist/sdk/annotations.d.ts +40 -0
  73. package/dist/sdk/annotations.js +61 -9
  74. package/dist/sdk/author-attribution.d.ts +12 -0
  75. package/dist/sdk/author-attribution.js +73 -11
  76. package/dist/sdk/cli-contracts/command-exit-contracts.d.ts +118 -0
  77. package/dist/sdk/cli-contracts/command-exit-contracts.js +152 -0
  78. package/dist/sdk/cli-contracts/completeness.js +5 -3
  79. package/dist/sdk/cli-contracts/flag-contracts.js +5 -2
  80. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +19 -0
  81. package/dist/sdk/cli-contracts/runtime-contracts.js +44 -2
  82. package/dist/sdk/cli-contracts/tool-parameter-tables.js +15 -2
  83. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  84. package/dist/sdk/cli-contracts/tool-schema.js +6 -3
  85. package/dist/sdk/comments.d.ts +7 -0
  86. package/dist/sdk/comments.js +2 -2
  87. package/dist/sdk/completion.js +9 -5
  88. package/dist/sdk/contracts.d.ts +1 -0
  89. package/dist/sdk/contracts.js +3 -2
  90. package/dist/sdk/core-governance.d.ts +1 -1
  91. package/dist/sdk/core-governance.js +3 -3
  92. package/dist/sdk/dependencies.d.ts +2 -0
  93. package/dist/sdk/dependencies.js +7 -6
  94. package/dist/sdk/environment/host-environment-errors.d.ts +27 -0
  95. package/dist/sdk/environment/host-environment-errors.js +124 -0
  96. package/dist/sdk/environment/project-runtime-compatibility.d.ts +65 -0
  97. package/dist/sdk/environment/project-runtime-compatibility.js +385 -0
  98. package/dist/sdk/environment/source-context.d.ts +23 -0
  99. package/dist/sdk/environment/source-context.js +29 -0
  100. package/dist/sdk/error-code-catalog.d.ts +6 -0
  101. package/dist/sdk/error-code-catalog.js +62 -8
  102. package/dist/sdk/extension/bundled-catalog.js +19 -6
  103. package/dist/sdk/generated-error-code-catalog.js +665 -3
  104. package/dist/sdk/governance/health.d.ts +11 -3
  105. package/dist/sdk/governance/health.js +32 -13
  106. package/dist/sdk/governance/provenance-health.d.ts +26 -0
  107. package/dist/sdk/governance/provenance-health.js +139 -0
  108. package/dist/sdk/governance/validate.js +13 -8
  109. package/dist/sdk/governance.d.ts +1 -0
  110. package/dist/sdk/governance.js +3 -2
  111. package/dist/sdk/graph/assembly.d.ts +4 -0
  112. package/dist/sdk/graph/assembly.js +22 -2
  113. package/dist/sdk/graph/run.d.ts +2 -0
  114. package/dist/sdk/graph/run.js +3 -2
  115. package/dist/sdk/index.d.ts +7 -3
  116. package/dist/sdk/index.js +9 -5
  117. package/dist/sdk/learnings.d.ts +15 -0
  118. package/dist/sdk/learnings.js +2 -2
  119. package/dist/sdk/lifecycle/close-many.d.ts +6 -1
  120. package/dist/sdk/lifecycle/close-many.js +43 -5
  121. package/dist/sdk/lifecycle/close.js +13 -8
  122. package/dist/sdk/lifecycle/create.js +6 -12
  123. package/dist/sdk/lifecycle/plan.js +6 -3
  124. package/dist/sdk/lifecycle/update-many.d.ts +2 -1
  125. package/dist/sdk/lifecycle/update-many.js +29 -5
  126. package/dist/sdk/lifecycle/update.js +6 -20
  127. package/dist/sdk/merge/driver.d.ts +2 -1
  128. package/dist/sdk/merge/driver.js +7 -4
  129. package/dist/sdk/merge/index.d.ts +1 -1
  130. package/dist/sdk/merge/index.js +3 -3
  131. package/dist/sdk/merge/install.d.ts +21 -0
  132. package/dist/sdk/merge/install.js +51 -21
  133. package/dist/sdk/merge/receipts.d.ts +14 -1
  134. package/dist/sdk/merge/receipts.js +36 -8
  135. package/dist/sdk/merge/reconcile.js +21 -4
  136. package/dist/sdk/merge/three-way.d.ts +6 -2
  137. package/dist/sdk/merge/three-way.js +24 -10
  138. package/dist/sdk/notes.d.ts +7 -0
  139. package/dist/sdk/notes.js +2 -2
  140. package/dist/sdk/query/get.d.ts +11 -0
  141. package/dist/sdk/query/get.js +37 -3
  142. package/dist/sdk/read-output-contracts.d.ts +1 -1
  143. package/dist/sdk/read-output-contracts.js +103 -5
  144. package/dist/sdk/relationship-kinds/contract.d.ts +48 -0
  145. package/dist/sdk/relationship-kinds/contract.js +22 -0
  146. package/dist/sdk/relationships.d.ts +6 -41
  147. package/dist/sdk/relationships.js +12 -126
  148. package/dist/sdk/runtime-primitives.d.ts +1 -1
  149. package/dist/sdk/runtime-primitives.js +3 -3
  150. package/dist/sdk/runtime.d.ts +1 -1
  151. package/dist/sdk/runtime.js +9 -25
  152. package/dist/sdk/similarity.d.ts +5 -0
  153. package/dist/sdk/similarity.js +40 -10
  154. package/dist/sdk/structured-mutations.js +5 -2
  155. package/dist/sdk/test/execution.js +4 -2
  156. package/dist/sdk/test/linked-command-detection.d.ts +2 -7
  157. package/dist/sdk/test/linked-command-detection.js +22 -9
  158. package/dist/sdk/test/parsers.js +5 -2
  159. package/dist/sdk/workspace-snapshot.d.ts +9 -0
  160. package/dist/sdk/workspace-snapshot.js +48 -16
  161. package/docs/AGENT_GUIDE.md +2 -1
  162. package/docs/AGENT_RUNTIME_PRIMITIVES.md +11 -4
  163. package/docs/COMMANDS.md +19 -1
  164. package/docs/DEPENDENCY_KIND_CONTRACT.md +29 -0
  165. package/docs/ITEM_READ_PROJECTIONS.md +26 -0
  166. package/docs/MERGE_SAFETY.md +10 -3
  167. package/docs/README.md +1 -0
  168. package/docs/RELATIONSHIP_GRAPH.md +1 -1
  169. package/docs/RELEASING.md +27 -2
  170. package/docs/SCRIPTING.md +27 -1
  171. package/docs/SDK_AGENT_SESSION_CONTEXT.md +35 -2
  172. package/docs/SDK_CONTEXT_INTEGRITY.md +81 -0
  173. package/docs/SDK_RUNTIME_BOUNDARIES.md +58 -0
  174. package/docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md +13 -0
  175. package/docs/SENTRY_CONTRACT_EPOCHS.md +20 -0
  176. package/docs/TESTING.md +17 -0
  177. package/docs/agent-task-token-baseline.json +2 -2
  178. package/marketplace.json +2 -2
  179. package/package.json +5 -3
  180. package/packages/pm-beads/package.json +1 -1
  181. package/packages/pm-calendar/package.json +1 -1
  182. package/packages/pm-command-kit/package.json +1 -1
  183. package/packages/pm-digital-twin/package.json +1 -1
  184. package/packages/pm-governance-audit/package.json +1 -1
  185. package/packages/pm-guide-shell/package.json +1 -1
  186. package/packages/pm-kanban/package.json +1 -1
  187. package/packages/pm-lifecycle-hooks/package.json +1 -1
  188. package/packages/pm-linked-test-adapters/package.json +1 -1
  189. package/packages/pm-search-advanced/package.json +1 -1
  190. package/packages/pm-templates/package.json +1 -1
  191. package/packages/pm-todos/package.json +1 -1
  192. package/packages/pm-vcs/package.json +1 -1
  193. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  194. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  195. package/sdk/public-surface.json +756 -57
  196. package/dist/cli-bundle/chunks/append-7BXBFDGD.js +0 -2
  197. package/dist/cli-bundle/chunks/chunk-2AXF3VSK.js +0 -2
  198. package/dist/cli-bundle/chunks/chunk-2XS43CCV.js +0 -2
  199. package/dist/cli-bundle/chunks/chunk-3A6KWB72.js +0 -8
  200. package/dist/cli-bundle/chunks/chunk-3ISTDB42.js +0 -8
  201. package/dist/cli-bundle/chunks/chunk-4MTI7XOV.js +0 -5
  202. package/dist/cli-bundle/chunks/chunk-6BX5UDCN.js +0 -3
  203. package/dist/cli-bundle/chunks/chunk-6QPO7KLR.js +0 -2
  204. package/dist/cli-bundle/chunks/chunk-7MXHZHSQ.js +0 -5
  205. package/dist/cli-bundle/chunks/chunk-7ZPMJW4U.js +0 -2
  206. package/dist/cli-bundle/chunks/chunk-A6KGKEWT.js +0 -2
  207. package/dist/cli-bundle/chunks/chunk-AGYNSNCI.js +0 -2
  208. package/dist/cli-bundle/chunks/chunk-B4H7FEFH.js +0 -5
  209. package/dist/cli-bundle/chunks/chunk-B4KLBBMN.js +0 -2
  210. package/dist/cli-bundle/chunks/chunk-BXCSXK4J.js +0 -2
  211. package/dist/cli-bundle/chunks/chunk-CALJHNBL.js +0 -23
  212. package/dist/cli-bundle/chunks/chunk-CFIGP5LY.js +0 -2
  213. package/dist/cli-bundle/chunks/chunk-CHOQ2VAW.js +0 -2
  214. package/dist/cli-bundle/chunks/chunk-CS6MRHG7.js +0 -2
  215. package/dist/cli-bundle/chunks/chunk-CUGNQQKH.js +0 -2
  216. package/dist/cli-bundle/chunks/chunk-D4FPS43D.js +0 -164
  217. package/dist/cli-bundle/chunks/chunk-E2ZSLTOP.js +0 -2
  218. package/dist/cli-bundle/chunks/chunk-FB7G2HY2.js +0 -2
  219. package/dist/cli-bundle/chunks/chunk-H5Y5YE6A.js +0 -2
  220. package/dist/cli-bundle/chunks/chunk-H5Y6UV6E.js +0 -2
  221. package/dist/cli-bundle/chunks/chunk-H7KGWPDF.js +0 -2
  222. package/dist/cli-bundle/chunks/chunk-HFSD77TQ.js +0 -2
  223. package/dist/cli-bundle/chunks/chunk-HX2GTA6L.js +0 -2
  224. package/dist/cli-bundle/chunks/chunk-J2IEKAVR.js +0 -2
  225. package/dist/cli-bundle/chunks/chunk-JC6FKIFM.js +0 -2
  226. package/dist/cli-bundle/chunks/chunk-K44PYFXH.js +0 -2
  227. package/dist/cli-bundle/chunks/chunk-K4KGEEBT.js +0 -2
  228. package/dist/cli-bundle/chunks/chunk-KFLK5TRH.js +0 -21
  229. package/dist/cli-bundle/chunks/chunk-KL6IEBV2.js +0 -2
  230. package/dist/cli-bundle/chunks/chunk-KWQZDZSS.js +0 -2
  231. package/dist/cli-bundle/chunks/chunk-KZ4X3DGU.js +0 -3
  232. package/dist/cli-bundle/chunks/chunk-LD77HJMQ.js +0 -13
  233. package/dist/cli-bundle/chunks/chunk-LEPJJ6QC.js +0 -2
  234. package/dist/cli-bundle/chunks/chunk-ME2JJ4LA.js +0 -3
  235. package/dist/cli-bundle/chunks/chunk-NE5VRDAI.js +0 -2
  236. package/dist/cli-bundle/chunks/chunk-NFLJ3FHD.js +0 -2
  237. package/dist/cli-bundle/chunks/chunk-NG6OXIBR.js +0 -19
  238. package/dist/cli-bundle/chunks/chunk-NYIGHWQY.js +0 -8
  239. package/dist/cli-bundle/chunks/chunk-NZ75GNSA.js +0 -2
  240. package/dist/cli-bundle/chunks/chunk-PCJWJNC2.js +0 -2
  241. package/dist/cli-bundle/chunks/chunk-PD3225AM.js +0 -2
  242. package/dist/cli-bundle/chunks/chunk-PDEGKG7P.js +0 -2
  243. package/dist/cli-bundle/chunks/chunk-PIE5HBNA.js +0 -2
  244. package/dist/cli-bundle/chunks/chunk-PW2H7YJR.js +0 -56
  245. package/dist/cli-bundle/chunks/chunk-RSIC5OPE.js +0 -2
  246. package/dist/cli-bundle/chunks/chunk-TPKN3S7S.js +0 -2
  247. package/dist/cli-bundle/chunks/chunk-TPXAXTCO.js +0 -2
  248. package/dist/cli-bundle/chunks/chunk-UFWUJO4V.js +0 -2
  249. package/dist/cli-bundle/chunks/chunk-UQLZQVFW.js +0 -55
  250. package/dist/cli-bundle/chunks/chunk-VT3Z5G7D.js +0 -2
  251. package/dist/cli-bundle/chunks/chunk-WOD3WWUN.js +0 -2
  252. package/dist/cli-bundle/chunks/chunk-WSJEIGJF.js +0 -3
  253. package/dist/cli-bundle/chunks/chunk-WYNUU7ZW.js +0 -2008
  254. package/dist/cli-bundle/chunks/chunk-YGPNCCXZ.js +0 -2
  255. package/dist/cli-bundle/chunks/close-CMY3BAUG.js +0 -2
  256. package/dist/cli-bundle/chunks/close-many-SA4XZCTK.js +0 -2
  257. package/dist/cli-bundle/chunks/comments-EZ556ZD3.js +0 -2
  258. package/dist/cli-bundle/chunks/copy-ZSGPA52X.js +0 -2
  259. package/dist/cli-bundle/chunks/create-I5DVV4YG.js +0 -2
  260. package/dist/cli-bundle/chunks/delete-RL3JACSW.js +0 -2
  261. package/dist/cli-bundle/chunks/deps-S7UBCECS.js +0 -2
  262. package/dist/cli-bundle/chunks/docs-ZZNVBBYO.js +0 -2
  263. package/dist/cli-bundle/chunks/files-27C337VT.js +0 -2
  264. package/dist/cli-bundle/chunks/focus-5Z2SG7LU.js +0 -2
  265. package/dist/cli-bundle/chunks/history-compact-HJQK67CZ.js +0 -2
  266. package/dist/cli-bundle/chunks/history-redact-PWC6PDWA.js +0 -2
  267. package/dist/cli-bundle/chunks/history-repair-N3CY4WBF.js +0 -2
  268. package/dist/cli-bundle/chunks/learnings-4FH23XDT.js +0 -2
  269. package/dist/cli-bundle/chunks/profile-5Y5XXH5N.js +0 -2
  270. package/dist/cli-bundle/chunks/register-mutation-YGYPW3BL.js +0 -20
  271. package/dist/cli-bundle/chunks/register-operations-WMDSUMQF.js +0 -2
  272. package/dist/cli-bundle/chunks/register-setup-DL7FFABC.js +0 -2
  273. package/dist/cli-bundle/chunks/restore-6KYBV5BY.js +0 -2
  274. package/dist/cli-bundle/chunks/schema-EQGKBYXJ.js +0 -2
  275. package/dist/cli-bundle/chunks/update-QVTYOD6I.js +0 -2
  276. package/dist/cli-bundle/chunks/update-many-DJSBU525.js +0 -2
  277. package/dist/cli-bundle/focused-chunks/chunk-2ECLECMK.js +0 -12
  278. package/dist/cli-bundle/focused-chunks/chunk-3K4XV2BF.js +0 -16
  279. package/dist/cli-bundle/focused-chunks/chunk-4EX25PXM.js +0 -8
  280. package/dist/cli-bundle/focused-chunks/chunk-CIXVQPB7.js +0 -5
  281. package/dist/cli-bundle/focused-chunks/chunk-DLTS3IHM.js +0 -2
  282. package/dist/cli-bundle/focused-chunks/chunk-DQ6FKGL3.js +0 -14
  283. package/dist/cli-bundle/focused-chunks/chunk-JLG2C4EQ.js +0 -2
  284. package/dist/cli-bundle/focused-chunks/chunk-MHMTKV5V.js +0 -2
  285. package/dist/cli-bundle/focused-chunks/chunk-MOTJFQ3F.js +0 -153
  286. package/dist/cli-bundle/focused-chunks/chunk-RW5IYD4J.js +0 -4
  287. package/dist/cli-bundle/focused-chunks/chunk-VZFU2R4M.js +0 -2
  288. package/dist/cli-bundle/focused-chunks/chunk-ZJIMJHDB.js +0 -2
@@ -1,21 +0,0 @@
1
- import{a as It}from"./chunk-HFSD77TQ.js";import{b as na}from"./chunk-J2IEKAVR.js";import{a as ta}from"./chunk-KL6IEBV2.js";import{a as ea}from"./chunk-WSJEIGJF.js";import{f as jo}from"./chunk-H5Y6UV6E.js";import{B as sa,c as Ln,m as Qo,n as Pn,o as Mn,r as Zo}from"./chunk-PW2H7YJR.js";import{e as Oo,j as Ae,l as Xo,m as Jo,n as Ct}from"./chunk-CALJHNBL.js";import{oa as $o,qa as Dn,ra}from"./chunk-LD77HJMQ.js";import{b as ni,c as si,d as ri,e as ii,g as oi,l as ai,m as ci,o as di,p as li}from"./chunk-PIE5HBNA.js";import{B as Ro,x as Sn}from"./chunk-NFLJ3FHD.js";import{A as On,B as Ho,C as Vo,D as Ko,E as Yo,P as Nn,q as qo,r as Bo,s as En,u as Cn,v as In,w as An,x as Wo,y as zo,z as Rn}from"./chunk-7MXHZHSQ.js";import{d as Go}from"./chunk-CUGNQQKH.js";import{i as Uo}from"./chunk-TPKN3S7S.js";import{j as Po,o as Mo,p as Do,q as Fo}from"./chunk-NZ75GNSA.js";import{a as No,d as Lo,e as Et}from"./chunk-H7KGWPDF.js";import{$ as ro,A as kn,Aa as xo,B as Ni,Ba as So,C as Li,Ca as le,D as Pi,Da as Eo,E as Mi,Ea as Co,F as Di,Fa as Io,G as Fi,Ga as Ao,H as ji,I as $i,J as Ui,K as Gi,L as qi,M as Bi,N as Wi,O as zi,P as Hi,Q as Vi,R as Ki,S as Yi,T as Xi,U as Ji,V as Qi,W as Zi,X as eo,Y as to,Z as no,_ as so,c as vn,da as io,e as ui,ea as oo,f as mi,fa as ao,g as _i,ga as co,h as pi,ha as lo,i as fi,ia as uo,j as gi,ja as mo,k as hi,ka as _o,l as yi,la as po,m as bi,ma as fo,n as wi,na as go,o as vi,oa as ho,p as ki,q as Ti,r as xi,ra as yo,s as Si,sa as bo,t as Ei,ta as Tn,u as Ci,ua as wo,v as Ii,w as Ai,wa as xn,x as Ri,xa as vo,ya as ko,z as Oi,za as To}from"./chunk-WOD3WWUN.js";import{B as bn,C as Hr,Ea as Qr,Fa as Zr,Ga as ei,Ha as ti,M as Vr,R as Kr,T as Yr,W as wn,Y as Xr,wa as Jr,x as qr}from"./chunk-NG6OXIBR.js";import{a as yn}from"./chunk-K4KGEEBT.js";import{f as hn,i as jr,j as He}from"./chunk-NYIGHWQY.js";import{$a as fr,$c as wt,$f as St,A as f,Aa as ir,Ad as xr,Bb as Se,C as g,Cb as pn,Cf as xt,Da as V,Db as fn,De as Ir,Df as Fr,E as P,Ec as yt,Ee as Ar,Fe as Rr,Ga as or,Ge as Or,He as Nr,Ia as ge,Ie as Lr,Je as he,Jf as $r,Kd as Sr,Ke as Pr,La as I,Ma as ar,Mf as Ur,Na as Z,Nc as ee,Ne as ze,Nf as N,Oa as O,Oc as yr,Of as Gr,Pc as br,Qa as cr,R as v,Ra as dr,Rc as wr,Sa as ft,T as Zs,Ua as lr,Ue as Mr,Va as un,Vb as gt,Wa as mn,Xa as ur,Xb as ht,Xc as vr,Ya as mr,Yc as bt,Yf as Br,Za as _r,Zf as Wr,_a as pr,_e as gn,_f as zr,a as de,ab as gr,ad as vt,ag as Ie,b as x,c as j,d as se,da as ln,dd as Ce,dg as ye,g as Ks,gd as kt,ha as er,jb as _n,la as tr,lc as W,ma as nr,me as Er,na as sr,oa as rr,od as Be,p as Ys,pd as We,r as Xs,t as Js,uc as Ee,ud as kr,ue as Cr,wc as X,x as Qs,xf as Tt,y as pt,yc as hr,yd as Tr,yf as Dr,z as qe,zd as J}from"./chunk-D4FPS43D.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0579277-f123-5f96-8664-dfe05ade1b24")}catch{}})();async function ia(e,t,n){return[...await xr(dr(e,t),t).catch(()=>[])].reverse().find(i=>i.patch.some(o=>o.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9c3fc3ab-ba84-5f6d-a05c-bc452ae26c15")}catch{}})();var oa="no_available_next_item";function eu(e){return e instanceof g&&e.context?.code==="already_claimed_by"}async function tu(e,t,n,s={}){let r=I(process.cwd(),n.path);if(!await x(O(r)))throw new g(`Tracker is not initialized at ${r}. Run pm init first.`,f.NOT_FOUND);let i=await N(r),o=ee(i.schema),a=J(s.author,i.author_default),c=Tr(a),d=null,l=!1,u=[],m=await ye({pmRoot:r,settings:i,id:e,op:"claim",author:a,message:s.message,force:t,skipNoop:!0,async mutate(_){let h=_.metadata.assignee??"",y=_.metadata.claim_principal?.trim()||h;if(d=h.trim().length>0?h:null,wr(_.metadata.status,o)&&!t)throw new g(`Cannot claim terminal item ${_.metadata.id} without --force`,f.CONFLICT);if(d!==null&&y!==c){if(s.ifAvailable===!0)return l=!0,u.push(`claim_skipped_held_by:${d}`),{changedFields:[]};if(!t){let T=await ia(r,_.metadata.id,h);throw new g(`Item ${_.metadata.id} is already ${T}. Use --force to take over, or --if-available to skip without failing.`,f.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}u.push(`claim_takeover:${d}->${a}`)}return _.metadata.assignee=a,_.metadata.claim_principal=c,{changedFields:["assignee","claim_principal"],warnings:u}}});return{item:m.item,claimed_by:l&&d!==null?d:a,previous_assignee:d,forced:t,...l?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function Cw(e,t,n={},s={}){let r=nu(n.maxAttempts),i=await N(I(process.cwd(),t.path)),o={...n,author:J(n.author,i.author_default)},a=await $o({...s,callerAuthor:o.author,limit:String(r)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return su(c.slice(0,r),e,t,o)}function nu(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new g("--max-attempts must be an integer from 1 to 100",f.USAGE);return t}async function su(e,t,n,s={},r=tu){let i=0;for(let a of e){i+=1;try{let c=await r(a.id,t,n,s),d={...c,recommendation:a,attempts:i,available:!0};if(!c.skipped)return d}catch(c){if(!eu(c))throw c}}if(s.ifAvailable===!0)return{available:!1,item:null,claimed_by:J(s.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:i,warnings:[oa]};let o=i===0;throw new g(o?"No actionable items matched the selection filters":"No actionable item remained available to claim",o?f.NOT_FOUND:f.CONFLICT,{code:oa,why:o?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[o?"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 Iw(e,t,n,s={}){let r=I(process.cwd(),n.path);if(!await x(O(r)))throw new g(`Tracker is not initialized at ${r}. Run pm init first.`,f.NOT_FOUND);let i=await N(r),o=J(s.author,i.author_default),a=s.ownershipReleaseBypass===!0,c=null,d;try{d=await ye({pmRoot:r,settings:i,id:e,op:"release",author:o,message:s.message,force:t,bypassAssigneeConflict:a,mutate(l){return c=l.metadata.assignee??null,!c&&!l.metadata.claim_principal?{changedFields:[]}:(delete l.metadata.assignee,delete l.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(l){jo(l,{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."]})}return{item:d.item,released_by:o,previous_assignee:c,forced:t}}import Fn from"node:fs/promises";import aa 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]="a6c0aa24-501a-5e76-a669-91d125634cf1")}catch{}})();var ru=1440*60*1e3,iu=new Set(["committed","compensated"]);function ou(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function au(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function cu(e,t,n,s,r){let i=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(i))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=s-i;return iu.has(t)?o>r?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function du(e,t,n,s){let r=s.hooks?.onRead?await s.hooks.onRead(e):[],i=au(await Fn.readFile(e,"utf8")),o=cu(t,i.status,i.updatedAt,s.nowMs,s.retentionMs);return o.entry.reason==="unparseable"&&r.push(`transaction_journal_unparseable:${n}`),o.remove&&!s.dryRun&&(await Fn.rm(e,{force:!0}),s.hooks?.onWrite&&r.push(...await s.hooks.onWrite(e))),{decision:o,warnings:r}}async function ca(e,t){let{dryRun:n,hooks:s}=t,r=t.now??Date.now(),i=Math.max(0,t.retentionDays)*ru,o=aa.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Fn.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(ou(d,"ENOENT"))return a;throw d}for(let d of c){let l=aa.join(o,d),u=`transactions/sdk/${d}`,m=await du(l,u,d,{dryRun:n,hooks:s,nowMs:r,retentionMs:i});a.warnings.push(...m.warnings),a.scanned+=1;let{decision:_}=m;if(!_.remove){a.retained.push(u),a.entries.push(_.entry);continue}a.removed.push(u),a.entries.push(_.entry)}return a}import Re from"node:fs/promises";import Nt from"node:path";import At from"node:fs/promises";import jn 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]="8cc32963-26eb-5e08-bffb-2d8da152a43f")}catch{}})();var lu=864e5;function Rt(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function uu(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function mu(e,t){let n;try{n=await At.readdir(e,{withFileTypes:!0})}catch(r){if(Rt(r,"ENOENT"))return[];throw r}let s=[];for(let r of n)if(r.isDirectory()){let i=jn.join(e,r.name),o;try{o=await At.readdir(i)}catch(a){Rt(a,"ENOENT")||t.push(`checkpoint_subdir_unreadable:${r.name}`);continue}for(let a of o)a.endsWith(".json")&&s.push(`${r.name}/${a}`)}else r.name.endsWith(".json")&&s.push(r.name);return s.sort()}async function da(e,t){let{dryRun:n,hooks:s}=t,r=t.now??Date.now(),i=Math.max(0,t.retentionDays)*lu,o=jn.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await mu(o,a.warnings);for(let d of c){let l=jn.join(o,d),u=`checkpoints/${d}`;a.scanned+=1,s?.onRead&&a.warnings.push(...await s.onRead(l));let m;try{m=await At.readFile(l,"utf8")}catch(w){if(Rt(w,"ENOENT")){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let _=uu(m),p=_===null?Number.NaN:Date.parse(_);if(!Number.isFinite(p)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:_,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=r-p,y={file:u,created_at:_,age_seconds:Math.floor(h/1e3),stale:h>i,reason:h>i?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await At.unlink(l)}catch(w){if(!Rt(w,"ENOENT")){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}s?.onWrite&&a.warnings.push(...await s.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}import Ve from"node:fs/promises";import Ot 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]="a026943f-1a46-526b-bfaa-435025c65c2a")}catch{}})();function _u(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:s,owner:r,created_at:i,ttl_seconds:o}=n;return typeof s!="string"||typeof r!="string"||typeof i!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:s,owner:r,created_at:i,ttl_seconds:o}}function Ke(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function la(e,t,n){let s=_u(t);if(s===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let r=Date.parse(s.created_at);if(!Number.isFinite(r))return{detail:"invalid_timestamp",entry:{file:e,id:s.id,owner:s.owner,created_at:s.created_at,ttl_seconds:s.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let i=n-r,o=Math.floor(i/1e3),a=i>s.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:s.id,owner:s.owner,created_at:s.created_at,ttl_seconds:s.ttl_seconds,age_seconds:o,stale:a,reason:a?"expired":"active"}}}async function ua(e,t){let n=t??Date.now(),s=Ot.join(e,"locks"),r={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},i;try{i=(await Ve.readdir(s)).filter(a=>a.endsWith(".lock")).sort()}catch(o){if(Ke(o,"ENOENT"))return r;throw o}for(let o of i){let a;try{a=await Ve.readFile(Ot.join(s,o),"utf8")}catch(d){if(Ke(d,"ENOENT"))continue;r.scanned+=1,r.unreadable_lock_count+=1;continue}r.scanned+=1;let{detail:c}=la(o,a,n);c==="active"?r.active_lock_count+=1:c==="expired"?r.stale_lock_count+=1:r.unparseable_lock_count+=1}return r}async function ma(e,t){let{dryRun:n,hooks:s}=t,r=t.now??Date.now(),i=Ot.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},a;try{a=(await Ve.readdir(i)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if(Ke(c,"ENOENT"))return o;throw c}for(let c of a){o.scanned+=1;let d=Ot.join(i,c),l=`locks/${c}`;if(s?.onRead){let _=await s.onRead(d);o.warnings.push(..._)}let u;try{u=await Ve.readFile(d,"utf8")}catch(_){if(Ke(_,"ENOENT")){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${c}`),o.retained.push(l),o.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=la(c,u,r);if(m.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="active"){o.retained.push(l),o.entries.push(m.entry);continue}if(!n){try{await Ve.unlink(d)}catch(_){if(!Ke(_,"ENOENT")){o.warnings.push(`lock_remove_failed:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}}if(s?.onWrite){let _=await s.onWrite(d);o.warnings.push(..._)}}o.removed.push(l),o.entries.push(m.entry)}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]="0973a87f-2b63-5fa1-9624-82897d181f71")}catch{}})();var Ye=["index","embeddings","runtime","locks","checkpoints","transactions"],pu=1440*60*1e3,fu=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];function _a(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function gu(e,t,n){let s=t.relativePath,r=Nt.join(e,s),i=await X({path:r,scope:"project"});try{let o=await Re.stat(r);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...i,`not_a_file:${s}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...i,`not_a_directory:${s}`]};if(n)return{removed:!0,warnings:i};t.kind==="file"?await Re.unlink(r):await Re.rm(r,{recursive:!0,force:!0});let a=await Ee({path:r,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...i,...a]}}catch(o){if(_a(o,"ENOENT"))return{removed:!1,warnings:i};throw o}}async function hu(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],s=[],r=[],i=[],o=Date.now()-pu;for(let a of n){let c=Nt.join(e,a.relativePath);if(!await x(c))continue;let d=(await Re.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=Nt.posix.join(a.relativePath,l),m=Nt.join(c,l);i.push(...await X({path:m,scope:"project"}));let _=await Re.stat(m).catch(p=>{if(!_a(p,"ENOENT"))throw p});if(_){if(_.mtimeMs>o){r.push(u);continue}s.push(u),!t&&(await Re.rm(m,{recursive:!0,force:!0}),i.push(...await Ee({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:s,retained:r,warnings:i}}function yu(e){if(!e||e.length===0)return[...Ye];let t=e.flatMap(s=>s.split(",")).map(s=>s.trim().toLowerCase()).filter(s=>s.length>0);if(t.length===0)throw new g(`--scope requires at least one value (${Ye.join(",")})`,f.USAGE);let n=new Set;for(let s of t){if(!Ye.includes(s))throw new g(`Invalid --scope value "${s}". Expected one or more of: ${Ye.join(", ")}`,f.USAGE);n.add(s)}return Ye.filter(s=>n.has(s))}function bu(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),s=e.removed.some(r=>r==="index/manifest.json"||r==="search/embeddings.jsonl"||r==="search/vectorization-status.json"||r==="search/lancedb"||r==="search/pending-refresh.json"||r==="search/pending-refresh.gate.lock");return n&&s&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(r=>r.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(r=>r.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function Jw(e,t={}){let n=I(process.cwd(),e.path);if(!await x(O(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,f.NOT_FOUND);let s=await N(n),r=t.dryRun===!0,i=yu(t.scope),o=fu.filter(p=>i.includes(p.scope)),a=[],c=[],d=[];for(let p of o){let h=await gu(n,p,r);h.removed?a.push(p.relativePath):c.push(p.relativePath),d.push(...h.warnings)}if(i.includes("runtime")){let p=await hu(n,r);a.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(i.includes("locks")){let p=await ma(n,{dryRun:r,hooks:{onRead:h=>X({path:h,scope:"project"}),onWrite:h=>Ee({path:h,scope:"project",op:"gc:lock_remove"})}});a.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),l={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(i.includes("transactions")){let p=s.checkpoints.retention_days,h=await ca(n,{dryRun:r,retentionDays:p,hooks:{onRead:y=>X({path:y,scope:"project"}),onWrite:y=>Ee({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}let m;if(i.includes("checkpoints")){let p=s.checkpoints.retention_days,h=await da(n,{dryRun:r,retentionDays:p,hooks:{onRead:y=>X({path:y,scope:"project"}),onWrite:y=>Ee({path:y,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),m={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}d.push(...await hr({mode:r?"gc:dry-run":"gc",total_items:o.length}));let _=bu({dryRun:r,scopes:i,removed:a});return{ok:d.length===0,dry_run:r,scope:i,removed:a,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:_,generated_at:v()}}import Lt from"node:fs/promises";import Pt 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]="09427917-8347-59cc-9358-452671aed3c3")}catch{}})();function Xe(e,t){throw new g(e,f.USAGE,{code:t})}var wu="2026-07-15T06:22:12.276Z",vu=Date.parse(wu),ku=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],pa=e=>typeof e=="string"?e:"",fa=e=>{let t=e??{},n=pa(t.author).trim().toLowerCase(),s=Number(["","unknown"].includes(n)),r=+(Date.parse(pa(t.ts))>=vu);return ku[s][r]};function ga(e,t,n=20,s=new Set,r=!1){let i=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,_]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(_)}catch{continue}d+=1;let h=fa(p);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&s.has(`${e}:${m+1}`)){u+=1;continue}a[h]+=1,r&&h==="actionable_unknown"&&o.push({item_id:e,line:m+1}),i.length<c&&i.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:i,samples_truncated:a.legacy_unknown+a.actionable_unknown>i.length,actionable_events:o}}var iv=(e,t,n=20,s=new Set)=>ga(e,t,n,s);function Tu(e){let t=new Set;for(let n of e.split(/\r?\n/)){let s;try{s=JSON.parse(n)}catch{continue}let i=(typeof s=="object"&&s!==null&&typeof s.context=="object"&&s.context!==null?s.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let o of i.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Je=async(e,t=20,n=!1)=>{let s=Pt.join(e,"history"),r;try{r=(await Lt.readdir(s)).filter(w=>w.endsWith(".jsonl")).sort((w,T)=>w.localeCompare(T))}catch{r=[]}let i=new Set,o=[],a=[],c=0,d=0,l=0,u=0,m=0,_=0,p="_workspace.jsonl",h=new Set;if(r.includes(p))try{h=Tu(await Lt.readFile(Pt.join(s,p),"utf8"))}catch{h=new Set}for(let w of r){let T;try{T=await Lt.readFile(Pt.join(s,w),"utf8")}catch{continue}let C=w.slice(0,-6),k=ga(C,T,t-o.length,h,n);c+=1,d+=k.checked_events,l+=k.unknown_event_count,u+=k.legacy_unknown_event_count,m+=k.actionable_unknown_event_count,_+=k.acknowledged_actionable_event_count,k.unknown_event_count>0&&i.add(C),o.push(...k.samples),n&&a.push(...k.actionable_events)}let y=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:_,affected_item_ids:[...i].sort((w,T)=>w.localeCompare(T)),samples:o,samples_truncated:y>o.length,...n?{actionable_events:a}:{}}};async function ov(e,t){let n=t.reviewer.trim(),s=t.attributed_author.trim(),r=t.reason.trim(),i=t.events??[];+(t.all_actionable===!0)+ +(i.length>0)>1&&Xe("Author acknowledgment accepts either explicit events or all_actionable, not both.","history_author_acknowledge_selector_conflict");let a=t.all_actionable===!0?(await Je(e,0,!0)).actionable_events:i;[a.length>0,n.length>0,n.toLowerCase()!=="unknown",s.length>0,s.toLowerCase()!=="unknown",r.length>0].includes(!1)&&Xe("Author acknowledgment requires events, reviewer, attributed_author, and reason.","history_author_acknowledge_required_values_missing");let d=[...new Map(a.map(m=>[`${m.item_id}:${m.line}`,{item_id:m.item_id,line:m.line}])).values()].sort((m,_)=>m.item_id.localeCompare(_.item_id)||m.line-_.line);for(let m of d){[/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1)&&Xe(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,"history_author_acknowledge_target_unreadable");let p;try{let y=(await Lt.readFile(Pt.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];p=JSON.parse(y??"")}catch{Xe(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,"history_author_acknowledge_target_unreadable")}fa(p)!=="actionable_unknown"&&Xe(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`,"history_author_acknowledge_target_not_actionable")}let l=await N(e),u=await xt({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:d,attributed_author:s}},message:r,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms});return{acknowledged:d.length,history_path:u.historyPath}}import{execFile as xu}from"node:child_process";import{randomUUID as Su}from"node:crypto";import{readdir as Eu,readFile as Cu}from"node:fs/promises";import Qe from"node:path";import{promisify as Iu}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]="c4721ede-e557-5720-a9c2-4b2b344cc6cc")}catch{}})();var Au=Iu(xu);async function $n(e){try{let{stdout:t}=await Au("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}function ha(e){return`${e}.json`}function gv(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,preferred:e.preferred,decisions:e.decisions.map(t=>({field:t.field,retained_hash:fn(Se(t.retained)),discarded_hash:fn(Se(t.discarded))}))}}async function hv(e){let t=await $n(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),s=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,r=Qe.basename(s,Qe.extname(s)),i={version:1,id:Su(),item_path:s.replaceAll("\\","/"),item_id:r,preferred:e.preferred,fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:v()};return await de(t),await se(Qe.join(t,ha(i.id)),`${JSON.stringify(i,null,2)}
2
- `),i}async function Ze(e,t={}){let n=await $n(e);if(n===null||!await x(n))return[];let s=[],r;try{r=await Eu(n)}catch{return[]}for(let i of r.sort((o,a)=>o.localeCompare(a)))if(i.endsWith(".json"))try{let o=JSON.parse(await Cu(Qe.join(n,i),"utf8"));o.version===1&&(t.includeReconciled||o.state==="pending")&&s.push(o)}catch{}return s.sort((i,o)=>i.created_at.localeCompare(o.created_at))}async function yv(e,t){let n=await $n(e);n!==null&&await se(Qe.join(n,ha(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:v()},null,2)}
3
- `)}async function bv(e){let t=await Ze(e.cwd??process.cwd(),e);return{ok:!0,count:t.length,receipts:t,generated_at:v()}}import ie from"node:fs/promises";import z 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]="6a350683-275b-5d4d-ae02-45798b115f89")}catch{}})();var Ru=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:"pm validate --check-history-drift --fix-hints",summary:"Historical mutations lack attributable authorship. Configure PM_AUTHOR, pass global --author, or set author_default so future audit events are attributable."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_unknown_author_events",command:"pm config project set author_default <stable-agent-id>",summary:"Historical mutations lack attributable authorship. Set a stable default or use invocation-wide --author for future events; existing audit history remains append-only."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Ou(e){if(typeof e!="string")return;let t=e.trim();for(let n of Ru)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Un(e){let t={};for(let n of e){let s=Ou(n);s!==void 0&&!Object.prototype.hasOwnProperty.call(t,s.code)&&(t[s.code]=s.command)}return t}function ya(e){return Object.values(Un(e))}import{execFile as Nu}from"node:child_process";import{realpath as Lu}from"node:fs/promises";import ba from"node:path";import{promisify as Pu}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]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var Mu=Pu(Nu),Du=32*1024*1024,Fu=1e4,ju=["search/eval-queries.json"];function Gn(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function $u(e){return`'${e.replaceAll("'","'\\''")}'`}async function Uu(e,t=Lu){return t(e).catch(()=>ba.resolve(e))}async function Mt(e){let t=await Ae(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await Uu(e),s=Gn(ba.relative(t,n));if(s.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let r=Oo.map(i=>`${s}/${Gn(i)}`);try{let{stdout:i}=await Mu("git",["ls-files","-z","--",...r.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:Du,windowsHide:!0,timeout:Fu}),o=new Set(ju.map(d=>`${s}/${d}`)),a=[...new Set(i.split("\0").filter(d=>d.length>0&&!o.has(Gn(d))))].sort((d,l)=>d.localeCompare(l)),c=r.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:s,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>$u(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:s,tracked_paths:[],tracked_path_count:0,remediation_command: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]="34fc99f6-45e5-53f2-96eb-767d50ed449c")}catch{}})();var Gu=new Set(ei),va=25,et=8,qu=z.join("runtime","telemetry","events.jsonl"),Bu=z.join("runtime","telemetry","state.json"),Wu=2500,zu=500,ka=Zr-3,Hu=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Ta(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("stale_in_progress_items:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function xa(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Ne(e){return e.trim().toLowerCase()}function Wn(e,t){let n=Ne(e),s=Ne(t);return n.startsWith("builtin-")?!0:s==="beads"||s==="todos"}async function Vn(e){try{return(await ie.stat(e)).isDirectory()}catch{return!1}}async function Vu(e){let t=(await ie.readdir(e,{withFileTypes:!0})).filter(s=>s.isDirectory()),n=await Promise.all(t.map(s=>ie.readdir(z.join(e,s.name),{withFileTypes:!0})));return new Set(n.flatMap(s=>s.filter(r=>r.isFile()).filter(r=>ge.some(i=>r.name.endsWith(i))).map(r=>z.parse(r.name).name)))}async function Ku(e,t,n,s){let r=await X({path:e,scope:"project"}),i=t!=="_workspace"&&!s.has(t);if(!n.enabled&&!i)return{warnings:r,overThreshold:!1,classification:"live"};let o;try{o=await ie.readFile(e,"utf8")}catch{return{warnings:r,overThreshold:!1,classification:"unreadable"}}let a="live";if(i){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:r,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function Yu(e,t,n){let s=z.join(e,"history");if(!await Vn(s))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let r=(await ie.readdir(s)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),o=t.enabled?t.max_entries:null,a=[],c=[],d=[],l=[];for(let u of r){let m=z.join(s,u),_=u.slice(0,-6),p=await Ku(m,_,t,n);a.push(...p.warnings),p.classification==="tombstone"&&d.push(_),p.classification==="orphaned"&&l.push(_),p.overThreshold&&c.push(_)}return{count:r.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:o,tombstones:d,orphaned:l}}function zn(e,t){return z.relative(e,t).replaceAll("\\","/")}async function Sa(e,t){let n=[...new Set(Object.values(t))].sort((r,i)=>r.localeCompare(i)),s=[];for(let r of n){let i=z.join(e,r),o=[];try{o=await ie.readdir(i)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT")continue;continue}for(let a of o)ge.some(c=>a.toLowerCase().endsWith(c))&&s.push(z.join(i,a))}return s.sort((r,i)=>zn(e,r).localeCompare(zn(e,i))),s}function Xu(e){return!(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")}async function Ju(e,t,n){let s=await Sa(e,t),r=[],i=[],o=[],a=[],c=yt(W());for(let d of s){let l=zn(e,d),u;try{u=await ie.readFile(d,"utf8")}catch{r.push(l);continue}let m=Ce(u);if(m){i.push({path:l,...m});continue}try{let _=kt(u,{format:cr(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:bt(_.metadata)})}catch{o.push(l)}}return{paths:s,unreadable:r,conflictMarkers:i,parseFailures:o,formatVersions:a}}async function Qu(e){let t=z.join(e,"history"),n=[],s=[],r=[],i=[];try{i=(await ie.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,a)=>o.localeCompare(a))}catch(o){Xu(o)&&n.push("history")}for(let o of i){let a=o.slice(0,-6),c;try{c=await ie.readFile(z.join(t,o),"utf8")}catch{n.push(a);continue}let d=Ce(c);if(d){s.push({id:a,...d});continue}c.split(/\r?\n/).forEach((l,u)=>{if(l.trim())try{JSON.parse(l)}catch{r.push({id:a,line:u+1})}})}return{files:i,unreadable:n,conflictMarkers:s,invalidJson:r}}async function Zu(e,t,n,s){let r=await Ju(e,t,n),i=await Qu(e),o=wt(r.formatVersions),a=await Mt(e),c=await Ae(e),d=c===null?null:await Ct(c),l=c===null?[]:await Ze(c),u=d?.status==="missing"&&d.missing_keys.length===5&&d.drifted_keys.length===0,m=[...r.unreadable.map(p=>`integrity_item_unreadable:${p}`),...r.conflictMarkers.map(p=>`integrity_item_conflict_marker:${p.path}:L${p.line}`),...r.parseFailures.map(p=>`integrity_item_parse_failed:${p}`),...i.unreadable.map(p=>`integrity_history_unreadable:${p}`),...i.conflictMarkers.map(p=>`integrity_history_conflict_marker:${p.id}:L${p.line}`),...i.invalidJson.map(p=>`integrity_history_invalid_json:${p.id}:L${p.line}`),...o.outdated.map(p=>`integrity_item_outdated_format_version:${p}`),...o.ahead.map(p=>`integrity_item_ahead_format_version:${p}`),...a.tracked_path_count>0?[`tracked_runtime_cache_files:${a.tracked_path_count}`]:[],...d!==null&&d.status!=="ok"?[`merge_driver_configuration_${u?"missing":"drift"}:${d.missing_keys.length+d.drifted_keys.length}`]:[],...l.length>0?[`merge_decisions_unreviewed:${l.length}`]:[]],_=[...new Set(m)].sort((p,h)=>p.localeCompare(h));return{check:{name:"integrity",status:_.length===0?"ok":"warn",details:{checked_item_files:r.paths.length,checked_history_streams:i.files.length,counts:{item_unreadable:r.unreadable.length,item_conflict_markers:r.conflictMarkers.length,item_parse_failures:r.parseFailures.length,history_unreadable:i.unreadable.length,history_conflict_markers:i.conflictMarkers.length,history_invalid_json:i.invalidJson.length,item_outdated_format_version:o.outdated.length,item_ahead_format_version:o.ahead.length,tracked_runtime_cache_files:a.tracked_path_count,merge_driver_configuration:d===null||d.status==="ok"?0:d.missing_keys.length+d.drifted_keys.length,pending_merge_decisions:l.length},item_unreadable:r.unreadable,item_conflict_markers:r.conflictMarkers,item_parse_failures:r.parseFailures,item_outdated_format_version:o.outdated,item_ahead_format_version:o.ahead,history_unreadable:i.unreadable,history_conflict_markers:i.conflictMarkers,history_invalid_json:i.invalidJson,tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command},merge_driver_configuration:d===null?null:{...d,required:s},pending_merge_decision_items:[...new Set(l.map(p=>p.item_id))].sort((p,h)=>p.localeCompare(h))}},warnings:_}}function em(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function tm(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:em(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function nm(e,t){let n=P(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function sm(e){let n=P(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function rm(e){return P(e.reason)??P(e.error)??P(e.message)}function qn(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let s=(e.name??"").localeCompare(t.name??"");return s!==0?s:(e.id??"").localeCompare(t.id??"")}function im(e){let t=[],n=[],s=[];e.forEach((i,o)=>{let a=nm(i.definition,o),c=sm(i.definition);if(c==="applied"){t.push({layer:i.layer,name:i.name,id:a,status:c});return}if(c==="failed"){s.push({layer:i.layer,name:i.name,id:a,status:c,reason:rm(i.definition)});return}n.push({layer:i.layer,name:i.name,id:a,status:c})}),t.sort(qn),n.sort(qn),s.sort(qn);let r=[...s.map(i=>`extension_migration_failed:${i.layer}:${i.name}:${i.id}`),...n.map(i=>`extension_migration_pending:${i.layer}:${i.name}:${i.id}`)];return{summary:{applied:t,pending:n,failed:s,applied_count:t.length,pending_count:n.length,failed_count:s.length},warnings:r}}function Ea(e,t,n,s,r,i,o,a,c){let d=[...new Set(e)].sort((y,w)=>y.localeCompare(w)),l=[...new Set(d.map(y=>xa(y)))].sort((y,w)=>y.localeCompare(w)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,m=c.length>0,_=m?"partial":"full",p=[],h=Qo(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(s.failed_count>0||s.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),r>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${Ks.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:s.failed_count,migration_pending_count:s.pending_count,managed_state_warning_count:r,managed_extension_entries_count:i,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:_,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function om(e,t,n){let s=await gt({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),r=s.loaded.map(b=>tm(b)),i=await ht({...s,loaded:s.loaded}),[o,a]=await Promise.all([Ln(s.roots.project),Ln(s.roots.global)]);await Zo(e,i.registrations.migrations);let c=im(i.registrations.migrations),d={failed:i.failed,warnings:i.warnings,hook_counts:i.hook_counts,command_override_count:i.command_override_count,command_handler_count:i.command_handler_count,parser_override_count:i.parser_override_count,preflight_override_count:i.preflight_override_count,service_override_count:i.service_override_count,renderer_override_count:i.renderer_override_count,registration_counts:i.registration_counts,registrations:i.registrations,migration_status:c.summary,managed_extensions:{project:{path:o.path,count:o.state.entries.length,entries:o.state.entries},global:{path:a.path,count:a.state.entries.length,entries:a.state.entries}}},l=new Set(o.state.entries.map(b=>Ne(b.name))),u=new Set(a.state.entries.map(b=>Ne(b.name))),m=[...new Map(s.loaded.filter(b=>!(b.layer==="project"?l:u).has(Ne(b.name))).map(b=>[`${b.layer}:${b.name}`,{layer:b.layer,name:b.name,directory:b.directory}])).values()].sort((b,R)=>{let q=`${b.layer}:${b.name}`,D=`${R.layer}:${R.name}`;return q.localeCompare(D)}),_=m.map(b=>`${b.layer}:${b.name}`).sort((b,R)=>b.localeCompare(R)),p=m.filter(b=>Wn(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,R)=>b.localeCompare(R)),h=m.filter(b=>!Wn(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,R)=>b.localeCompare(R)),y=h.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${h.length}`]:[],w=[...s.warnings,...d.warnings,...c.warnings,...o.warnings,...a.warnings,...y],T=Pn(w),C=Mn(),k=Ea(w,s.failed.length,i.failed.length,c.summary,o.warnings.length+a.warnings.length,o.state.entries.length+a.state.entries.length,_,p,h);return{check:{name:"extensions",status:w.length===0?"ok":"warn",details:{...s,loaded:r,warnings:w,activation:d,triage:k,...c.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:C,capability_guidance:T}},warnings:w}}function am(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function re(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function cm(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function Dt(e,t){let n=re(e,t);return{...n,sample:n.sample.map(s=>cm(s))}}function L(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(s=>typeof s=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function dm(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var lm={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:L(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:L(e.missing_required,t),missing_optional:L(e.missing_optional,t),missing:L(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:L(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:Dt(e.discovered,t),effective:Dt(e.effective,t),loaded:Dt(e.loaded,t),failed:re(e.failed,t),warnings:L(e.warnings,t),activation:{failed:re(n.failed,t),warnings:L(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:dm(n.migration_status)},triage:e.triage,capability_contract:e.capability_contract,capability_guidance:re(e.capability_guidance,t)}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:L(n.affected_item_ids,t),samples:re(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:L(e.item_unreadable,t),item_conflict_markers:re(e.item_conflict_markers,t),item_parse_failures:L(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:L(n.tracked_paths,t)},history_unreadable:L(e.history_unreadable,t),history_conflict_markers:re(e.history_conflict_markers,t),history_invalid_json:re(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>({checked_items:e.checked_items,counts:e.counts,drifted_items:L(e.drifted_items,t),missing_streams:L(e.missing_streams,t),unreadable_streams:L(e.unreadable_streams,t),hash_mismatches:L(e.hash_mismatches,t),chain_mismatches:L(e.chain_mismatches,t),skipped:e.skipped}),vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:L(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:L(e.stale_items_after,t),skipped:e.skipped})};function Ca(e,t){let n=lm[e.name];return n?n(e.details,t):e.details}function um(e){let t=L(e.warnings,et);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,details:Ca(n,et)})),warnings:t.sample,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:et},generated_at:e.generated_at}}function wa(e){return e.details.skipped===!0}function mm(e){let t=L(e.warnings,et),n=e.checks.filter(wa).map(s=>s.name);return{ok:e.ok,checks:e.checks.filter(s=>!wa(s)).map(s=>({name:s.name,status:s.status,details:{}})),warning_count:t.count,warnings:t.sample,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:et,omitted_checks:n},generated_at:e.generated_at}}function Hn(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=am(e,va);return{values:n.values,truncated:n.truncated,total:e.length}}function Oe(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function _m(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return Gu.has(e)?e:null}function Ft(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function Ia(e){let t=0,n=0,s=0,r=0,i=0;for(let o of e.split(`
4
- `)){let a=o.trim();if(a.length!==0){s+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,i=Math.max(i,d),d>=ka&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:s,highRetryEntries:r,maxAttempts:i}}function pm(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function fm(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function gm(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await Aa(n)}}function hm(e,t,n){let s=[];if(t.invalidRows>0&&s.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return s;let r=n.last_successful_flush_at,i=n.last_failed_flush_at,o=i&&(!r||i>r),a=!r,c=t.validEntries>=zu;return(o||a||c)&&s.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&s.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),s}function ym(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function bm(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Qr?[`telemetry_schema_version_behind:${t}`]:[]}function wm(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,s=t.last_otel_success_at,r=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!r&&(!s||r>=s)?[`telemetry_otel_export_failing:${n}`]:[]}function vm(){return{telemetry_disabled:Oe("PM_TELEMETRY_DISABLED")||Oe("PM_NO_TELEMETRY"),pm_no_telemetry:Oe("PM_NO_TELEMETRY"),telemetry_otel_disabled:Oe("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:Oe("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:_m()}}function km(e,t){return e.telemetry.enabled&&t.validEntries>0}function Tm(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Aa(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(Wu)});return{probe_url:Ft(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let s of Hu){let r=n.headers.get(s)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:Ft(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function xm(e,t){let n=Z(process.cwd()),s=z.join(n,qu),r=z.join(n,Bu),i=await j(s),o=i!==null,a=i?Buffer.byteLength(i,"utf8"):0,c=i?Ia(i):pm(),d=await j(r),{runtimeState:l,stateParseFailed:u}=fm(d),m=e.telemetry.endpoint.trim(),_=Ft(m),p=await gm(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...hm(e,c,l),...ym(p),...bm(p),...wm(e,l));let y=km(e,c),w=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:_,global_pm_root:n,queue_path:s,queue_exists:o,queue_entries:c.validEntries,queue_draining:Tm(y,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:a,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:ka,queue_max_attempts:c.maxAttempts,runtime_state_path:r,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:vm()}},warnings:h}}async function Sm(e){let t;try{t=await ua(e)}catch(s){let r=s instanceof Error?s.message:String(s);return{check:{name:"locks",status:"warn",details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:r,pm_root:e}},warnings:[`locks_scan_failed:${r}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function Em(e,t){let n="metadata",{missingStreams:s,unreadableStreams:r,hashMismatches:i,chainMismatches:o,driftedItems:a}=await It(e,t,{cacheHitVerification:n}),c=[...s.map(d=>`history_drift_missing_stream:${d}`),...r.map(d=>`history_drift_unreadable_stream:${d}`),...i.map(d=>`history_drift_hash_mismatch:${d}`),...o.map(d=>`history_drift_chain_mismatch:${d}`)];return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,cache_hit_verification:n,drifted_items:a,counts:{drifted:a.length,missing_streams:s.length,unreadable_streams:r.length,hash_mismatches:i.length,chain_mismatches:o.length},missing_streams:s,unreadable_streams:r,hash_mismatches:i,chain_mismatches:o}},warnings:c}}function Cm(e,t){let n=qr(e),s=Hr(n.settings),r=Vr(n.settings,t),i=s.active?Kr(s.active.name,s.active.model):null;return{runtimeDefaults:n,providerResolution:s,vectorStoreResolution:r,runtimeEmbeddingIdentity:i,semanticRuntimeAvailable:!!(s.active&&r.active)}}function Im(){return{refreshed:[],skipped:[],warnings:[]}}async function Am(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?Im():Xr(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function Rm(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Yr(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function Om(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,s)=>n.localeCompare(s))}function Nm(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Ra(e,t){let n=t.providerResolution.active?.name??null,s=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:bn(n,e.search?.provider??null),vector_store_active:s,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:bn(s,e.vector_store?.adapter??null)}}function Lm(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function Pm(e,t,n){return e.enabled&&n.length>0&&t}async function Mm(e,t,n,s,r){let i=Cm(t,e),o=await wn(e),a=i.semanticRuntimeAvailable?Dn(n,o.entries):[],c=await Am({pmRoot:e,snapshot:i,refreshPolicy:s,staleBefore:a}),d=await wn(e),l=i.semanticRuntimeAvailable?Dn(n,d.entries):[],u=!i.runtimeDefaults.auto_ollama_defaults_applied,m=Rm({strictVectorizationWarnings:u,semanticRuntimeAvailable:i.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:i.runtimeEmbeddingIdentity}),_=Om({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:i.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=Hn(a,r),h=Hn(l,r),y=Pm(s,i.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:_.length===0?"ok":"warn",details:{semantic_runtime_available:i.semanticRuntimeAvailable,compatibility_mode_auto_defaults:i.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:i.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:i.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:i.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:Lm(s),...Ra(t,i),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:i.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:r?"full":"summary",stale_items_summary_limit:va,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:y,refresh_skipped_reason:Nm(s,i.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:_}}function Dm(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function Fm(e){let t=e.checkOnly===!0,n=e.noRefresh===!0||t,s=e.refreshVectors===!0;if(s&&t)throw new g("--check-only cannot be combined with --refresh-vectors",f.USAGE);if(s&&e.noRefresh===!0)throw new g("--no-refresh cannot be combined with --refresh-vectors",f.USAGE);return{enabled:s||!n,checkOnly:t,noRefresh:n,refreshVectors:s}}var jm=new Set(["extensions","locks","search"]);function $m(e){let t=new Set(Xs.filter(r=>r.length>0)),n=new Set,s=new Set(Object.values(Js));for(let r of e.folders)t.has(r)&&!s.has(r)||(t.delete(r),n.add(r));for(let r of jm)t.delete(r),n.add(r);return{requiredDirs:[...t].sort((r,i)=>r.localeCompare(i)),optionalDirs:[...n].sort((r,i)=>r.localeCompare(i)),optionalDirSet:n}}async function Um(e,t,n){let{requiredDirs:s,optionalDirs:r,optionalDirSet:i}=$m(t),o=[],a=[],c=[];for(let d of[...s,...r]){let l=z.join(e,d);c.push(...await X({path:l,scope:"project"})),!await Vn(l)&&(i.has(d)?a.push(d):o.push(d))}return{requiredDirs:s,optionalDirs:r,missingRequiredDirs:o,missingOptionalDirs:a,missingDirs:n?[...o,...a]:[...o],hookWarnings:c}}function Oa(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,s=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||s)&&e.full!==!0,skipDrift:(e.skipDrift===!0||s)&&e.full!==!0,skipVectors:(e.skipVectors===!0||s)&&e.full!==!0}}async function Gm(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?zr(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):Ie(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Bn(e){return{check:{name:e,status:"ok",details:{skipped:!0}},warnings:[]}}function qm(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function Bm(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function Wm(e){return{name:"settings_values",status:e.length===0?"ok":"warn",details:{warnings:e}}}var Kn=e=>e.unknown_event_count??0,Yn=e=>e.actionable_unknown_event_count??Kn(e);function zm(e,t,n,s,r){let i=Kn(s),o=Yn(s),a=i>0,c=o>0,d=r.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!c&&!d?"ok":"warn",details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...a?{author_attribution:s}:{},...d?{stale_in_progress:r}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Na(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function Hm(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function Vm(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function Km(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historySummary.over_threshold.map(t=>`history_stream_over_compact_threshold:${t}`),...e.authorAttributionWarnings,...e.staleInProgressWarnings],locks:e.locksCheck.warnings,integrity:e.integrityCheck.warnings,history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function Ym(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-repair --all";if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function Xm(e){for(let t of e.checks){let n=Un(e.remediationSources[t.name]);Ym({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}function La(e,t,n){return n?mm(e):t.brief===!0?um(e):e}async function uk(e,t={}){let n=I(process.cwd(),e.path),s=O(n);if(!await x(s))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,f.NOT_FOUND);let{settings:r,warnings:i}=await Ur(n),o=[...new Set(i)],a=V(r,W()),c=t.strictDirectories===!0,d=Fm(t),l=await Um(n,a,c),u=Dm(r),m=await xm(r,{checkTelemetry:t.checkTelemetry===!0}),_=await om(n,r,!!e.noExtensions),p=Oa(t),h=[],y=await Gm({pmRoot:n,settings:r,typeRegistry:a,skipPolicy:p,itemReadWarnings:h}),w=y,T=[...new Set(h)],C=p.skipDrift?{warnings:[]}:await Tt({pmRoot:n,settings:r,itemIds:y.map(dn=>dn.id),commandLabel:"health"}),k=await Yu(n,r.history.compact_policy,await Vu(n)),b=await Je(n,20,t.verboseAuthorEvents===!0),R=Yn(b),q=R>0?[`history_unknown_author_events:${R}`]:[],D=Na(await Jr(n,y,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),$=await Sm(n),Y=p.skipIntegrity?Bn("integrity"):await Zu(n,a.type_to_folder,r.schema,t.requireMergeDrivers===!0),ce=p.skipDrift?Bn("history_drift"):await Em(n,w),S=p.skipVectors?Bn("vectorization"):await Mm(n,r,w,d,t.verboseStaleItems===!0),B=[qm(s,r,o),Bm(l,c),Wm(u),m.check,_.check,zm(y,r,k,b,D.scan),$.check,Y.check,ce.check,S.check],Vs=Hm({directoryState:l,normalizedSettingsReadWarnings:o,settingWarnings:u,normalizedItemReadWarnings:T,telemetryCheck:m,extensionCheck:_,historyPolicyWarnings:C.warnings,historySummary:k,authorAttributionWarnings:q,staleInProgressWarnings:D.warnings,locksCheck:$,integrityCheck:Y,historyDriftCheck:ce,vectorizationCheck:S});Xm({checks:B,remediationSources:Km({directoryState:l,normalizedSettingsReadWarnings:o,settingWarnings:u,telemetryCheck:m,extensionCheck:_,historySummary:k,authorAttributionWarnings:q,staleInProgressWarnings:D.warnings,locksCheck:$,integrityCheck:Y,historyDriftCheck:ce,vectorizationCheck:S}),historyDriftedCount:Vm(ce),overThresholdCount:k.over_threshold.length});let Zl={ok:Vs.filter(dn=>!Ta(dn,t.requireMergeDrivers===!0)).length===0,checks:B,warnings:Vs,generated_at:v()};return La(Zl,t,p.summaryMode)}var mk={buildExtensionHealthTriageSummary:Ea,buildCapabilityContractMetadata:Mn,buildStaleInProgressHealthSummary:Na,buildVectorizationProviderDetails:Ra,collectUnknownCapabilityGuidance:Pn,isAdvisoryHealthWarning:Ta,isDirectory:Vn,isExpectedUnmanagedExtension:Wn,listItemDocumentPaths:Sa,normalizeEndpointForDisplay:Ft,normalizeExtensionNameForMatch:Ne,parseTelemetryQueue:Ia,probeTelemetryEndpointHealth:Aa,projectHealthResult:La,resolveActionableUnknownAuthorEventCount:Yn,resolveHealthSkipPolicy:Oa,resolveUnknownAuthorEventCount:Kn,selectStaleItemDetail:Hn,summarizeHealthCheckDetails:Ca,summarizeExtensionList:Dt,summarizeRecordList:re,summarizeStringList:L,telemetryEnvFlagEnabled:Oe,warningCode:xa};import Le from"node:fs/promises";import Pe 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]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function Jm(e,t){let n=[...new Set(Object.values(t))],s=[];return await Promise.all(n.map(async r=>{let i;try{i=await Le.readdir(Pe.join(e,r))}catch{return}for(let o of i)for(let a of ge)if(o.toLowerCase().endsWith(a)){s.push({relativePath:`${r}/${o}`,id:o.slice(0,-a.length)});break}})),s.sort((r,i)=>r.relativePath.localeCompare(i.relativePath))}function Qm(e,t){let{id:n,relativePath:s,liveItemIds:r,out:i}=e,o=Ce(t);if(o){i.conflictMarkers.push({id:n,path:s,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=null,c=t.split(/\r?\n/).map((d,l)=>({content:d.trim(),number:l+1})).filter(d=>d.content.length>0);for(let d of c)try{let l=JSON.parse(d.content);if(typeof l!="object"||l===null||Array.isArray(l))throw new TypeError("history entry must be an object");a=l}catch{i.unparseable.push({id:n,path:s,line:d.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&r.has(n)&&i.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(i.repairReconciliations+=1))}function Xn(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function Zm(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},s;try{s=await Le.readdir(Pe.join(e,"history"))}catch{return n}for(let r of s.sort((i,o)=>i.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let i;try{i=await Le.readFile(Pe.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Xn("history stream",o)});continue}Qm({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},i)}return n}function Pa(e){let t=Ce(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function e_(e){let t=[],n=0,s=null;try{s=await j(O(e))}catch(i){n+=1,t.push({path:"settings.json",detail:Xn("configuration file",i)})}if(s!==null){n+=1;let i=Pa(s);i!==null&&t.push({path:"settings.json",detail:i})}let r;try{r=await Le.readdir(Pe.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let i of r.sort((o,a)=>o.localeCompare(a))){if(!i.endsWith(".json"))continue;n+=1;let o;try{o=await Le.readFile(Pe.join(e,"schema",i),"utf8")}catch(c){t.push({path:`schema/${i}`,detail:Xn("configuration file",c)});continue}let a=Pa(o);a!==null&&t.push({path:`schema/${i}`,detail:a})}return{scanned:n,unparseable:t}}async function Ma(e,t,n,s={}){let r=await Jm(e,n),i=new Set(r.map(u=>u.id)),o=new Map;for(let u of r){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((_,p)=>_.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Pe.join(e,u.relativePath);return kt(await Le.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:s.schema,extensionFieldNames:s.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await Zm(e,i),l=await e_(e);return{item_files_on_disk:r.length,item_ids_on_disk:i.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c4d45cf-6b97-5151-a325-db09d31962a7")}catch{}})();var t_=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Jn=new Set(["--pm-path","--path","--author"]),n_={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},s_=new Set(["-p","--package"]),r_=new Set(["-c","--call"]),Qn=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Zn=new Set(["-C","--prefix","--userconfig","--cache"]),Da=new Set(["--cwd"]),Fa=new Set(["--cwd"]),i_=new Set(["exec","x"]),ja=new Set(["run","run-script"]),$a=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Me(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function jt(e){let t=$t(e.split(" ").filter(i=>i.length>0));if(t.length===0)return null;let[n,...s]=t;if(tt(n)||nt(n))return s;if(n==="node"&&s[0]&&nt(s[0]))return s.slice(1);let r=n==="npx"||n==="bunx"?be(s):n==="pnpm"?Gt(s):n==="npm"?qt(s):null;return r&&(tt(r.command)||ts(r.command))?r.args:null}var es=(e,t="pm")=>{let n=t.trim().toLowerCase(),s=n.length;for(;s>0&&n[s-1]==="-";)s-=1;let r=n.slice(0,s);if(r.length===0)return[];let i=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of Me(i)){let c=jt(a),d=c?ns(c):null,l=d&&t_.has(d.subcommand)?a_(d.remaining,n_[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&o.add(l)}return[...o].sort((a,c)=>a.localeCompare(c))};function $t(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Ut(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Jn.has(n)){t+=2;continue}t+=1;continue}return n}}function tt(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function o_(e){let t=e.trim();if(!t.startsWith("@")){let r=t.indexOf("@");return r===-1?t:t.slice(0,r)}let n=t.indexOf("/");if(n===-1)return t;let s=t.indexOf("@",n+1);return s===-1?t:t.slice(0,s)}function ts(e){let t=o_(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function nt(e){return e==="dist/cli.js"||e==="./dist/cli.js"||e.endsWith("/dist/cli.js")}function be(e){let t=0;for(;t<e.length;){let s=e[t];if(s==="--"){t+=1;break}if(!s.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(s);if(r){let i=r[1];return i?{command:i,args:e.slice(t+1)}:null}if(r_.has(s)){t+=1;break}t+=s_.has(s)&&!s.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function ue(e,t){let n=0;for(;n<e.length;){let s=e[n];if(s==="--"){n+=1;continue}if(s.startsWith("-")){if(s.includes("=")){n+=1;continue}if(t.has(s)){n+=2;continue}n+=1;continue}return{subcommand:s,args:e.slice(n+1)}}return null}function Gt(e){let t=ue(e,Qn);return t?.subcommand!=="dlx"?null:be(t.args)}function qt(e){let t=ue(e,Zn);return!t||!i_.has(t.subcommand)?null:be(t.args)}function ns(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Jn.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function a_(e,t=new Set){for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="--")return e[n+1];if(!s.startsWith("-"))return s;!s.includes("=")&&(Jn.has(s)||t.has(s))&&(n+=1)}}import ds from"node:fs/promises";import{realpathSync as p_}from"node:fs";import{execFile as f_}from"node:child_process";import H from"node:path";import{promisify as g_}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]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var c_=["metadata","resolution"],ss=["metadata","resolution","estimates","lifecycle"],d_="completed";function rs(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Ua(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Ga(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let s=Ua(n.close_reason)??d_;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:s,command:`pm update ${n.id} --resolution ${rs(s)}`,gate:"resolution"})}return t}function qa(e){let t=[];for(let n of e){let s=Ua(n.resolution);s!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:s,command:`pm update ${n.id} --close-reason ${rs(s)}`,gate:"metadata"})}return t}function Ba(e,t){return e.map(n=>{let s=$r(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(s),command:`pm update ${n.id} --estimate ${s}`,gate:"estimates"}})}function Wa(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function za(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let s=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${s} ${n.item_id} --remove ${rs(n.path)}`})}return t}function Ha(e){let t=(e??[]).flatMap(s=>s.split(",")).map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new g(`--fix-scope values must not be empty. Supported values: ${ss.join(", ")}.`,f.USAGE);return new Set(c_)}let n=new Set;for(let s of t){let r=s.toLowerCase().replaceAll("-","_");if(ss.includes(r)){n.add(r);continue}throw new g(`Unknown --fix-scope value "${s}". Supported values: ${ss.join(", ")}.`,f.USAGE)}return n}function Va(e,t){let n=[],s=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?s.push(r):n.push(r);return{applicable:n,gated:s}}function st(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var l_=/^([A-Z][A-Z0-9]*-\d+)\b/;function u_(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=l_.exec(t);return n?n[1]:null}function Ka(e){return typeof e=="string"&&e.trim().length>0}function Ya(e){let t=new Map;for(let s of e){if(typeof s.title!="string"||Ka(s.duplicate_of))continue;let r=u_(s.title);if(r===null)continue;let i=t.get(r);i||(i=[],t.set(r,i)),i.some(o=>o.id===s.id)||i.push({id:s.id,title:s.title,parent:Ka(s.parent)?s.parent.trim():null})}let n=[];for(let[s,r]of t){if(r.length<2)continue;let i=new Set(r.map(c=>c.id.toLowerCase())),o=r.filter(c=>c.parent===null||!i.has(c.parent.toLowerCase()));if(o.length<2)continue;let a=[...o].sort((c,d)=>c.id.localeCompare(d.id));n.push({code:s,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return n.sort((s,r)=>s.code.localeCompare(r.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function Xa(e){let t=new Map;for(let s of e){let r=t.get(s.item_type);r||(r=new Map,t.set(s.item_type,r)),r.set(s.field,(r.get(s.field)??0)+1)}let n={};for(let s of[...t.keys()].sort((r,i)=>r.localeCompare(i))){let r=t.get(s),i={};for(let o of[...r.keys()].sort((a,c)=>a.localeCompare(c)))i[o]=r.get(o);n[s]=i}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var Ja=3;function Qa(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Za(e,t,n=Ja){let s=Number.isFinite(n)&&n>=1?Math.floor(n):Ja,r=new Map;for(let i of t){let o=Qa(i);if(o.length===0)continue;let a=r.get(o);a?a.push(i):r.set(o,[i])}return e.map(i=>{let o=(r.get(Qa(i))??[]).filter(a=>a!==i).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:i,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:i,classification:"moved",candidates:o.slice(0,s),candidates_truncated:o.length>s}})}function ec(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function m_(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function tc(e){return`${e.item_id} ${e.link_kind}`}function nc(e,t){let n=new Map;for(let s of e){let r=n.get(s.path);r?(r.classification=m_(r.classification,s.classification),r.owners.set(tc(s),s)):n.set(s.path,{classification:s.classification,owners:new Map([[tc(s),s]])})}return[...n.entries()].sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>({path:s,classification:r.classification,items:[...r.owners.values()].map(i=>{let o=t(i.item_id);return{id:i.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:i.link_kind}}).sort((i,o)=>{let a=i.id.localeCompare(o.id);return a!==0?a:i.field.localeCompare(o.field)})}))}function __(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function sc(e){let t=[];for(let n of e)for(let s of n.items)t.push(`${n.path}:${n.classification} owner=${s.id} status=${s.status} field=${s.field} title="${__(s.title)}"`);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]="f8048210-9e9f-585b-b0df-a34eca521cc3")}catch{}})();var h_=["src","tests","docs"],y_=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],b_=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),w_=["resolution","expected_result","actual_result"],v_=["default","tracked-all","tracked-all-strict"],rc=["core","strict","custom"],Wt=["off","warn","error"];var os=["author","acceptance_criteria","estimated_minutes","close_reason"],dc=[...os,"reviewer","risk","confidence","sprint","release"],ls=Array.from(new Set(dc)),k_={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"},T_={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},x_={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},S_={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},E_={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},C_=32*1024*1024,I_=1e4,lc=40,ae=5,A_=4096,R_=255,O_=g_(f_);function uc(e){let t={};for(let[n,s]of Object.entries(e))Array.isArray(s)||(t[n]=typeof s=="object"&&s!==null?uc(s):s);return t}function N_(e){return{...e,checks:e.checks.map(t=>({...t,details:uc(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function we(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function ic(e){return we(e).replace(/\/+$/,"")}function Q(e){let t=P(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Ht(e,t){return vt(e,t)??e}function rt(e,t){return t.terminal_statuses.has(Ht(e,t))}function me(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Bt(e,t){return e.length!==t.length?!1:e.every((n,s)=>n===t[s])}function L_(e){let t=me(Qs),n={blocked_reason:me(pt.blocked_reason),resolution:me(pt.resolution),actual_result:me(pt.actual_result)},s=me(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:me(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:me(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:me(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:s,stale_blocker_reason_pattern_source:Bt(s,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:Bt(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Bt(r.resolution,n.resolution)?"default":"settings",actual_result:Bt(r.actual_result,n.actual_result)?"default":"settings"}}}function mc(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(rc.includes(t))return t;throw new g(`Unknown --metadata-profile value "${e}". Supported values: ${rc.join(", ")}.`,f.USAGE)}function _c(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Wt.includes(t))return t;throw new g(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Wt.join(", ")}.`,f.USAGE)}function pc(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Wt.includes(t))return t;throw new g(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Wt.join(", ")}.`,f.USAGE)}function P_(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>k_[n]).filter(n=>n!==void 0).sort((n,s)=>n.localeCompare(s))}function M_(e,t,n){let s=P_(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...os],configured_custom_fields:s,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...dc],configured_custom_fields:s,fallback_to_core:!1,warnings:[]}:s.length>0?{profile:e,profile_source:t,required_fields:s,configured_custom_fields:s,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...os],configured_custom_fields:s,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var D_=new Set(["acceptance_criteria","estimated_minutes"]);function fc(e,t,n,s){return!s&&D_.has(t)&&rt(e.status,n)?!1:t==="author"?!P(e.author):t==="acceptance_criteria"?!P(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ht(e.status,n)===n.close_status&&!P(e.close_reason):t==="reviewer"?!P(e.reviewer):t==="risk"?!P(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!P(e.confidence):t==="sprint"?!P(e.sprint):!P(e.release)}function gc(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new g(`Unknown --scan-mode value "${e}". Supported values: ${v_.join(", ")}.`,f.USAGE)}function hc(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return H.resolve(t);let n=H.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return H.dirname(H.dirname(n));let r=H.resolve(process.cwd()),i=oc(n),o=oc(r),a=H.relative(i,o);return a.length===0||!a.startsWith("..")&&!H.isAbsolute(a)?n:r}function oc(e){try{return p_.native(e)}catch{return H.resolve(e)}}function yc(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function us(e,t,n){let s=t.length>0?H.join(e,t):e,r;try{r=await ds.readdir(s,{withFileTypes:!0})}catch(i){if(yc(i,["ENOENT"]))return;throw i}for(let i of r){if(i.name.startsWith("."))continue;let o=t.length>0?H.join(t,i.name):i.name;if(i.isDirectory()){if(b_.has(i.name))continue;await us(e,o,n);continue}i.isFile()&&n.push(we(o))}}async function as(e){let t=[];for(let n of h_)await us(e,n,t);for(let n of y_){let s=H.join(e,n);try{(await ds.stat(s)).isFile()&&t.push(we(n))}catch{}}return[...new Set(t)].sort((n,s)=>n.localeCompare(s))}async function bc(e){try{let{stdout:t}=await O_("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:C_,windowsHide:!0,timeout:I_}),n=t.split("\0").map(s=>we(s)).filter(s=>s.length>0);return[...new Set(n)].sort((s,r)=>s.localeCompare(r))}catch{return null}}function F_(e,t){let n=new Set,s=ic(Ys);s.length>0&&n.add(s);let r=ic(H.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((i,o)=>i.localeCompare(o))}function ac(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function j_(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let s=await bc(e);if(s)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:s,candidateTotal:s.length,candidateScanned:s.length};let r=await as(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await as(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function M(e,t=ae){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function _e(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=M(e,lc);return{values:n.values,truncated:n.truncated,total:e.length}}var $_={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},U_={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function G_(e){let t=e.missing_fields.map(n=>`${$_[n]} "${U_[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function wc(e,t){let n=e.details?.missing_resolution_remediation_hints,s=Array.isArray(n)&&n.length>0,r=s?n.filter(o=>typeof o=="string"):ya(t);if(r.length===0)return;let i=s&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...i?{fix_hints_truncated:!0}:{}}}function vc(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var q_="validate_metadata_duplicate_issue_codes";function kc(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:ae,s=e.slice(0,n);return{rows:s.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:s.length<e.length,warnings:[`${q_}:${e.length}`]}}function B_(){return Object.fromEntries(ls.map(e=>[e,[]]))}function W_(e,t,n){let s=B_();for(let r of e)for(let i of ls)fc(r,i,t,n)&&s[i].push(r.id);return s}function z_(e,t,n){let s=[...e.warnings];for(let r of e.required_fields){let i=t[r];i.length>0&&s.push(`${T_[r]}:${i.length}`)}return s.push(...n),s}function Tc(e,t){let n={};for(let s of e.required_fields){let r=t[s],i=r?r.length:0,o=x_[s];i>0&&o&&(n[o]=i)}return n}function xc(e,t,n){let s=[];for(let r of e.required_fields){let i=t[r];if(i)for(let o of i){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";s.push({item_type:c,field:r})}}return s}function H_(e,t,n,s){for(let r of t.required_fields){let i=n[r];if(!i||i.length===0)continue;let o=S_[r],a=E_[r];if(!o||!a)continue;let c=M(i,s?i.length:ae);e[o]=c.values,e[a]=c.truncated}}function Sc(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let s=t.close_reason;return s?s.map(r=>({id:r,resolution:P(n.get(r)?.resolution)})):[]}function Ec(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let s=t.estimated_minutes;return s?s.map(r=>({id:r,type:P(n.get(r)?.type)})):[]}function V_(e,t,n,s){let r=new Map(e.map(y=>[y.id,y])),i=t.profile==="strict",o=W_(e,n,i),a=Ya(e),c=kc(a,s),d=z_(t,o,c.warnings),l=Tc(t,o),u=xc(t,o,r),m=Xa(u),_={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...ls],counts:l,missing_by_type:m,duplicate_issue_codes_count:a.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(_.configured_custom_required_fields=[...t.configured_custom_fields]),H_(_,t,o,s);let p=Sc(t,o,r),h=Ec(t,o,r);return{check:{name:"metadata",status:d.length===0?"ok":"warn",details:_},warnings:d,closeReasonBackfillRows:p,estimateBackfillRows:h}}function K_(e,t,n){let s=new Set(t.terminal_done_statuses);s.add(t.close_status);let r=e.filter(m=>s.has(Ht(m.status,t))),i=[],o=[];for(let m of r){let _=w_.filter(p=>!P(m[p]));_.length!==0&&(i.push({id:m.id,missing_fields:_}),o.push({id:m.id,missing_fields:_,close_reason:P(m.close_reason)}))}let a=i.length>0?[`validate_resolution_missing_fields:${i.length}`]:[],c=n?Number.POSITIVE_INFINITY:ae,d=M(i.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=i.map(m=>G_(m)),u=M(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",details:{checked_closed_items:r.length,missing_resolution_items:i.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function Cc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ic(e,t="pm",n=_n()){let s=new Set(e.map(i=>i.id)),r=[...e].sort((i,o)=>i.id.localeCompare(o.id));return new Map(r.map(i=>{let o=new Set,a=Q(i.blocked_by);a&&s.has(a)&&o.add(a),(i.dependencies??[]).filter(d=>{let l=Q(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Q(d.id)).filter(d=>d!==void 0&&s.has(d)).forEach(d=>o.add(d));let c=Q(i.definition_of_ready);return Rc(c??"",t).filter(d=>s.has(d)).forEach(d=>o.add(d)),[i.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function Ac(e,t,n){let s=Uo(e,n?l=>rt(l,n):void 0),r=s.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),i=s.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:ae,a=M(r,o),c=M(i,o),d=M(s.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:r.length===0?"ok":"warn",details:{checked_items:e.length,dangling_reference_count:r.length+i.length,active_dangling_reference_count:r.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:i.length,legacy_closed_dangling_reference_count:s.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:s.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function Rc(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),s=new RegExp(`(?:^|[^a-z0-9-])(${Cc(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(s)].map(r=>r[1].toLowerCase()))].sort((r,i)=>r.localeCompare(i))}function ms(e){let t=0,n=new Map,s=new Map,r=[],i=new Set,o=[],a=l=>{n.set(l,t),s.set(l,t),t+=1,r.push(l),i.add(l);for(let m of e.get(l)??[])n.has(m)?i.has(m)&&s.set(l,Math.min(s.get(l),n.get(m))):(a(m),s.set(l,Math.min(s.get(l),s.get(m))));if(s.get(l)!==n.get(l))return;let u=[];for(;r.length>0;){let m=r.pop();if(i.delete(m),u.push(m),m===l)break}u.sort((m,_)=>m.localeCompare(_)),o.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return o.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function _s(e,t){let n=e[0];if(e.length===1)return[n,n];let s=new Set(e),r=[n],i=new Set([n]),o=a=>{let c=(t.get(a)??[]).filter(d=>s.has(d));for(let d of c){if(d===n&&r.length>1)return r.push(n),!0;if(!i.has(d)){if(i.add(d),r.push(d),o(d))return!0;r.pop(),i.delete(d)}}return!1};return o(n)?[...r]:[...e,n]}function Oc(e,t="pm"){let n=Ic(e,t),s=ms(n),r=[...new Set(s.flat())].sort((o,a)=>o.localeCompare(a)),i=s.map(o=>_s(o,n).join("->"));return{cycle_count:s.length,cycle_item_ids:r,cycle_sample_paths:i}}function Nc(e,t=_n()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),s=new Map(e.map(i=>[i.id,[]]));return[...e].sort((i,o)=>i.id.localeCompare(o.id)).forEach(i=>{let o=s.get(i.id),a=Q(i.parent),c=a?n.get(a.toLowerCase()):void 0;c&&o.push(c),(i.dependencies??[]).forEach(d=>{let l=t.resolve(d.kind);if(!l?.hierarchy)return;let u=n.get(d.id.toLowerCase());u&&(l.hierarchyDirection==="source_parent"?s.get(u).push(i.id):o.push(u))})}),s.forEach((i,o)=>{s.set(o,[...new Set(i)].sort((a,c)=>a.localeCompare(c)))}),s}function Lc(e){let t=Nc(e),n=ms(t),s=[...new Set(n.flat())].sort((i,o)=>i.localeCompare(o)),r=n.map(i=>_s(i,t).join("->"));return{cycle_count:n.length,cycle_item_ids:s,cycle_sample_paths:r}}function Pc(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function zt(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Mc(e,t){let n=zt(e).split("/").filter(Boolean),s=zt(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<s.length&&n[r]===s[r];)r+=1;return r}function Y_(e,t){let n=zt(t),s=zt(e),r=t.endsWith("/")?t:`${t}/`,i=e.startsWith(r),o=n.length>0&&n===s,a=Mc(e,t);return!i&&!o&&a===0?null:i?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function X_(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function J_(e,t,n){let s=t==="docs_unowned"?"docs":"files",r;return n.flatMap(i=>(s==="docs"?i.docs??[]:i.files??[]).map(o=>({item:i,link:o}))).forEach(({item:i,link:o})=>{if(o.scope!=="project")return;let a=we(o.path);if(a.length===0||a===e)return;let c=Y_(e,a);c!==null&&X_(r,i,c.score)&&(r={item:i,score:c.score,confidence:c.confidence})}),r?{id:r.item.id,type:r.item.type,title:r.item.title,status:r.item.status,confidence:r.confidence}:null}function Dc(e,t){return e.map(n=>{let s=Pc(n),r=s==="docs_unowned"?"docs":"files",i=J_(n,s,t),o=i?.id??"<id>";return{path:n,classification:s,owner_candidate:i,remediation_hint:`pm ${r} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Fc(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function Q_(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,s])=>{let r=Q(e[n]);return r?s.some(i=>r.toLowerCase().includes(i)):!1}).map(([n])=>n).sort((n,s)=>n.localeCompare(s))}function Z_(e,t,n,s,r){let i=Q(t.parent),o=i?n.get(s.get(i.toLowerCase())??i):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!rt(o.status,r)}}function ep(e,t,n,s){let r=Q(e.blocked_by),i=Q(e.blocked_reason),o=i?.toLowerCase(),a=Ht(e.status,n),c=[];return t.has(a)?(!r&&!i&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&s.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),i&&c.push("non_blocked_status_has_blocked_reason"),c)}function tp(e,t,n,s){let r=new Map(e.map(c=>[c.id,c])),i=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!rt(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=Q_(c,s);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=Q(c.parent),u=l?r.get(i.get(l.toLowerCase())??l):void 0;if(u&&rt(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(Z_(c,u,r,i,n))),t){let m=ep(c,o,n,s);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((_,p)=>_.localeCompare(p))})}}return a}function np(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function cc(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function sp(e,t,n,s,r,i){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=cc("validate_lifecycle_dependency_cycles",n,r),c=cc("validate_hierarchy_parent_cycle",s,i);return[...o,...a?[a]:[],...c?[c]:[]]}function jc(e){let t=we(e);return t.length>A_||t.split(/[\\/]/).some(n=>n.length>R_)}async function rp(e,t){let n=H.isAbsolute(t)?t:H.resolve(e,t);if(jc(n))return!1;try{let s=await ds.stat(n);return!s.isFile()&&!s.isDirectory()}catch(s){return yc(s,["ENOENT","ENOTDIR"])}}async function ip(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},s=e.flatMap(r=>[...(r.files??[]).map(i=>({item:r,artifact:i,link_kind:"files"})),...(r.docs??[]).map(i=>({item:r,artifact:i,link_kind:"docs"}))]);for(let{item:r,artifact:i,link_kind:o}of s){if(i.scope!=="project")continue;if(ea(i.path)){n.remoteLinkedPaths.add(i.path.trim());continue}let a=we(i.path);a.length!==0&&(n.linkedProjectPaths.add(a),await rp(t,i.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:r.id,path:a,link_kind:o})))}return n}function op(e,t,n,s,r,i){let o=s==="tracked-all-strict",a=o&&!r,c=r||o,d=c?[]:F_(t,n),l=d.length===0?[]:e.candidateFiles.filter(_=>ac(_,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(_=>!ac(_,d)),m={};if(l.length>0){let _=_e(l,i);m.pm_internals={count:l.length,paths:_.values,paths_truncated:_.truncated,paths_total:_.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function $c(e,t,n,s,r,i,o,a="pm"){let c=tp(e,t,r,i);np(c);let d=Oc(c.activeItems,a),l=Lc(e),u=sp(c,t,n,s,d.cycle_count,l.cycle_count),m=o?Number.POSITIVE_INFINITY:ae,_=M(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),m),p=M(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),m),h=M(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),m),y=M(d.cycle_item_ids,m),w=M(d.cycle_sample_paths,m),T=M(l.cycle_item_ids,m),C=M(l.cycle_sample_paths,m);return{check:{name:"lifecycle",status:d.cycle_count>0&&n==="error"||l.cycle_count>0&&s==="error"?"error":u.length===0?"ok":"warn",details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:_.values,active_closure_like_metadata_rows_truncated:_.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:p.values,active_terminal_parent_rows_truncated:p.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:h.values,stale_blocker_rows_truncated:h.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:y.values,dependency_cycle_item_ids_truncated:y.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:s,parent_cycle_count:l.cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:T.values,parent_cycle_item_ids_truncated:T.truncated,parent_cycle_sample_paths:C.values,parent_cycle_sample_paths_truncated:C.truncated,stale_blocker_reason_patterns:[...i.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:i.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...i.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:i.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...i.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:i.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...i.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:i.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function Uc(e,t,n,s,r,i){let o=await ip(e,t),a=new Map(e.map(S=>[S.id,S])),c=[...new Set(o.missingLinkedPaths)].sort((S,B)=>S.localeCompare(B)),d=await j_(t,s),l=op(d,n,t,s,r,i),u=l.candidateFiles.filter(S=>!o.linkedProjectPaths.has(S)),m=Dc(u,e),_=Za(c,l.candidateFiles),p=new Map(_.map(S=>[S.path,S.classification])),h=_.filter(S=>S.classification==="moved").length,y=o.staleLinkRows.map(S=>({...S,classification:p.get(S.path)??"deleted"})).sort((S,B)=>S.item_id.localeCompare(B.item_id)||S.path.localeCompare(B.path)||S.link_kind.localeCompare(B.link_kind)),w=[];l.strictModeForcesPmInternals&&w.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&w.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&w.push(`validate_files_orphaned_paths:${u.length}`);let T=[...o.remoteLinkedPaths].sort((S,B)=>S.localeCompare(B)),C=_e(T,i),k=_e(c,i),b=_e(u,i),R=_e(m.map(S=>`${S.path}:${S.classification}:owner_candidate=${S.owner_candidate?.id??"unowned"}`),i),q=i?m:_e(Fc(m),!1).values,D=_e(ec(_),i),$=y.map(S=>({item_id:S.item_id,path:S.path,link_kind:S.link_kind,classification:S.classification})),Y=nc($,S=>{let B=a.get(S);return B?{type:B.type,title:B.title,status:B.status}:void 0}),ce=i?Y:_e(sc(Y),!1).values;return{check:{name:"files",status:w.length===0?"ok":"warn",details:{workspace_root:t,scan_mode_requested:d.requestedMode,scan_mode_applied:d.appliedMode,strict_tracked_all_mode:l.strictTrackedAllMode,strict_mode_forces_pm_internals:l.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:l.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:i?"full":"summary",file_list_summary_limit:lc,candidate_scan_source:d.source,include_pm_internals:l.includePmInternalsEffective,include_pm_internals_requested:r,pm_internal_candidate_prefixes:l.pmInternalCandidatePrefixes,pm_internal_excluded_count:l.excludedPmInternalPaths.length,excluded_total:l.excludedPmInternalPaths.length,excluded_by_reason:l.excludedByReason,linked_project_paths:o.linkedProjectPaths.size,remote_linked_paths_count:T.length,remote_linked_paths_total:C.total,remote_linked_paths:C.values,remote_linked_paths_truncated:C.truncated,candidate_total_raw:d.candidateTotal,candidate_scanned_raw:d.candidateScanned,candidate_total:l.candidateFiles.length,candidate_scanned:l.candidateFiles.length,scanned_candidate_files:l.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:k.total,missing_linked_paths:k.values,missing_linked_paths_truncated:k.truncated,missing_linked_paths_moved_count:h,missing_linked_paths_deleted_count:c.length-h,missing_linked_path_classifications:D.values,missing_linked_path_classifications_truncated:D.truncated,missing_linked_path_rows_count:Y.length,missing_linked_path_rows:ce,orphaned_paths_count:u.length,orphaned_paths_total:b.total,orphaned_paths:b.values,orphaned_paths_truncated:b.truncated,orphaned_path_classifications:R.values,orphaned_path_classifications_truncated:R.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:q}},warnings:w,staleLinkPruneRows:y}}async function ap(e,t,n){let{missingStreams:s,unreadableStreams:r,hashMismatches:i,chainMismatches:o,driftedItems:a}=await It(e,t),c=[];s.length>0&&c.push(`validate_history_drift_missing_streams:${s.length}`),r.length>0&&c.push(`validate_history_drift_unreadable_streams:${r.length}`),i.length>0&&c.push(`validate_history_drift_hash_mismatches:${i.length}`),o.length>0&&c.push(`validate_history_drift_chain_mismatches:${o.length}`);let d=n?Number.POSITIVE_INFINITY:ae,l=M(a,d);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,drifted_items_count:a.length,drifted_items:l.values,drifted_items_truncated:l.truncated,counts:{missing_streams:s.length,unreadable_streams:r.length,hash_mismatches:i.length,chain_mismatches:o.length}}},warnings:c}}function cp(e,t,n){let s=n.trim().replaceAll(/\s+/g," "),r=s.length>120?`${s.slice(0,117)}...`:s;return`${e}:${t}:${r}`}function Gc(e,t,n){let s=new Set(e.map(y=>y.id.toLowerCase())),r=0,i=0,o=new Set,a=[],c=e.flatMap(y=>(y.tests??[]).map(w=>({item:y,linkedTest:w})));for(let{item:y,linkedTest:w}of c){if(typeof w.command!="string"||w.command.trim().length===0)continue;r+=1;let T=es(w.command,t);if(T.length!==0){i+=T.length;for(let C of T)o.add(C),s.has(C.toLowerCase())||a.push(cp(y.id,C,w.command))}}let d=[...new Set(a)].sort((y,w)=>y.localeCompare(w)),l=[...new Set(d.map(y=>y.split(":")[1]??""))].filter(y=>y.length>0).sort((y,w)=>y.localeCompare(w)),u=d.length>0?[`validate_command_references_stale_pm_ids:${d.length}`]:[],m=n?Number.POSITIVE_INFINITY:ae,_=M(d,m),p=M(l,m),h=M([...o].sort((y,w)=>y.localeCompare(w)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",details:{checked_items:e.length,linked_commands_scanned:r,referenced_pm_ids_count:i,unique_referenced_pm_ids_count:o.size,unique_referenced_pm_ids:h.values,unique_referenced_pm_ids_truncated:h.truncated,stale_pm_id_references_count:d.length,stale_pm_ids_count:l.length,stale_pm_ids:p.values,stale_pm_ids_truncated:p.truncated,stale_pm_id_reference_rows:_.values,stale_pm_id_reference_rows_truncated:_.truncated}},warnings:u}}function dp(e,t){let n=wt(e.map(c=>({ref:c.id,version:bt(c)}))),s=[];n.outdated.length>0&&s.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&s.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:ae,i=M(n.outdated,r),o=M(n.ahead,r);return{check:{name:"format_version",status:n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok",details:{checked_items:e.length,current_format_version:vr,outdated_items_count:n.outdated.length,outdated_items:i.values,outdated_items_truncated:i.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:s}}var cs="pm validate auto-fix";async function qc(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let s={message:cs};if(e.kind==="set_resolution"?s.resolution=e.value:e.kind==="set_close_reason"?s.closeReason=e.value:e.kind==="set_estimate"?s.estimatedMinutes=e.value:e.kind==="reparent"?s.parent=e.parent_id:s.unset=["parent"],!n.runUpdate)throw new g("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",f.USAGE);await n.runUpdate(e.item_id,s,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function is(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Bc(e,t,n){let s=[],r=[],i=new Map;for(let o of e.filter(a=>is(a)===null))try{await qc(o,t,n),s.push(o)}catch(a){r.push({fix:o,error:a})}for(let o of e.filter(a=>is(a)!==null)){let a=is(o),c=i.get(a);c?c.push(o):i.set(a,[o])}for(let o of i.values()){let a=o[0];if(!a)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await na(a.item_id,{remove:c,message:cs},t):await ta(a.item_id,{remove:c,message:cs},t),s.push(...o)}catch(d){r.push(...o.map(l=>({fix:l,error:d})))}}return{applied:s,failed:r}}var pT={applyValidateFix:qc,applyValidateFixes:Bc,attachValidateFixHints:wc,buildCommandReferencesCheck:Gc,buildDependencyReferencesCheck:Ac,buildCloseReasonBackfillRows:Sc,buildFilesCheck:Uc,buildLifecycleCheck:$c,buildLifecycleDependencyGraph:Ic,buildLifecycleParentGraph:Nc,buildEstimateBackfillRows:Ec,buildMetadataCounts:Tc,buildMissingFieldOccurrences:xc,buildOrphanedPathRows:Dc,classifyOrphanedPath:Pc,collectDefaultProjectFileCandidates:as,collectTrackedGitFileCandidates:bc,detectLifecycleDependencyCycles:Oc,detectLifecycleParentCycles:Lc,escapeRegExp:Cc,extractItemIds:Rc,findLifecycleDependencyCycleComponents:ms,isMetadataFieldMissing:fc,linkedArtifactPathExceedsFilesystemLimits:jc,listFilesRecursive:us,resolveDependencyCycleSeverity:_c,resolveParentCycleSeverity:pc,resolveFileScanMode:gc,resolveLifecycleDependencyCycleSamplePath:_s,resolveRequestedChecks:vc,resolveValidateMetadataProfile:mc,resolveWorkspaceRoot:hc,sharedDirectoryPrefixLength:Mc,summarizeOrphanedPathRows:Fc,summarizeDuplicateIssueCodes:kc,toMeaningfulString:Q};async function lp(e,t,n,s){let r=await Ma(e,new Set(t.map(m=>m.id)),n,{schema:s.schema,extensionFieldNames:yt(W())}),i=[];r.unreadable_item_files.length>0&&i.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&i.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&i.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&i.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&i.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&i.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let o=i.length,a=await Mt(e);a.tracked_path_count>0&&i.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Jo(e,Xo(s));c.status==="drift"&&i.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Ae(e),l=d===null?null:await Ct(d);l!==null&&l.status!=="ok"&&i.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=d===null?[]:await Ze(d);return u.length>0&&i.push(`validate_merge_decisions_unreviewed:${u.length}`),{check:{name:"storage_integrity",status:o>0?"error":i.length>0?"warn":"ok",details:{...r,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:u.length,pending_merge_decision_items:[...new Set(u.map(m=>m.item_id))].sort((m,_)=>m.localeCompare(_)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:i}}function oe(e,t,n){n&&wc(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function up(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,s=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let r=V_(e.items,e.metadataPolicy,e.statusRegistry,s);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows,oe(t,r,n)}if(e.requestedChecks.has("resolution")){let r=K_(e.items,e.statusRegistry,s);t.resolutionBackfillRows=r.resolutionBackfillRows,oe(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=$c(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,s,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,oe(t,r,n),oe(t,Ac(e.items,s,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await Uc(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=r.staleLinkPruneRows,oe(t,r,n)}return e.requestedChecks.has("command_references")&&oe(t,Gc(e.items,e.settings.id_prefix,s),n),e.requestedChecks.has("history_drift")&&oe(t,await ap(e.pmRoot,e.items,s),n),e.requestedChecks.has("format_version")&&oe(t,dp(e.items,s),n),e.requestedChecks.has("storage_integrity")&&oe(t,await lp(e.pmRoot,e.items,V(e.settings,W()).type_to_folder,e.settings),n),t}function mp(e,t,n){let s=[];return e.autoFix===!0&&(s.push(...qa(t.closeReasonBackfillRows)),s.push(...Ga(t.resolutionBackfillRows)),s.push(...Ba(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),s.push(...Wa(t.terminalParentFixRows))),e.pruneMissing===!0&&s.push(...za(t.staleLinkPruneRows)),s}async function _p(e,t,n,s,r,i){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=mp(e,t,n),{applicable:a,gated:c}=Va(o,s),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await Bc(a,r,i);l.push(...m.applied.map(st)),u.push(...m.failed.map(({fix:_,error:p})=>({...st(_),error:p instanceof Error?p.message:String(p)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...s].sort((m,_)=>m.localeCompare(_)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(st),applied_fixes:l,gated_fixes:c.map(m=>({...st(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function fT(e,t,n={}){Sr(e.counts===!0,e.full===!0,"--counts");let s=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!s)throw new g("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",f.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new g("--fix-scope requires --auto-fix.",f.USAGE);let r=Ha(e.fixScope),i=I(process.cwd(),t.path);if(!await x(O(i)))throw new g(`Tracker is not initialized at ${i}. Run pm init first.`,f.NOT_FOUND);let o=await N(i),a=ee(o.schema),c=V(o,W()),d=[],l=await Ie(i,o.item_format,c.type_to_folder,d,o.schema),u=vc(e);if(u.has("history_drift")){let $=await Je(i);$.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${$.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",_=mc(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),p=M_(_,m,o.validation.metadata_required_fields),h=L_(o),y=_c(e.dependencyCycleSeverity),w=pc(e.parentCycleSeverity),T=gc(e.scanMode),C=hc(i),k=await up({requestedChecks:u,options:e,global:t,pmRoot:i,workspaceRoot:C,settings:o,items:l,statusRegistry:a,metadataPolicy:p,lifecyclePatternPolicy:h,dependencyCycleSeverity:y,parentCycleSeverity:w,fileScanMode:T,initialWarnings:[...new Set(d)]}),b=s?await _p(e,k,o,r,t,n):void 0,R=[...new Set(k.warnings)].sort(($,Y)=>$.localeCompare(Y)),D={ok:!k.checks.some($=>$.status==="error"),has_warnings:R.length>0,checks:k.checks,warnings:R,...b!==void 0?{fixes:b}:{},generated_at:v(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?D:{...N_(D),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32223457-5f57-5049-99cf-c5d766413fb6")}catch{}})();var pp="1h",fp="now",gp="+1d";function pe(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Wc(e,t,n){return{type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message}}async function zc(e,t,n,s){let r=Wc(e,t,n),i=[];return pe(i,"start",n.start??fp),n.end!==void 0?pe(i,"end",n.end):pe(i,"duration",n.duration??pp),pe(i,"location",n.location),pe(i,"timezone",n.timezone),n.allDay===!0&&pe(i,"all_day","true"),r.event=[i.join(",")],Nn(r,s)}function yT(e,t,n){return zc("Meeting",e,t,n)}function bT(e,t,n){return zc("Event",e,t,n)}function wT(e,t,n){let s=Wc("Reminder",e,t),r=[];return pe(r,"at",t.at??gp),pe(r,"text",t.text??e),s.reminder=[r.join(",")],Nn(s,n)}import ot from"node:crypto";import{cp as Hc,lstat as hp,mkdir as ve,readFile as De,readdir as ps,rename as Yc,rm as gs,writeFile as Vt}from"node:fs/promises";import E 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]="3e32be7c-f8a4-547d-8c19-456b4567982e")}catch{}})();var Xc="https://schema.unbrained.dev/pm/workspace-snapshot/v1",Jc=E.join("runtime","workspace-snapshots"),yp=new Set(["checkpoints","locks","runtime","search","transactions"]),bp=/^[a-z0-9][a-z0-9._-]*$/,it="sdk-workspace-transaction",Qc={renameEntry:Yc,removeEntry:async e=>{await gs(e,{recursive:!0,force:!0})}},fs=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,s){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(s*1e3/3))}start(){this.timer=setInterval(()=>{this.refresh===void 0&&(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))},this.intervalMs),this.timer.unref()}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()}async renew(){let t=JSON.parse(await De(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==it||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await se(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
5
- `)}};async function Zc(e,t=""){let n=await ps(E.join(e,t),{withFileTypes:!0}),s=[];for(let r of n.sort((i,o)=>i.name.localeCompare(o.name))){if(t.length===0&&yp.has(r.name))continue;let i=E.posix.join(t.replaceAll(E.sep,"/"),r.name);if(r.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${i}`);if(r.isDirectory())s.push(...await Zc(e,i));else if(r.isFile())s.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return s}async function ed(e){let t=await Zc(e),n=ot.createHash("sha256"),s=[],r=0;for(let o of t){let a=await De(E.join(e,o));s.push(a),r+=a.byteLength,n.update(o),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let i=n.digest("hex");return{manifest:{schema:Xc,fingerprint:i,files:t,bytes:r},contents:s}}function Vc(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
6
- `).filter(t=>t.trim().length>0).length}async function wp(e,t){let n=new Map;for(let s=0;s<t.length;s+=32){let r=t.slice(s,s+32),i=await Promise.all(r.map(async o=>[o,await De(E.join(e,o))]));for(let[o,a]of i)n.set(o,a)}return n}function hs(e){if(!bp.test(e))throw new g("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",f.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"}})}function td(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function ke(e){return E.join(e,Jc)}function nd(e){return new g(`Unknown workspace snapshot: ${e}`,f.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 sd(e,t){try{return JSON.parse(await De(e,"utf8"))}catch(n){throw td(n,"ENOENT")?nd(t):n}}async function Kc(e,t,n){try{await gs(e,{recursive:n})}catch(s){throw td(s,"ENOENT")?nd(t):s}}async function vp(e,t,n=Qc){try{return await n.renameEntry(e,t),!1}catch(s){if(!(s instanceof Error&&"code"in s&&(s.code==="EEXIST"||s.code==="ENOTEMPTY")))throw s;return await n.removeEntry(e),!0}}async function kp(e,t,n,s,r){await s.renameEntry(t,n);try{await s.renameEntry(e,t),await r?.()}catch(i){throw await s.renameEntry(n,t),await s.removeEntry(e),i}await s.removeEntry(n)}async function Tp(e,t){return hs(t),/^[a-f0-9]{64}$/.test(t)?t:(await sd(E.join(ke(e),"refs",`${t}.json`),t)).fingerprint}async function xp(e,t={}){if(t.name!==void 0&&(hs(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new g("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",f.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:s}=await ed(e),r=ke(e),i=E.join(r,"objects",n.fingerprint),o=!1;try{o=(await hp(i)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="ENOENT"))throw a}if(!o){let a=E.join(r,"objects",`.create-${process.pid}-${ot.randomUUID()}`);await ve(E.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let l=E.join(a,"files",d);await ve(E.dirname(l),{recursive:!0}),await Vt(l,s[c])}await Vt(E.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
7
- `,"utf8"),await ve(E.dirname(i),{recursive:!0}),o=await vp(a,i)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=E.join(r,"refs");await ve(c,{recursive:!0});let d=E.join(c,`.ref-${process.pid}-${ot.randomUUID()}`);await Vt(d,`${JSON.stringify(a,null,2)}
8
- `,"utf8"),await Yc(d,E.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:o}}async function ys(e,t){let n=await Tp(e,t),s=await sd(E.join(ke(e),"objects",n,"manifest.json"),t);if(s.schema!==Xc||s.fingerprint!==n)throw new g(`Snapshot manifest identity mismatch: ${t}`,f.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 s}async function Sp(e){let t=ke(e),n=await ps(E.join(t,"objects")).catch(r=>{if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return[];throw r}),s=await ps(E.join(t,"refs")).catch(r=>{if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return[];throw r});return{objects:await Promise.all(n.filter(r=>/^[a-f0-9]{64}$/.test(r)).sort().map(r=>ys(e,r))),references:await Promise.all(s.filter(r=>r.endsWith(".json")).sort().map(async r=>JSON.parse(await De(E.join(t,"refs",r),"utf8"))))}}async function Ep(e,t){let n=await ys(e,t),{manifest:s,contents:r}=await ed(e),i=new Map(s.files.map((u,m)=>[u,r[m]])),o=await wp(E.join(ke(e),"objects",n.fingerprint,"files"),n.files),a=new Set(s.files),c=new Set(n.files),d=new Set([...a,...c]);for(let u of d){let m=i.get(u),_=o.get(u);m!==void 0&&_!==void 0&&m.equals(_)&&d.delete(u)}let l=s.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let m=Vc(i.get(u)),_=Vc(o.get(u));return{path:u,current_entries:m,target_entries:_,removed_entries:Math.max(0,m-_)}}).filter(u=>u.removed_entries>0).sort((u,m)=>u.path.localeCompare(m.path));return{target_fingerprint:n.fingerprint,current_fingerprint:s.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!a.has(u)).length,removed_item_count:[...a].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:l.length,removed_history_entry_count:l.reduce((u,m)=>u+m.removed_entries,0),affected_history_streams:l,changes_authoritative_state:s.fingerprint!==n.fingerprint}}async function Cp(e,t,n={}){if(n.force!==!0)throw new g("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",f.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 s=n.author?.trim()||"pm-sdk",r=n.lockTtlSeconds??60,i=n.lockWaitMs??5e3,o=await Dr(e,it,r,s,!1,!1,i),a=new fs(ft(e,it),s,r);a.start();let c,d=!1,l=!1;try{let u=await Ep(e,t),m=await ys(e,t),_=await xp(e),p=m.fingerprint,h=ke(e),y=E.join(h,"objects",p,"files"),w=E.dirname(e),T=E.basename(e);c=E.join(w,`.${T}.restore-${ot.randomUUID()}`);let C=E.join(w,`.${T}.backup-${ot.randomUUID()}`);await ve(c,{recursive:!0}),await Hc(y,c,{recursive:!0,force:!1}),await ve(E.join(c,"runtime"),{recursive:!0}),await Hc(h,E.join(c,Jc),{recursive:!0,force:!1});let k=await xt({pmRoot:c,op:"workspace_snapshot_restore",author:s,message:n.message??`Restore workspace snapshot ${p}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:p,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:u.changed_file_count,removed_file_count:u.removed_file_count,removed_item_count:u.removed_item_count,affected_history_stream_count:u.affected_history_stream_count,removed_history_entry_count:u.removed_history_entry_count},lockTtlSeconds:r,lockWaitMs:i}),b=E.relative(c,k.historyPath).replaceAll("\\","/");await a.stop(),l=!0;let R=ft(c,it);return await ve(E.dirname(R),{recursive:!0}),await Vt(R,await De(ft(e,it)),{flag:"wx"}),d=!0,await kp(c,e,C,Qc,async()=>{a.start(),l=!1}),await a.stop(),l=!0,{manifest:m,plan:u,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:b,audit_operation:"workspace_snapshot_restore"}}catch(u){throw c!==void 0&&!d&&await Promise.allSettled([gs(c,{recursive:!0,force:!0})]),u}finally{try{l||await a.stop()}catch{}finally{await o()}}}async function OT(e,t){return(await Cp(e,t,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function NT(e,t){hs(t);let n=ke(e);if(!/^[a-f0-9]{64}$/.test(t))return await Kc(E.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:s}=await Sp(e);if(s.some(r=>r.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Kc(E.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]="3b72f4a5-9e0b-5f8e-8ee9-e45cd83d6f92")}catch{}})();var Ip=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),Ap=new Set(["--add","--body","--comment","--dep","--description","--doc","--field","--file","--learning","--note","--remove","--test","--type-option"]),Rp=new Set(["append","comments","create","docs","files","learnings","notes","test","update"]),Op=["--allow-","--check-","--dry-run","--explain","--filter-","--full","--has-","--include-","--json","--no-","--only","--quiet","--require-","--runtime-only","--schema-only","--stream","--strict-","--summary","--today","--verbose"];function Np(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:t.endsWith("-file")?["argv","file"]:Ap.has(t)&&Rp.has(e)?["argv","stdin"]:["argv"]}function Lp(e){let t=e.value_name!==void 0||e.value_type==="string"||e.value_type==="number"||e.list===!0||e.repeatable===!0,n=e.flag==="--stdin"||e.flag==="--stdin-json"||Op.some(s=>e.flag.startsWith(s));return t||!n}function Pp(e,t){let n=Lp(t),s=Np(e,t.flag),r=t.description??Ip[t.flag]??`${n?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:r,takes_value:n,value_required:n,...n?{value_name:t.value_name??"value"}:{},value_type:n?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:s,...s.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{}}}function rd(e,t){return t.map(n=>Pp(e,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]="6fc2cd04-2fe4-5a0e-944d-fab0f86509e2")}catch{}})();var Mp=new Set(["claim","close","context","create","get","help","list","next","plan","release","search","update","validate"]),Dp=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),bs=Object.freeze([...he.map(e=>({command:e,tier:Mp.has(e)?"core":Dp.has(e)?"standard":"full"})),{command:"completion-statuses",tier:"internal"},{command:"completion-tags",tier:"internal"},{command:"completion-types",tier:"internal"},{command:"test-runs-worker",tier:"internal"}]),id={core:0,standard:1,full:2,internal:3},Fp=new Map(bs.map(({command:e,tier:t})=>[e,t]));function od(e,t="standard"){return Fp.get(e.trim().toLowerCase())??t}function jp(e){let t=id[e];return bs.filter(n=>n.tier!=="internal"&&id[n.tier]<=t).map(n=>n.command)}var $p=Object.freeze({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:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function DT(e,t){if(t==="full")return[...e];let n=new Set(jp(t));return e.filter(s=>{let r=$p[s];return r!==void 0&&n.has(r)})}var FT=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),jT=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function $T(){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_VISIBILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier |","| --- | --- |",...bs.map(({command:t,tier:n})=>`| \`${t}\` | ${n} |`),""].join(`
9
- `)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="479dd590-7f54-54ae-bbaf-8f183fd6b6b4")}catch{}})();var Up=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],Gp=new Map(Up.map(e=>[e.exit_code,e.class]));function ad(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function cd(e){let t=new Set,n=e.map(s=>{let r=s.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(r))throw new TypeError(`Invalid pm error code: ${JSON.stringify(s.code)}`);if(t.has(r))throw new TypeError(`Duplicate pm error code: ${r}`);t.add(r);let i=ad(s.sources),o=ad(s.emitting_commands);if(![1,2,3,4,5].includes(s.exit_code)||s.meaning.trim().length===0||s.recovery.trim().length===0||i.length===0||o.length===0||Gp.get(s.exit_code)!==s.class)throw new TypeError(`Invalid pm error code contract: ${r}`);return Object.freeze({...s,code:r,meaning:s.meaning.trim(),recovery:s.recovery.trim(),sources:i,emitting_commands:o})});return Object.freeze(n.sort((s,r)=>s.code.localeCompare(r.code)))}function GT(e,t){let n=e.trim(),s=t.find(r=>r.code===n);if(!s)throw new TypeError(`Unknown pm error code "${n}"`);return 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]="93c784d2-8f0f-5bf4-875e-3d83a675c9eb")}catch{}})();var dd=cd([{code:"acceptance_criteria_semicolon_forbidden",meaning:"Acceptance criteria semicolon forbidden condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"]},{code:"already_claimed_by",meaning:"Already claimed by condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"ambiguous_list_all",meaning:"Ambiguous list all condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-list-query.ts"],emitting_commands:["*"]},{code:"ambiguous_option_combination",meaning:"Ambiguous option combination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"annotation_flag_like_value",meaning:"Annotation flag like value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"]},{code:"annotation_message_without_text",meaning:"Annotation message without text condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"]},{code:"append_empty_body",meaning:"Append empty body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"]},{code:"body_file_conflicts_with_body",meaning:"Body file conflicts with body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"]},{code:"body_file_missing_path",meaning:"Body file missing path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"]},{code:"body_file_unreadable",meaning:"Body file unreadable condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"]},{code:"bundle_integrity_torn_install",meaning:"Bundle integrity torn install condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/bundle-integrity.ts"],emitting_commands:["*"]},{code:"capability_undeclared",meaning:"Capability undeclared condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"capability_unused",meaning:"Capability unused condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"child_projection_item_bound_exceeded",meaning:"Child projection item bound exceeded condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-children.ts"],emitting_commands:["*"]},{code:"close_reason_required",meaning:"Close reason required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"]},{code:"close_through_update",meaning:"Close through update condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"close_validation_missing_fields",meaning:"Close validation missing fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"collected_zero_items",meaning:"Collected zero items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"command_failed",meaning:"Command failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"command_namespace",meaning:"Command namespace condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"]},{code:"command_override_conflict",meaning:"Command override conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"config_duplicate",meaning:"Config duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"config_key_unknown",meaning:"Config key unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"config_value_invalid",meaning:"Config value invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"conflicting_lifecycle_owner",meaning:"Conflicting lifecycle owner condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-operations.ts"],emitting_commands:["*"]},{code:"context_takes_no_item_argument",meaning:"Context takes no item argument condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"core_item_field_requires_dedicated_flag",meaning:"Core item field requires dedicated flag condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"create_positional_type_without_title",meaning:"Create positional type without title condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts"],emitting_commands:["*"]},{code:"dependency_edge_not_allowed",meaning:"Dependency edge not allowed condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"]},{code:"duplicate_command",meaning:"Duplicate command condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"duplicate_edge",meaning:"Duplicate edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"]},{code:"duplicate_sweep_cost_limit",meaning:"Duplicate sweep cost limit condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/similarity.ts"],emitting_commands:["*"]},{code:"duplicate_target_circular",meaning:"Duplicate target circular condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_is_duplicate",meaning:"Duplicate target is duplicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_missing",meaning:"Duplicate target missing condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_self",meaning:"Duplicate target self condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"empty_surface",meaning:"Empty surface condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"event_cursor_query_mismatch",meaning:"Event cursor query mismatch condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"event_index_unavailable",meaning:"Event index unavailable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"extension_command_activation_failed",meaning:"Extension command activation failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/commander-usage.ts"],emitting_commands:["*"]},{code:"extension_dependency_name_unsafe",meaning:"Extension dependency name unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"extension_dependency_spec_invalid",meaning:"Extension dependency spec invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"extension_dependency_version_unsafe",meaning:"Extension dependency version unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"extension_install_soft_failed",meaning:"Extension install soft failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"]},{code:"extension_install_source_contains_destination",meaning:"Extension install source contains destination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-runtime.ts"],emitting_commands:["*"]},{code:"extension_item_field_reserved",meaning:"Extension item field reserved condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"extension_item_field_type_conflict",meaning:"Extension item field type conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"extension_item_field_unknown",meaning:"Extension item field unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_failed",meaning:"Extension mutation guard failed condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_invalid_decision",meaning:"Extension mutation guard invalid decision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_invalid_denial",meaning:"Extension mutation guard invalid denial condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_timed_out",meaning:"Extension mutation guard timed out condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_update_health_partial_coverage",meaning:"Extension update health partial coverage condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"field_duplicate",meaning:"Field duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"field_invalid",meaning:"Field invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"field_mcp_input_collision",meaning:"Field mcp input collision condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"github_source_entry_unbuilt",meaning:"Github source entry unbuilt condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/shared.ts"],emitting_commands:["*"]},{code:"history_author_acknowledge_selector_required",meaning:"History author acknowledge selector required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-history-author.ts"],emitting_commands:["*"]},{code:"history_drift_chain_mismatch",meaning:"History drift chain mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_drift_hash_mismatch",meaning:"History drift hash mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_drift_missing_stream",meaning:"History drift missing stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_drift_unreadable_stream",meaning:"History drift unreadable stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_merge_conflict_markers_detected",meaning:"History merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"]},{code:"history_stream_over_compact_threshold",meaning:"History stream over compact threshold condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_target_out_of_range",meaning:"History target out of range condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"]},{code:"history_unknown_author_events",meaning:"History unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"improvement_metric_contract_conflict",meaning:"Improvement metric contract conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"]},{code:"improvement_observation_conflict",meaning:"Improvement observation conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"]},{code:"init_existing_settings_requires_force",meaning:"Init existing settings requires force condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"init_gitignore_unwritable",meaning:"Init gitignore unwritable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace.ts"],emitting_commands:["*"]},{code:"init_id_prefix_conflict",meaning:"Init id prefix conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"init_id_prefix_path_like",meaning:"Init id prefix path like condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"integrity_history_conflict_marker",meaning:"Integrity history conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_history_invalid_json",meaning:"Integrity history invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_history_unreadable",meaning:"Integrity history unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_ahead_format_version",meaning:"Integrity item ahead format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_conflict_marker",meaning:"Integrity item conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_outdated_format_version",meaning:"Integrity item outdated format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_parse_failed",meaning:"Integrity item parse failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_unreadable",meaning:"Integrity item unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"invalid_argument_value",meaning:"Invalid argument value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts"],emitting_commands:["*","create"]},{code:"invalid_command_usage",meaning:"Invalid command usage condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"invalid_event_cursor",meaning:"Invalid event cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_event_follow_interval",meaning:"Invalid event follow interval condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_event_limit",meaning:"Invalid event limit condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_event_since",meaning:"Invalid event since condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_history_analytics_limit",meaning:"Invalid history analytics limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"]},{code:"invalid_history_analytics_minimum_sample",meaning:"Invalid history analytics minimum sample condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"]},{code:"invalid_history_analytics_since",meaning:"Invalid history analytics since condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"]},{code:"invalid_improvement_ledger",meaning:"Invalid improvement ledger condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger-validation.ts"],emitting_commands:["*"]},{code:"invalid_improvement_metric",meaning:"Invalid improvement metric condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"]},{code:"invalid_improvement_observation",meaning:"Invalid improvement observation condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"]},{code:"invalid_improvement_observation_limit",meaning:"Invalid improvement observation limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"]},{code:"invalid_improvement_observation_timestamp",meaning:"Invalid improvement observation timestamp condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"]},{code:"invalid_provenance_predicate",meaning:"Invalid provenance predicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"]},{code:"invalid_query_cursor",meaning:"Invalid query cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/pagination.ts"],emitting_commands:["*"]},{code:"invalid_read_output_session",meaning:"Invalid read output session condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output-session.ts"],emitting_commands:["*"]},{code:"invalid_workspace_snapshot_target",meaning:"Invalid workspace snapshot target condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"item_document_invalid",meaning:"Item document invalid condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"]},{code:"item_document_roundtrip_failed",meaning:"Item document roundtrip failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"]},{code:"item_id_collision",meaning:"Item id collision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"]},{code:"item_not_found",meaning:"Item not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"likely_duplicate",meaning:"Likely duplicate condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/similarity.ts"],emitting_commands:["*"]},{code:"linked_test_value_not_quoted",meaning:"Linked test value not quoted condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"list_source_incomplete",meaning:"List source incomplete condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/list.ts"],emitting_commands:["list"]},{code:"local_package_archive_unsafe",meaning:"Local package archive unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"local_source_not_found_bare_name",meaning:"Local source not found bare name condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"lock_conflict",meaning:"Lock conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"locks_stale_count",meaning:"Locks stale count condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"locks_unreadable",meaning:"Locks unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"malformed_plan_step_evidence",meaning:"Malformed plan step evidence condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"manifest_capabilities_absent",meaning:"Manifest capabilities absent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"merge_conflict_markers_detected",meaning:"Merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"]},{code:"merge_git_config_unwritable",meaning:"Merge git config unwritable condition.",stability:"stable",exit_code:5,class:"dependency_failed",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"]},{code:"merge_root_not_found",meaning:"Merge root not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"]},{code:"missing_directory",meaning:"Missing directory condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"missing_lifecycle_target",meaning:"Missing lifecycle target condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension.ts"],emitting_commands:["*"]},{code:"missing_required_argument",meaning:"Missing required argument condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","core/telemetry/observability.ts","sdk/history-redact.ts","sdk/invocation-author.ts"],emitting_commands:["*"]},{code:"missing_required_option",meaning:"Missing required option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"]},{code:"module_import_failed",meaning:"Module import failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"multi_target_github_install_ambiguous",meaning:"Multi target github install ambiguous condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"]},{code:"mutation_author_required",meaning:"Mutation author required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"]},{code:"mutation_secret_guard_blocked",meaning:"Mutation secret guard blocked condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"]},{code:"no_matching_tests",meaning:"No matching tests condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_projects_matched_filters",meaning:"No projects matched filters condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_test_files_found",meaning:"No test files found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_tests_found",meaning:"No tests found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_update_fields",meaning:"No update fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"npm_package_not_found",meaning:"Npm package not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"ownership_conflict",meaning:"Ownership conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"],emitting_commands:["*"]},{code:"ownership_dependency_bypass_restricted_options",meaning:"Ownership dependency bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"ownership_metadata_bypass_restricted_options",meaning:"Ownership metadata bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"package_spec_empty",meaning:"Package spec empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_name_empty",meaning:"Profile name empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_name_not_normalized",meaning:"Profile name not normalized condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_summary_empty",meaning:"Profile summary empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_title_empty",meaning:"Profile title empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"redundant_edge",meaning:"Redundant edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"]},{code:"reindex_already_running",meaning:"Reindex already running condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/reindex.ts"],emitting_commands:["*"]},{code:"reserved_item_field",meaning:"Reserved item field condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"schema_migration_input_required",meaning:"Schema migration input required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/migration-gates.ts"],emitting_commands:["*"]},{code:"settings_read_fs_error",meaning:"Settings read fs error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"settings_read_invalid_json",meaning:"Settings read invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"settings_read_invalid_schema",meaning:"Settings read invalid schema condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"settings_read_merge_failed",meaning:"Settings read merge failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"status_duplicate",meaning:"Status duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"status_invalid",meaning:"Status invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"stdin_json_invalid",meaning:"Stdin json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"]},{code:"stdin_json_unknown_key",meaning:"Stdin json unknown key condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"]},{code:"structured_event_immutable",meaning:"Structured event immutable condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"]},{code:"structured_event_input_conflict",meaning:"Structured event input conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"structured_event_json_empty",meaning:"Structured event json empty condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"structured_event_json_invalid",meaning:"Structured event json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"structured_event_since_invalid",meaning:"Structured event since invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"telemetry_endpoint_probe_failed",meaning:"Telemetry endpoint probe failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_endpoint_probe_http_status",meaning:"Telemetry endpoint probe http status condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_otel_export_failing",meaning:"Telemetry otel export failing condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_queue_high_retries",meaning:"Telemetry queue high retries condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_queue_invalid_rows",meaning:"Telemetry queue invalid rows condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_queue_pending",meaning:"Telemetry queue pending condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_schema_version_behind",meaning:"Telemetry schema version behind condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_state_invalid_json",meaning:"Telemetry state invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"template_type_unknown",meaning:"Template type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"terminal_plan_mutation",meaning:"Terminal plan mutation condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"terminal_state_conflict",meaning:"Terminal state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"tracked_runtime_cache_files",meaning:"Tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"tracker_not_initialized",meaning:"Tracker not initialized condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"tracker_root_missing",meaning:"Tracker root missing condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"]},{code:"tracker_root_not_directory",meaning:"Tracker root not directory condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"]},{code:"type_duplicate",meaning:"Type duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"type_invalid",meaning:"Type invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"unknown_command",meaning:"Unknown command condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"]},{code:"unknown_context_intent",meaning:"Unknown context intent condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-intent-contracts.ts"],emitting_commands:["*"]},{code:"unknown_error",meaning:"Unknown error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"unknown_field",meaning:"Unknown field condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"]},{code:"unknown_field_projection",meaning:"Unknown field projection condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts"],emitting_commands:["get","list"]},{code:"unknown_item_type",meaning:"Unknown item type condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"]},{code:"unknown_lifecycle_action",meaning:"Unknown lifecycle action condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension.ts"],emitting_commands:["*"]},{code:"unknown_option",meaning:"Unknown option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"unknown_plan_template",meaning:"Unknown plan template condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"unknown_provenance_dimension",meaning:"Unknown provenance dimension condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"]},{code:"unknown_status",meaning:"Unknown status condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"]},{code:"unknown_subcommand",meaning:"Unknown subcommand condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts","cli/register-operations.ts","sdk/runtime-extended-actions.ts","sdk/telemetry.ts"],emitting_commands:["*"]},{code:"unsupported_update_option",meaning:"Unsupported update option condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"validate_command_references_stale_pm_ids",meaning:"Validate command references stale pm ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_files_missing_linked_paths",meaning:"Validate files missing linked paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_files_orphaned_paths",meaning:"Validate files orphaned paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_files_tracked_all_strict_forces_pm_internals",meaning:"Validate files tracked all strict forces pm internals condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_format_version_ahead_items",meaning:"Validate format version ahead items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_format_version_outdated_items",meaning:"Validate format version outdated items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_hierarchy_parent_cycle",meaning:"Validate hierarchy parent cycle condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_hierarchy_parent_cycle_error",meaning:"Validate hierarchy parent cycle error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_chain_mismatches",meaning:"Validate history drift chain mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_hash_mismatches",meaning:"Validate history drift hash mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_missing_streams",meaning:"Validate history drift missing streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_unreadable_streams",meaning:"Validate history drift unreadable streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_unknown_author_events",meaning:"Validate history unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_active_closure_like_metadata",meaning:"Validate lifecycle active closure like metadata condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_active_terminal_parent",meaning:"Validate lifecycle active terminal parent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_dependency_cycles",meaning:"Validate lifecycle dependency cycles condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_dependency_cycles_error",meaning:"Validate lifecycle dependency cycles error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_stale_blockers",meaning:"Validate lifecycle stale blockers condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_merge_fence_drift",meaning:"Validate merge fence drift condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_custom_profile_missing_required_fields",meaning:"Validate metadata custom profile missing required fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_duplicate_issue_codes",meaning:"Validate metadata duplicate issue codes condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_acceptance_criteria",meaning:"Validate metadata missing acceptance criteria condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_close_reason",meaning:"Validate metadata missing close reason condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_confidence",meaning:"Validate metadata missing confidence condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_estimate",meaning:"Validate metadata missing estimate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_release",meaning:"Validate metadata missing release condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_reviewer",meaning:"Validate metadata missing reviewer condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_risk",meaning:"Validate metadata missing risk condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_sprint",meaning:"Validate metadata missing sprint condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_resolution_missing_fields",meaning:"Validate resolution missing fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_duplicate_item_ids",meaning:"Validate storage duplicate item ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_history_conflict_markers",meaning:"Validate storage history conflict markers condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_resurrected_items",meaning:"Validate storage resurrected items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_tracked_runtime_cache_files",meaning:"Validate storage tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_unparseable_config",meaning:"Validate storage unparseable config condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_unparseable_history",meaning:"Validate storage unparseable history condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_unreadable_items",meaning:"Validate storage unreadable items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"vectorization_embedding_identity_changed",meaning:"Vectorization embedding identity changed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"vectorization_stale_items_remaining",meaning:"Vectorization stale items remaining condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"workflow_duplicate_type",meaning:"Workflow duplicate type condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_status_unknown",meaning:"Workflow status unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_transition_malformed",meaning:"Workflow transition malformed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_type_empty",meaning:"Workflow type empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_type_unknown",meaning:"Workflow type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workspace_history_state_conflict",meaning:"Workspace history state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"]},{code:"workspace_root_pm_path",meaning:"Workspace root pm path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_force_required",meaning:"Workspace snapshot force required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_manifest_mismatch",meaning:"Workspace snapshot manifest mismatch condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_name_reserved_fingerprint",meaning:"Workspace snapshot name reserved fingerprint condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_not_found",meaning:"Workspace snapshot not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"wrong_item_type",meaning:"Wrong item type condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]}]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af86d275-63a8-5205-a8b3-154efdbd8e2a")}catch{}})();var qp=["mutation_receipt","entity","collection","diagnostic","stream"],Bp=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),Wp=new Set(["close-many","update-many"]),zp=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),Hp=new Set(["aggregate","deps","graph","health","stats","validate"]);function at(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!qp.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function ld(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return Wp.has(n)?at({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):Bp.has(n)?at({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):zp.has(n)?at({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):Hp.has(n)?at({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):at({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var Vp=he.map(e=>ld(e)),Kp=new Map(Vp.map(e=>[e.command,e]));function ud(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=t.split(" "),s=Kp.get(n);return s?{...s,command:t}:ld(t)}function Yp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xp(e){return Yp(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function HT(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!Xp(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.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]="cde81c26-97fa-5236-b807-e944ba4af321")}catch{}})();var Jp=Sn("list").properties.outputSession,Qp={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:{type:"integer",minimum:1,description:"Universal estimated-token ceiling for a read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...Jp}},md={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},F={type:"string",description:"pm item id, for example pm-abc1."},Zp=`Operation name (one of): ${ze.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,ef={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."}},tf={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 A(e,t=[]){return{...md,properties:{...md.properties,...e},required:t}}var nf=[{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:A({action:{type:"string",enum:[...ze],description:Zp},id:F,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."},...Qp},["action"])},{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:A({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:A({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, 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:A({query:{type:"string"},options:{type:"object"},...tf},["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:A({options:{type:"object"},...ef})},{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:A({id:F,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.",inputSchema:A({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"}})},{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:A({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:A({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:F,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:A({id:F,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:A({id:F,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:A({id:F,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:A({id:F,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:A({id:F,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:A({id:F,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:A({id:F,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. 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:A({id:F,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:A({id:F,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:A({id:F,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List or add structured notes on a pm item. Use options.add to append a note; omit it to list existing notes.",inputSchema:A({id:F,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List or add learnings on a pm item. Use options.add to capture a learning/insight; omit it to list existing learnings.",inputSchema:A({id:F,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:A({id:F,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:A({subcommand:{type:"string",enum:[...Pr]},id:F,target:F,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:A({id:F,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:A({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:A({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:A({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. Schema mutations write workspace config files, not item history.",inputSchema:A({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"],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or custom field key (show-field/add-field/remove-field). Required for those subcommands."},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:[...ln]},description:`Lifecycle roles for add-status: ${ln.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."}},["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:A({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:A({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:A({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."}})}],sf={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"},rf=nf.map(e=>{let t=sf[e.name];if(!t)return e;let n=e.inputSchema.properties,s=e.inputSchema.required.map(String);return{...e,inputSchema:Sn(t,{properties:n,required:s})}});function _d(){return rf.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(s=>String(s)).sort((s,r)=>s.localeCompare(r)):[];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]="36bb127d-7a88-5e0d-8296-3d74b9ceb813")}catch{}})();var of=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),af=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],xd=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Yt=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"]),ct=new Set(["cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),Sd=new Map([["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"],["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"]]),Ed=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"]]),Cd=new Map([...Ed.entries()].flatMap(([e,t])=>Te(t).map(n=>[n,e]))),Id=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],cf=new Map(Id.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),df=10,lf=20,pd=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["claim","Claim work."],["close","Close work."],["comments","Manage comments."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["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."],["learnings","Manage learnings."],["list","List work."],["next","Pick next work."],["notes","Manage notes."],["ops","Run operations."],["package","Manage packages."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["stats","Show stats."],["telemetry","Manage telemetry."],["test","Run linked tests."],["update","Update work."],["upgrade","Upgrade packages."],["validate","Validate data."],["workspace","Manage portable workspace primitives."]]),Ad=[["init",Oi],["install",Li],["uninstall",Pi],["explore",Mi],["manage",Gi],["describe",Di],["reload",qi],["doctor",Bi],["catalog",Wi],["adopt",zi],["adopt-all",Fi],["activate",ji],["deactivate",$i],["migrate",Ui]],uf=Ad.map(([e,t])=>e==="init"?[e,Ni]:[e,t]),mf=[...Ad.map(([e,t])=>[`extension ${e}`,t]),...uf.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Ii],["config",Ai],["extension",Ri],["package",kn],["packages",kn],["install",Hi],["create",fo],["item mutate",go],["item complete",ho],["update",yo],["update-many",bo],["upgrade",Vi],["calendar",Tn],["cal",Tn],["context",xn],["ctx",xn],["get",vo],["search",Co],["eval",So],["workspace",le],["workspace snapshot",le],["workspace snapshot create",le],["workspace snapshot list",le],["workspace snapshot inspect",le],["workspace snapshot restore",le],["workspace snapshot delete",le],["next",Eo],["aggregate",_i],["deps",To],["graph",xo],["guide",ko],["reindex",Ki],["history",bi],["history-compact",xi],["history-redact",vi],["history-repair",ki],["history-author-acknowledge",Ti],["merge",wi],["schema",Si],["profile",Ei],["plan",Ci],["restore",Zi],["delete",eo],["close",Yi],["close-many",Xi],["append",Ji],["claim",Qi],["release",to],["start-task",no],["pause-task",so],["close-task",ro],["comments",pi],["notes",fi],["learnings",gi],["files",hi],["docs",yi],["test",io],["test-all",oo],["telemetry",ao],["test-runs",co],["gc",lo],["stats",uo],["duplicates",mo],["validate",po],["health",_o],["contracts",Io],["completion",Ao],["activity",wo],...[...xd].map(e=>[e,mi])],Ts=new Map(mf);function _f(e){let t=Cd.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function fd(e){return he.includes(e)?K(e):e.startsWith("extension-")?K(`extension ${e.slice(10)}`):e.startsWith("package-")?K(`package ${e.slice(8)}`):e.startsWith("test-runs-")?K(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?K(`templates ${e.slice(10)}`):Yt.has(e)?Ed.get(e)??K(e):null}function pf(e,t){return e.command_path===null?!1:Te(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `))}function Te(e){return e.split("|").map(t=>K(t)).filter(t=>t.length>0)}function ff(e,t){let n=new Set(t),s=new Set;for(let r of e)if(r.command_path)for(let i of Te(r.command_path)){let o=i.split(" ").filter(a=>a.length>0);if(o.length!==0)for(let a=o.length;a>0;a-=1){let c=o.slice(0,a).join(" ");if(n.has(c)){s.add(c);break}}}return[...s].sort((r,i)=>r.localeCompare(i))}function Kt(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function dt(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function gf(e,t){if(!t)return{...e};let s=dt(e).filter(r=>{let i=r.properties;if(typeof i!="object"||i===null)return!1;let o=i.action;return typeof o!="object"||o===null?!1:o.const===t});return{...e,oneOf:s}}function ws(e,t){let s=dt(e).filter(r=>{let i=r.properties;if(typeof i!="object"||i===null)return!1;let o=i.action;if(typeof o!="object"||o===null)return!1;let a=o.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:s}}function K(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function gd(e){return e.replace(/\s+/g,"-")}function te(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function hd(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let s of e){let r=te(s);!r||n.has(r)||(n.add(r),t.push(r))}return t}function vs(e,t,n){n&&(e[t]=!0)}function yd(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function hf(e){let t=yd(e.long,"long"),n=yd(e.short,"short"),s=t??n;if(!s)return null;let r={flag:s};n&&t&&(r.short=n),vs(r,"required",e.required===!0),vs(r,"repeatable",e.repeatable===!0),vs(r,"list",e.list===!0);let i=te(e.description);i&&(r.description=i);let o=te(e.value_name);o&&(r.value_name=o);let a=[te(e.value_type),te(e.type),o?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(r.value_type=a),r}function Rd(e){let t=new Map;for(let s of e){let r=K(s.target_command);if(r.length===0)continue;let i=t.get(r)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},o=`${s.layer}:${s.name}`;i.sourceDedupe.has(o)||(i.sourceDedupe.add(o),i.sources.push({layer:s.layer,name:s.name}));for(let a of s.flags){let c=hf(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;i.dedupe.has(d)||(i.dedupe.add(d),i.flags.push(c))}t.set(r,i)}let n=new Map;for(let[s,r]of t.entries())n.set(s,{flags:r.flags,sources:r.sources.sort((i,o)=>{let a=i.layer.localeCompare(o.layer);return a!==0?a:(i.name??"").localeCompare(o.name??"")})});return n}function yf(e){let t=Rd(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let o=K(i.command);if(o.length===0)continue;let a=te(i.action)??gd(o),c=Array.isArray(i.arguments)?i.arguments.map(d=>{let l=te(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:te(d.description)}:null}).filter(d=>d!==null):[];n.set(o,{command:o,action:a,source:{layer:i.layer,name:i.name},description:te(i.description),intent:te(i.intent),arguments:c,flags:t.get(o)?.flags??[],examples:hd(i.examples),failure_hints:hd(i.failure_hints)})}let s=new Set;for(let i of e.handlers)s.add(K(i));for(let i of n.keys())s.add(i);for(let i of t.keys())s.add(i);let r=[];for(let i of[...s].sort((o,a)=>o.localeCompare(a))){let o=n.get(i);if(o){r.push({...o,flags:o.flags.length>0?o.flags:t.get(i)?.flags??[]});continue}r.push({command:i,action:gd(i),source:null,description:null,intent:null,arguments:[],flags:t.get(i)?.flags??[],examples:[],failure_hints:[]})}return r}function bf(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let s=t.replace(/-([a-z0-9])/g,(r,i)=>i.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return s.length>0?s:null}function wf(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 vf(e,t){let n=e.value_type??"boolean",s=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",r=e.repeatable===!0||e.list===!0;return{type:r?"array":s,...r?{items:{type:s}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function kf(e){let t=e.command.split("|").map(r=>r.trim()).filter(r=>r.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},s=["action"];for(let r of e.arguments)n[r.name]=wf(r,e.action),r.required&&s.push(r.name);for(let r of e.flags){let i=bf(r);!i||n[i]!==void 0||(n[i]=vf(r,e.action),r.required===!0&&s.push(i))}return{type:"object",properties:n,required:s,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function Tf(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 xf(e){let t=new Map;for(let n of e){let s=t.get(n.action);if(!s){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}s.command=[...new Set([s.command,n.command])].sort((i,o)=>i.localeCompare(o)).join("|"),s.arguments=s.arguments.length>=n.arguments.length?s.arguments:n.arguments;let r=new Set(s.flags.map(i=>`${i.flag}|${i.short??""}`));for(let i of n.flags){let o=`${i.flag}|${i.short??""}`;if(!r.has(o))r.add(o),s.flags.push(i);else{let a=s.flags.find(c=>`${c.flag}|${c.short??""}`===o);a&&Tf(a,i)}}s.examples=[...new Set([...s.examples,...n.examples])],s.failure_hints=[...new Set([...s.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,s)=>n.action.localeCompare(s.action))}async function Sf(e,t=N){let n={mode:qe.extensions.policy.mode,trust_mode:qe.extensions.policy.trust_mode,default_sandbox_profile:qe.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let s=I(process.cwd(),e.path);if(!await x(O(s)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let r=await t(s),i=await gt({pmRoot:s,settings:r,cwd:process.cwd(),noExtensions:!1}),o=await ht({...i,loaded:i.loaded});return{handlers:new Set(o.commands.handlers.map(c=>K(c.command))),disabledReason:null,commandDefinitions:o.registrations.commands,flagRegistrations:o.registrations.flags,registrations:o.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 Ef(e,t={}){let n=new Map;for(let s of ze){let r=Yt.has(s);if(r&&!t.includePackageOwnedActions)continue;let i=fd(s);n.set(s,{action:s,provider:r?"extension":"core",requires_extension:r,command_path:i})}if(t.includePackageOwnedActions)for(let s of Yt)n.has(s)||n.set(s,{action:s,provider:"extension",requires_extension:!0,command_path:fd(s)});for(let s of e)n.has(s.action)||n.set(s.action,{action:s.action,provider:"extension",requires_extension:!0,command_path:K(s.command)});return[...n.values()].sort((s,r)=>(s.action??"").localeCompare(r.action??""))}function Cf(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};let n=e.command_path?Te(e.command_path):[],s=n.some(o=>t.handlers.has(o)),r=n.map(o=>Sd.get(o)).find(o=>typeof o=="string"),i=t.disabledReason===null&&s;return{action:e.action,invocable:i,available:i,requires_extension:!0,provider:"extension",disabled_reason:i?null:t.disabledReason??(r?`optional_package_not_installed:${r}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:s,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function Od(e){return Ts.get(e)??ui}function If(e){return ct.has(e)?!1:Ts.has(e)}function Af(e){return xd.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function bd(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function Rf(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function Of(e){let t=new Map;for(let s of e.definitions){let r=bd(s.cli_flag);if(!r)continue;let i=s.cli_aliases.map(a=>Rf(a)).find(a=>a!==null),o=s.cli_aliases.map(a=>bd(a)).filter(a=>a!==null&&a!==r);for(let a of s.commands){let c=t.get(a)??{flags:[],seen:new Set},d=i?{flag:r,short:i}:{flag:r},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of o){let m=`${u}|`;c.seen.has(m)||(c.seen.add(m),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[s,r]of t.entries())n.set(s,vn(r.flags));return n}function wd(e,t){let n=[],s=new Set;for(let r of[...e,...t]){let i=`${r.flag}|${r.short??""}`;s.has(i)||(s.add(i),n.push(r))}return vn(n)}function Nf(e,t,n,s){return e.map(r=>{let i=If(r),o=i?Od(r):[],a=n.get(Af(r))??[],c=t.get(r),d=wd(o,a),l=wd(d,c?.flags??[]),u=o.length>0&&(c?.flags.length??0)>0?"mixed":i?"core":"extension";return{command:r,flags:l,...s?{canonical_command:ks(r),visibility:od(ks(r)),flag_invocations:rd(r,l)}:{},provider:u,extension_sources:c?.sources}}).sort((r,i)=>r.command.localeCompare(i.command))}function Lf(e){let t=new Set(e);return Id.map(n=>({canonical:n.canonical,aliases:n.aliases.filter(s=>t.has(s))})).filter(n=>t.has(n.canonical)&&n.aliases.length>0)}function Pf(){return{create_string_options:ai,create_repeatable_options:ci,update_string_options:di,update_repeatable_options:li,list_string_options:ni,search_string_options:si,calendar_string_options:ri,context_string_options:ii,activity_string_options:oi}}function vd(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let s=or(e,"create",n),r=[...new Set(s.required)].sort((a,c)=>a.localeCompare(c)),i=[...new Set(r.map(a=>ir("create",a)))].sort((a,c)=>a.localeCompare(c)),o=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:r,required_flags:i,required_type_options:o,policy_errors:[...new Set(s.errors)].sort((a,c)=>a.localeCompare(c))}}function Mf(e){let t={},n={};for(let s of[...e.types].sort((r,i)=>r.localeCompare(i))){let r=e.by_type[s];t[s]=vd(r,"strict"),n[s]=vd(r,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Df(e,t){let n=dt(e);if(n.length===0)return e;let s=!1,r=n.map(i=>{let o=i.properties;if(typeof o!="object"||o===null)return i;let a=o.action;return typeof a!="object"||a===null||a.const!=="create"?i:(s=!0,{...i,"x-create-required-options":t})});return s?{...e,oneOf:r}:e}function Ff(e){let t=Kt(e.action)!==void 0||Kt(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,s=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,r=e.schemaOnly===!0,i=e.flagsOnly===!0,o=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=Kt(e.action),l=Kt(e.command),u=!s&&!c&&!r&&!i&&!o&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:s,schemaOnly:r,flagsOnly:i,availabilityOnly:o,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u}}function jf(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new g("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",f.USAGE)}async function $f(e,t=N){try{return await t(e)}catch{return structuredClone(qe)}}async function Uf(e,t){let n=await $f(t),s=await Sf(e),r=V(n,s.registrations??W()),i=br(n.schema),o=yf(s);return{settings:n,runtimeProbe:s,typeRegistry:r,statusRegistry:ee(n.schema),runtimeFieldRegistry:i,runtimeFieldFlagMap:Of(i),createRequiredOptionContracts:Mf(r),extensionContracts:o,mergedExtensionContracts:xf(o),extensionFlagMap:Rd(s.flagRegistrations)}}function kd(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Yt.has(e.selectedAction)||e.selectedCommand!==void 0&&ct.has(e.selectedCommand))}function Gf(e,t){let n=Ef(t,{includePackageOwnedActions:kd(e)});return kd(e)&&e.selectedCommand!==void 0&&ct.has(e.selectedCommand)&&!n.some(s=>s.command_path===e.selectedCommand)&&n.push({action:_f(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function qf(e,t){let n=new Set(t.map(s=>s.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new g(`Unknown action: "${e.selectedAction}".`,f.USAGE)}function Bf(e,t){return[...new Set([...he.filter(n=>!ct.has(n)),...[...Ts.keys()].filter(n=>!ct.has(n)),...e.flatMap(n=>n.command_path?Te(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>K(n)).filter(n=>n.length>0).sort((n,s)=>n.localeCompare(s))}function Wf(e,t){let n=t.slice(0,df),s=t.length-n.length,r=s>0?`${n.join(", ")}, and ${s} more`:n.join(", "),i=t.slice(0,lf),o=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new g(`Command "${e}" is a command namespace. Choose a concrete child command: ${r}.`,f.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:o,nextSteps:[`Retry with a child command, for example: ${o[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --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 zf(e,t){return new g(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,f.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function Hf(e){return new g(`Unknown command: "${e}".`,f.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 Vf(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let s=t.filter(i=>i.startsWith(`${e.selectedCommand} `));if(s.length>0)throw Wf(e.selectedCommand,s);let r=Sd.get(e.selectedCommand);throw r?zf(e.selectedCommand,r):Hf(e.selectedCommand)}function Kf(e,t){let n=Gf(e,t.mergedExtensionContracts);qf(e,n);let s=Bf(n,t.mergedExtensionContracts);Vf(e,s);let r=e.selectedCommand?Cd.get(e.selectedCommand):void 0,i=e.selectedCommand?n.filter(d=>r?d.action===r:pf(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.some(d=>d.action===e.selectedAction))throw new g(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,f.USAGE);let o=e.selectedAction?i.filter(d=>d.action===e.selectedAction):i,a=[...new Map(o.map(d=>Cf(d,t.runtimeProbe)).map(d=>[r?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:s,commandScopedDescriptors:i,scopedActionDescriptors:o,selectedPackageOwnedAction:r,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function Yf(e){return new Set(dt(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let s=n.action;if(typeof s!="object"||s===null)return null;let r=s.const;return typeof r=="string"?r:null}).filter(t=>t!==null))}function Xf(e){let t=Ro,n=dt(t),s=Yf(t),r=e.filter(i=>!s.has(i.action)).map(i=>kf(i));return r.length>0?{...t,oneOf:[...n,...r]}:t}function Td(e,t,n){let s=new Set(t.actionDescriptors.map(i=>i.action)),r=e.selectedAction?gf(n,e.selectedAction):e.selectedCommand?ws(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):ws(n,s);return e.runtimeOnly&&!e.selectedAction?ws(r,new Set(t.actions)):r}function Jf(e,t,n){let s=Xf(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?Df(Td(e,n,s),t.createRequiredOptionContracts):Td(e,n,s);return{mergedSchema:s,filteredSchema:i}}function Qf(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?ff(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Zf(e,t){return t}function eg(e){let t=e.split(" ")[0];return pd.get(e)??pd.get(t)??"Inspect flags."}function ks(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":t==="ctx"?"context":t==="packages"?"package":cf.get(t)??t}function tg(e){let t=new Map;for(let s of e){let r=s.split(" ")[0],i=ks(r),o=t.get(i)??new Set;o.add(r),t.set(i,o)}return[...t.keys()].filter(s=>s.length>0).sort((s,r)=>s.localeCompare(r)).map(s=>{let r=gn(s,{generateFallback:!0}),i=new Set(Od(s).map(c=>c.flag)),o=(of.get(s)??af).filter(c=>i.has(c)),a=[...t.get(s)].filter(c=>c!==s).sort((c,d)=>c.localeCompare(d));return{command:s,...a.length>0?{aliases:a}:{},intent:eg(s),...o.length>0?{flags:o}:{},default_max_estimated_tokens:r.default_max_estimated_tokens}})}function ng(e){return e.map(t=>({budget:gn(t,{generateFallback:!0}),envelope:ud(t)}))}function sg(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(s=>Te(s.command).includes(e.selectedCommand));if(e.selectedAction){let s=new Set(n);return t.extensionContracts.filter(r=>Te(r.command).some(i=>s.has(i)))}return t.extensionContracts}function rg(e,t,n,s){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?[]:s,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function ig(e,t){e.runtime_schema={statuses:t.statusRegistry.definitions.map(n=>n.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()].map(([n,s])=>[n,[...new Set(s.map(r=>`--${r.cli_flag}`))].sort((r,i)=>r.localeCompare(i))]))},e.extension_contracts={capabilities:[...Ir],services:[...Ar],policy_modes:[...Rr],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Lr],trust_modes:[...Or],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Nr],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...tr],create_modes:[...nr],close_validation_modes:[...sr],workflow_enforcement_modes:[...rr]}}function og(e,t,n,s){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=s;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=s}}function ag(e,t,n,s,r){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=Nf(s,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let i=new Set(s);e.list_projections=Object.entries(Fo).filter(([o])=>i.has(o)).map(([o,a])=>({command:o,default:a,brief_fields:[...Do],compact_fields:[...Mo]}))}r.length>0&&(e.command_aliases=r)}}function cg(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=Pf();return}e.commander_aliases_omitted_reason="unfiltered_default_brief"}}function dg(e,t){e.command_summaries=tg(t),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Mr],allows_unbounded_opt_out:!0}}async function dx(e,t){let n=Ff(e);jf(n);let s=I(process.cwd(),t.path),r=await Uf(t,s),i=Kf(n,r),o=Jf(n,r,i),a=Qf(n,i),c=Zf(n,a),d=rg(n,o,i,c);if((n.summary||n.fullOutput)&&dg(d,c),n.summary)return d;let l=Lf(a),u=sg(n,r,c);return n.flagsOnly&&!n.fullOutput||ig(d,r),og(d,n,o,u),ag(d,n,r,c,l),cg(d,n),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=_d(),d.context_intents=Cr(),d.read_output_dimensions=Er,d.error_codes=dd,d.command_output_contracts=ng(c)),d}import{createHash as ug}from"node:crypto";import{execFile as mg}from"node:child_process";import Pd from"node:path";import{promisify as _g}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]="939d5f93-d287-5c1c-bc78-d013f76735f2")}catch{}})();var Nd=1;function lg(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 xs(e){if(e===null)return{format_version:Nd,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new g("Improvement ledger contains invalid JSON.",f.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Nd||!Array.isArray(t.observations))throw new g("Improvement ledger has an unsupported shape or format version.",f.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let s of n)if(!lg(s))throw new g("Improvement ledger contains an invalid observation.",f.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]="aaa927b3-4bc4-561f-aff1-85dc95c12ea1")}catch{}})();var pg=_g(mg),fg=50,Ld=1e3,gg=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Md(e){let t=e.trim().toLowerCase();if(!gg.test(t))throw new g(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,f.USAGE,{code:"invalid_improvement_metric"});return t}function hg(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new g("Improvement direction must be higher, lower, or target.",f.USAGE,{code:"invalid_improvement_observation"});return t}function lt(e,t){let n=e?.trim();if(n){if(n.length>256)throw new g(`${t} must not exceed 256 characters.`,f.USAGE,{code:"invalid_improvement_observation"});return n}}function yg(e){let t=e??fg;if(!Number.isSafeInteger(t)||t<0||t>Ld)throw new g(`Improvement observation limit must be an integer from 0 to ${Ld}.`,f.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Dd(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new g(`${t} must be an ISO timestamp.`,f.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function bg(e,t,n){if(!Number.isFinite(n.value))throw new g("Improvement observation value must be finite.",f.USAGE,{code:"invalid_improvement_observation"});let s=Md(n.metric),r=hg(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||r==="target"&&n.threshold===void 0)throw new g("Target-directed observations require a finite threshold.",f.USAGE,{code:"invalid_improvement_observation"});let i=await vg(e,n.revision),o=lt(n.source,"source"),a=lt(n.itemId,"itemId"),c=lt(n.unit,"unit"),d=lt(n.idempotencyKey,"idempotencyKey")??(i.revision_source==="unversioned"?void 0:[i.revision,s,o??"manual",a??"workspace"].join(":")),l={metric:s,value:n.value,direction:r,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Dd(n.observedAt??v(),"observedAt"),...i,author:J(n.author,t.author_default),...a===void 0?{}:{item_id:a},...o===void 0?{}:{source:o},...d===void 0?{}:{idempotency_key:d}};return{id:ug("sha256").update(Se(l)).digest("hex").slice(0,24),...l}}function wg(e,t){let n=t.idempotency_key?e.observations.find(r=>r.idempotency_key===t.idempotency_key):e.observations.find(r=>r.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 g(`Improvement observation retry key already records a different value for ${t.metric}.`,f.CONFLICT,{code:"improvement_observation_conflict"});return n}let s=e.observations.find(r=>r.metric===t.metric);if(s&&(s.direction!==t.direction||s.unit!==t.unit||t.direction==="target"&&s.threshold!==t.threshold))throw new g(`Metric ${t.metric} is already declared with direction ${s.direction} and unit ${s.unit??"<none>"}.`,f.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function vg(e,t){let n=lt(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await pg("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:ar(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function kg(e){let t=e[0],n=e[e.length-1],s=n.value-t.value,r=n.direction==="higher"?s>0:n.direction==="lower"?s<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:s,improved:r,sample_count:e.length}}async function Fd(e,t={}){let n=I(process.cwd(),t.path);if(!await x(O(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,f.NOT_FOUND);let s=await N(n),r=await bg(n,s,e),i=Pd.join(n,"improvement-ledger.json"),o=await Fr({pmRoot:n,filePath:i,op:"improvement_observe",author:r.author,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms,message:e.message??`Record ${r.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=xs(a),d=wg(c,r);return d?{raw:a,result:d}:(c.observations.push(r),c.observations.sort((l,u)=>l.observed_at.localeCompare(u.observed_at)||l.metric.localeCompare(u.metric)||l.id.localeCompare(u.id)),{raw:`${Se(c)}
10
- `,result:r})}});return{changed:o.changed,observation:o.result,ledger_path:"improvement-ledger.json"}}async function jd(e={}){let t=I(e.cwd??process.cwd(),e.pmRoot);if(!await x(O(t)))throw new g(`Tracker is not initialized at ${t}. Run pm init first.`,f.NOT_FOUND);let n=e.metric===void 0?void 0:Md(e.metric),s=e.since===void 0?void 0:Dd(e.since,"since"),r=yg(e.limit),o=xs(await j(Pd.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(s===void 0||c.observed_at>=s)),a=new Map;for(let c of o){let d=a.get(c.metric)??[];d.push(c),a.set(c.metric,d)}return{observations:[...o].reverse().slice(0,r),total:o.length,truncated:o.length>r,trends:[...a].map(([,c])=>kg(c)).sort((c,d)=>c.metric.localeCompare(d.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]="1f6a4ff8-fc1e-5aac-8117-bae8f325b275")}catch{}})();function Tg(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 xg(e,t,n){let s=t,r=new Set([e.id]);for(;s!==void 0&&!r.has(s.id);)r.add(s.id),s=s.parent_id?n.get(s.parent_id):void 0;return s===void 0}function Sg(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((s,r)=>s.entries[0].ts.localeCompare(r.entries[0].ts)||s.id.localeCompare(r.id)),t.push(...n.map(s=>s.children))}}function $d(e=We,t=Be){return t.map(n=>{let s=e.filter(r=>((n==="model"?r.model_environment_keys:r.provenance_environment_keys?.[n])?.length??0)>0||r.provenance_resolvers?.[n]!==void 0).map(r=>r.harness).sort();return{dimension:n,harnesses:s,covered:s.length>0}})}function Rx(e,t=1){let n=new Map;for(let s of e){if(!s.agent_harness)continue;let r=n.get(s.agent_harness)??{harness:s.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};r.entries+=1,s.agent_model||s.agent_provenance?.model&&s.agent_provenance.model.value.length>0?r.observed+=1:s.agent_provenance?.model===null?r.unavailable+=1:r.legacy_missing+=1,n.set(s.agent_harness,r)}return[...n.values()].map(s=>{let r=s.observed+s.unavailable;return{...s,coverage:r===0?null:s.observed/r,inert:r>=t&&s.observed===0}}).sort((s,r)=>s.harness.localeCompare(r.harness))}function Ud(e,t=Be,n=1){let s=new Map;for(let r of e)if(r.agent_harness)for(let i of t){let o=`${r.agent_harness}\0${i}`,a=s.get(o)??{harness:r.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=r.agent_provenance?.[i];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,s.set(o,a)}return[...s.values()].map(r=>{let i=r.observed+r.unavailable;return{...r,coverage:i===0?null:r.observed/i,inert:i>=n&&r.observed===0}}).sort((r,i)=>r.harness.localeCompare(i.harness)||r.dimension.localeCompare(i.dimension))}function Ox(e){let t=[...e].sort((i,o)=>i.ts.localeCompare(o.ts)||i.author.localeCompare(o.author)||i.op.localeCompare(o.op)||i.before_hash.localeCompare(o.before_hash)||i.after_hash.localeCompare(o.after_hash)),n=new Map,s=new Map;for(let i of t){let o=i.agent_episode,a=Tg(i),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(i);continue}let l={id:a.id,...o?.label===void 0?{}:{label:o.label},...o?.parent_id===void 0?{}:{parent_id:o.parent_id},source:a.source,entries:[i],children:[]};n.set(c,l),o!==void 0&&s.set(a.id,l)}let r=[];for(let i of n.values()){let o=i.parent_id?s.get(i.parent_id):void 0;o&&xg(i,o,s)?o.children.push(i):r.push(i)}return Sg(r),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]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var Eg=1e4,Gd=1e5,Cg=1e3,Ig=30,Ag=["append","comment","docs","file","learning","note","test_run"];function Rg(e){let t=e??Eg;if(!Number.isSafeInteger(t)||t<1||t>Gd)throw new g(`History analytics event limit must be an integer from 1 to ${Gd}.`,f.USAGE,{code:"invalid_history_analytics_limit"});return t}function qd(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new g("History analytics minimum sample must be an integer from 1 to 10000.",f.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function Og(e){let t=e?.trim();if(!t)return new Date(Date.now()-Ig*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let r=Number(n[1]),i=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(r)||r<1)throw new g("History analytics --since duration must be positive.",f.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-r*i).toISOString()}let s=Date.parse(t);if(!Number.isFinite(s))throw new g("History analytics --since must be an ISO timestamp or negative duration such as -30d.",f.USAGE,{code:"invalid_history_analytics_since"});return new Date(s).toISOString()}async function Xt(e,t){let n=Rg(t.eventLimit),s=Og(t.since),r=[],i=s,o=!1;for(;r.length<n;){let a=await ra({pmRoot:e,since:i,limit:Math.min(Cg,n-r.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(r.push(...c),o=a.has_more,i=a.next_cursor,!a.has_more)break}return{events:r,receipt:{since:s,events:r.length,truncated:o,...o?{next_cursor:i}:{},source:"history_event_index"}}}function Ng(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function Lg(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 Pg(e){return Ag.some(t=>e.startsWith(t))}function Bd(e,t){let n=e.get(t);if(n)return n;let s={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,s),s}function Mg(e,t,n){let s=new Map,r=new Map,i=new Map;for(let o of t){let a=Ng(o.entry,e),c=Lg(o.entry),d=r.get(o.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&r.set(o.item_id,l),!a)continue;let u=Bd(s,a);u.events+=1,Pg(o.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,i.set(o.item_id,a)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:s,lastCloseValue:i}}function Dg(e,t,n){for(let s of n){if(s.type!=="Issue")continue;let r=new Set((s.dependencies??[]).filter(i=>i.kind==="discovered_from").map(i=>i.id));for(let i of r){let o=t.get(i);o&&(Bd(e,o).defectEscapes+=1)}}}function Fg(e,t,n,s){let r=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:r==="available"?t.closes/s:null,rework_rate:r==="available"?t.reopens/t.closes:null,defect_escape_rate:r==="available"?t.defectEscapes/t.closes:null,sample_status:r}}function jg(e,t,n,s,r,i){let{buckets:o,lastCloseValue:a}=Mg(e,t,s);return Dg(o,a,n),{dimension:e,status:o.size===0?"unavailable":"available",rows:[...o].map(([c,d])=>Fg(c,d,r,i)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function $g(e,t){let n=e[0]?.entry.ts??t,s=e[e.length-1]?.entry.ts??n,r=Date.parse(n),i=Date.parse(s);return!Number.isFinite(r)||!Number.isFinite(i)?1:Math.max(1,(i-r)/864e5)}function Ug(e,t,n){let s=$d(t),r=Ud(e,Be,n),i=r.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),o=s.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:s,observations:r,inert:i,undeclared:o,warnings:[...i.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...o.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function jx(e,t=We,n={}){return Ss(await Xt(e,n),t,n)}function Ss(e,t=We,n={}){let s=qd(n.minimumSample);return{...Ug(e.events.map(r=>r.entry),t,s),window:e.receipt}}async function $x(e,t,n,s={}){return Es(await Xt(e,s),t,n,s)}function Es(e,t,n,s={}){let r=qd(s.minimumSample),i=$g(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(o=>jg(o,e.events,t,n,r,i)),minimum_sample:r,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]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var Gg=32;function qg(e){let t=[];for(let n of e??[]){let s=[];for(let r of n.split(",")){let i=r.slice(0,r.indexOf("=")).trim();s.length>0&&i!=="unit"&&i!=="threshold"&&(t.push(s.join(",")),s=[]),s.push(r)}t.push(s.join(","))}return t}function ut(e,t){let n=qg(e).map(r=>{let[i,...o]=r.split(","),a=i.indexOf("="),c=i.slice(0,a).trim(),d=i.slice(a+1).trim(),l=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(l))throw new g(`Invalid --measure "${r}"; expected name=value[,unit=...][,threshold=...]`,f.USAGE);let u,m;for(let _ of o){let p=_.indexOf("="),h=_.slice(0,p).trim(),y=_.slice(p+1).trim();if(h==="unit"&&y.length>0)u=y;else if(h==="threshold"&&y.length>0&&Number.isFinite(Number(y)))m=Number(y);else throw new g(`Invalid --measure attribute "${_}"`,f.USAGE)}return{name:c,value:l,unit:u,threshold:m,recorded_at:t}});return[...new Map(n.map(r=>[r.name,r])).values()].sort((r,i)=>r.name.localeCompare(i.name)).slice(0,Gg)}function Wd(e,t,n){return e.flatMap(s=>(s.measurements??[]).filter(r=>r.name===t&&r.value<n).map(r=>({...r,run_id:s.run_id})))}function zd(e,t){let n=e.flatMap(i=>i.measurements??[]).filter(i=>i.name===t).sort((i,o)=>o.recorded_at.localeCompare(i.recorded_at)),s=n[0],r=n[1];return{name:t,latest:s?.value??null,previous:r?.value??null,delta:s!==void 0&&r!==void 0?s.value-r.value:null,unit:s?.unit}}import Wg from"node:fs/promises";import Vd 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]="ed44fc89-8b6e-5c83-a4f4-ced4e9031dac")}catch{}})();function Jt(e,t,n,s,r,i="min"){let o=r==="min"?e-t:t-e,a=i==="min"?n.localeCompare(s??n):(s??n).localeCompare(n);return o<0||o===0&&s!==null&&a<0}function Bg(e,t){let n=Buffer.byteLength(t,"utf8"),s=0,r=null,i=null,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;s+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,m=Date.parse(u);Number.isNaN(m)||(Jt(m,o,u,r,"min")&&(o=m,r=u),Jt(m,a,u,i,"max","max")&&(a=m,i=u))}return{id:e,bytes:n,lines:s,oldest_ts:r,newest_ts:i}}function Hd(e,t){let n=t?.topN??5,s=Math.max(0,Math.floor(n)),r=e.map(({id:_,raw:p})=>Bg(_,p)),i=0,o=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let _ of r){if(i+=_.lines,o+=_.bytes,_.oldest_ts!==null){let p=Date.parse(_.oldest_ts);Jt(p,d,_.id,a?.id??null,"min")&&(d=p,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let p=Date.parse(_.newest_ts);Jt(p,l,_.id,c?.id??null,"max")&&(l=p,c={id:_.id,ts:_.newest_ts})}}let u=s===0?[]:[...r].sort((_,p)=>p.bytes-_.bytes||_.id.localeCompare(p.id)).slice(0,s),m=s===0?[]:[...r].sort((_,p)=>p.lines-_.lines||_.id.localeCompare(p.id)).slice(0,s);return{total_streams:e.length,total_lines:i,total_bytes:o,largest_by_bytes:u,deepest_by_lines:m,oldest_entry:a,newest_entry: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]="a4de53c1-bb22-591f-a064-142c642a2443")}catch{}})();function zg(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function Hg(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function Vg(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function Kg(e){let t=Vd.join(e,"history");if(!await x(t))return[];await X({path:t,scope:"project"});let n=(await Wg.readdir(t)).filter(r=>r.endsWith(".jsonl")).sort((r,i)=>r.localeCompare(i)),s=[];for(let r of n){let i=Vd.join(t,r),o=await j(i);o!==null&&(await X({path:i,scope:"project"}),s.push({id:r.slice(0,-6),raw:o}))}return s}async function Yg(e,t){let n=[],s=v();for(let r of ut(t.observe,s))n.push(await Fd({metric:r.name,value:r.value,direction:t.direction,unit:r.unit,threshold:r.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:s,author:t.author,message:t.message},e));return n}function Xg(e,t,n){let s={};return t.byAssignee&&(s.assignee=Et(e,"assignee",n)),t.byTag&&(s.tag=Et(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(s.priority=Et(e,"priority",n)),s}async function Jg(e,t,n,s,r){let i={since:r.since,eventLimit:r.eventLimit,minimumSample:r.minimumSample},o=r.provenanceCoverage||r.fleetAttribution?await Xt(e,i):void 0;return{provenanceCoverage:r.provenanceCoverage&&o?Ss(o,n.agent_identity?.harness_signals,i):void 0,fleetAttribution:r.fleetAttribution&&o?Es(o,t,s,i):void 0}}function Qg(e,t,n,s){let r=Object.keys(s.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,...s.metadataCoverage?{metadata_coverage:s.metadataCoverage}:{},...r?{breakdowns:s.breakdowns}:{},...s.storage?{storage:s.storage}:{},...s.fieldUtilization?{field_utilization:s.fieldUtilization}:{},...s.improvementLedger?{improvement_ledger:s.improvementLedger}:{},...s.recordedObservations.length>0?{recorded_observations:s.recordedObservations}:{},...s.provenanceCoverage?{provenance_coverage:s.provenanceCoverage}:{},...s.fleetAttribution?{fleet_attribution:s.fleetAttribution}:{},generated_at:v()}}async function dS(e,t={}){let n=I(process.cwd(),e.path);if(!await x(O(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,f.NOT_FOUND);let s=await N(n),r=await Yg(e,t),i=V(s,W()),o=ee(s.schema),a=t.fieldUtilization?await Ie(n,s.item_format,i.type_to_folder,void 0,s.schema):await St(n,s.item_format,i.type_to_folder,void 0,s.schema);await Tt({pmRoot:n,settings:s,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=zg(i.types),d=Hg(o.definitions.map(k=>k.id));for(let k of a)c[k.type]+=1,d[k.status]+=1;let l=await Kg(n),u=0;for(let k of l)u+=Vg(k.raw);let m=t.storage?Hd(l):void 0,_=No(o),p=t.metadataCoverage?Lo(a,_):void 0,h=Xg(a,t,_),y=t.fieldUtilization?Po(a):void 0,w=t.measurements===!0||r.length>0?await jd({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:T,fleetAttribution:C}=await Jg(n,a,s,o.terminal_statuses,t);return Qg({items:a.length,history_streams:l.length,history_entries:u},c,d,{metadataCoverage:p,breakdowns:h,storage:m,fieldUtilization:y,improvementLedger:w,recordedObservations:r,provenanceCoverage:T,fleetAttribution: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]="6152efa9-8338-57f0-b3de-5707befed019")}catch{}})();async function _S(e,t={}){let n=await Go({pmRoot:I(process.cwd(),e.path),...t.status===void 0?{}:{statuses:t.status.flatMap(s=>s.split(",").map(r=>r.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(s=>{let r=s.id;return{...s,canonical_id:r,close_command:`pm close <duplicate-id> --duplicate-of ${r}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import Zg from"node:fs/promises";import fe 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]="150c6ff7-cfb5-542f-bd3d-3c8088d1086a")}catch{}})();var Qd=fe.join("runtime","telemetry","events.jsonl"),Zd=fe.join("runtime","telemetry","state.json"),eh=fe.join("runtime","telemetry"),th=20,Kd=["status","flush","stats","clear"],Yd=(e,t)=>{let n=Math.ceil(t*e.length),s=Math.min(e.length-1,Math.max(0,n-1));return e[s]},Cs=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Xd=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},nh=e=>({command:Cs(e.event.command,"<unknown>"),eventType:Cs(e.event.event_type,"unknown"),eventSchemaVersion:Xd(e.event.schema_version),clientSchemaVersion:Xd(e.client_schema_version)}),sh=()=>({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:{}}),rh=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},ih=e=>{let t=e?.command_resolution;return Cs(t,"")||void 0},el=(e,t)=>{e[t]=(e[t]??0)+1},oh=(e,t)=>{let n=rh(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let s=ih(t);s!==void 0&&el(e.resolution_counts,s)},ah=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Jd=(e,t)=>{t!==void 0&&e.add(t)},ch=(e,t)=>{let n=nh(t),s=e.get(n.command)??sh();s.count+=1,s.max_attempts=Math.max(s.max_attempts,ah(t.attempts)),el(s.event_type_counts,n.eventType),Jd(s.event_schema_versions,n.eventSchemaVersion),Jd(s.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&oh(s,t.event.payload),e.set(n.command,s)},dh=(e,t)=>{let n=t.ok_count+t.error_count,s=[...t.finish_durations_ms].sort((i,o)=>i-o),r=Object.entries(t.resolution_counts).sort((i,o)=>i[0].localeCompare(o[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((i,o)=>i[0].localeCompare(o[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((i,o)=>i-o),client_schema_versions:[...t.client_schema_versions].sort((i,o)=>i-o),...s.length>0?{duration_p50_ms:Yd(s,.5),duration_p95_ms:Yd(s,.95),duration_max_ms:s[s.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...r.length>0?{command_resolution_counts:Object.fromEntries(r)}:{}}},lh=e=>{let t=(e??"status").trim().toLowerCase();if(Kd.includes(t))return t;throw new g(`Unknown pm telemetry subcommand "${e}". Allowed: ${Kd.join(", ")}`,f.USAGE,{code:"unknown_subcommand",examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Is=()=>{throw new g("--limit must be a positive integer",f.USAGE)},tl=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Is():e,uh=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Is():tl(Number.parseInt(t,10))},mh=e=>e===void 0?th:typeof e=="number"?tl(e):typeof e=="string"?uh(e):Is(),_h=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},ph=e=>{try{let t=JSON.parse(e);return _h(t)?t:void 0}catch{return}},fh=e=>e===null?[]:e.split(`
11
- `).map(t=>t.trim()).filter(t=>t.length>0),nl=e=>{let t=fh(e),n=[],s=0;for(let r of t){let i=ph(r);i===void 0?s+=1:n.push(i)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:s,entries:n}},gh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hh=e=>{try{let t=JSON.parse(e);return gh(t)?t:{}}catch{return{}}},yh=async e=>{let t=await j(e);return t===null||t.trim().length===0?{}:hh(t)},Qt=e=>e??null,Zt=async e=>{let t=await N(e),n=fe.join(e,Qd),s=fe.join(e,Zd),r=await j(n),i=nl(r),o=await yh(s);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:s,queue_rows_total:i.rows_total,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_size_bytes:Buffer.byteLength(r??"","utf8"),last_attempted_flush_at:Qt(o.last_attempted_flush_at),last_successful_flush_at:Qt(o.last_successful_flush_at),last_failed_flush_at:Qt(o.last_failed_flush_at),last_failed_flush_error:Qt(o.last_failed_flush_error)}},bh=e=>{let t=new Map;for(let n of e)ch(t,n);return[...t.entries()].map(([n,s])=>dh(n,s)).sort((n,s)=>s.count-n.count||n.command.localeCompare(s.command))},wh=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Zt(t.globalPmRoot),generated_at:v()}),vh=async(e,t)=>{let n=await Zt(t.globalPmRoot);await ti(t.globalPmRoot);let s=await Zt(t.globalPmRoot),r=Math.max(0,n.queue_entries-s.queue_entries),i=s.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:s.queue_entries,queue_entries_drained:r,queue_progressed:r>0,queue_empty:i,queue_drained:i,status:s,generated_at:v()}},kh=async(e,t)=>{let n=mh(e.limit),s=await j(t.queuePath),r=nl(s),i=bh(r.entries),o=i.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:i.length,queue_entries:r.valid_entries,queue_invalid_rows:r.invalid_rows,queue_rows_total:r.rows_total,truncated:i.length>o.length,stats:o,generated_at:v()}},Th=async(e,t)=>{let n=await N(t.globalPmRoot),s=[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="",s&&await Gr(t.globalPmRoot,n,"telemetry:clear");let r=fe.join(t.globalPmRoot,eh),i=await x(r);return await Zg.rm(r,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:s,runtime_dir_removed:i&&!await x(r),queue_exists_after:await x(t.queuePath),state_exists_after:await x(t.statePath),status:await Zt(t.globalPmRoot),generated_at:v()}},xh={status:wh,flush:vh,stats:kh,clear:Th};async function xS(e,t){let n=lh(e.subcommand),s=Z(process.cwd());return xh[n](e,{globalPmRoot:s,queuePath:fe.join(s,Qd),statePath:fe.join(s,Zd)})}import{spawn as vl}from"node:child_process";import{cp as al,mkdir as Ah,mkdtemp as kl,open as Ns,readdir as Ls,rm as Tl}from"node:fs/promises";import{tmpdir as xl}from"node:os";import G 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]="62af7c1e-c1c7-529e-ab30-117103ac4607")}catch{}})();var sl=20;function Sh(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return sl;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?sl:t}function As(e){let t=[...e].filter(s=>s.run_id.trim().length>0&&s.started_at.trim().length>0&&s.finished_at.trim().length>0&&s.recorded_at.trim().length>0).sort((s,r)=>{let i=Zs(s.recorded_at,r.recorded_at);if(i!==0)return i;let o=s.run_id.localeCompare(r.run_id);return o!==0?o:s.kind.localeCompare(r.kind)}),n=Sh();return t.length>n?t.slice(t.length-n):t}async function en(e){await ye({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=As([...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]="8a6a3402-dae3-56f8-b9ba-a4f6f8a47cda")}catch{}})();var rl=100;function Rs(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new g(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,f.USAGE);return n}function Eh(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=rl?n:`${n.slice(0,rl-3)}...`}function il(e){return e.map((t,n)=>`${n+1}. ${Eh(t)}`).join("; ")}function Ch(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 Ih(e,t){let n=e.command?.toLowerCase()??"",s=e.path?.toLowerCase()??"";return n.includes(t)||s.includes(t)}function ol(e,t){let n=Ch(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((r,i)=>i+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new g(`Combine at most one linked-test selector per run: ${n.map(r=>`--${r}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,f.USAGE);let s=n[0];if(e.length===0)throw new g(`--${s} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,f.USAGE);if(s==="match"){let r=t.match.trim().toLowerCase();if(r.length===0)throw new g("--match requires a non-empty substring to match against linked-test command/path values",f.USAGE);let i=[],o=[];for(let a=0;a<e.length;a+=1)Ih(e[a],r)&&(o.push(e[a]),i.push(a+1));if(o.length===0)throw new g(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${il(e)}`,f.USAGE);return{selector:"match",requested:t.match,selected:o,selected_indexes:i,selected_count:o.length,skipped_count:e.length-o.length}}if(s==="only-index"){let r=Rs(t.onlyIndex);if(r>e.length)throw new g(`--only-index ${r} is out of range: this item has ${e.length} linked test(s). Available entries: ${il(e)}`,f.USAGE);return{selector:"only-index",requested:String(r),selected:[e[r-1]],selected_indexes:[r],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]="7d05534b-3cf7-506c-8626-4bd4a42cbc80")}catch{}})();var nn=20*1024*1024,Rh=3e3,Oh=1e4,Nh=5e3,cl=120,Lh=new Set(["locks","extensions","runtime"]),Ph=new Set(["history","index","search","extensions","locks","runtime"]),Mh=[/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],Dh=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,Fh=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,jh=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 Ds(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let s=Number.parseInt(n,10);return!Number.isFinite(s)||s<=0?t:s}function $h(){return Ds("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",Rh)}function Uh(){return Ds("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",Oh)}function Gh(){return Ds("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",Nh)}function qh(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 Bh(e){let t=0,n=0,s=0;for(let r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"){n+=1;continue}s+=1}return{passed:t,failed:n,skipped:s}}function Fs(e){let t=0,n=0,s=0,r=0;for(let i of e){let o=i.execution_context;!o||o.is_pm_command!==!0||(t+=1,o.is_pm_tracker_read_command===!0&&(n+=1),o.mismatch_detected===!0&&(s+=1),o.auto_pm_context_applied===!0&&(r+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:s,auto_remediated:r}}function Wh(e){let t=e??"project";if(!er.includes(t))throw new g(`Invalid scope "${e}"`,f.USAGE);return t}function sn(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Cn.includes(t))return t;throw new g(`Invalid --pm-context value "${e}". Expected one of: ${Cn.join(", ")}`,f.USAGE)}function zh(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:sn(e.pm_context_mode)}function Hh(e,t){return e==="auto"?t?"tracker":"schema":e}function Vh(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 Kh(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:s}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&s==="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 Yh(e,t){let n={};if(!e)return n;for(let s of e){let r=In(s,t);if(r)for(let[i,o]of Object.entries(r))n[i]=o}return n}function Xh(e,t){if(!e)return[];let n=[];for(let s of e){let r=An(s,t);r&&n.push(...r)}return[...new Set(n)]}function Jh(e){let t=rn(e);return Me(t).some(n=>jt(n)!==null)}function Qh(e){let t=rn(e);return Me(t).some(n=>{let s=jt(n);if(!s)return!1;let r=ns(s);return r?jh.has(r.subcommand):!1})}function tn(e){if(e)return ja.has(e.subcommand)?ue(e.args,$a)?.subcommand:e.subcommand}function dl(e,t){if(e==="npx"||e==="bunx")return be(t)?.command;if(e==="pnpm")return tn(ue(t,Qn));if(e==="npm")return tn(ue(t,Zn));if(e==="yarn")return tn(ue(t,Da));if(e==="bun")return tn(ue(t,Fa))}function ll(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function Os(e){return!e||!tt(e.command)&&!ts(e.command)?!1:Ut(e.args)==="test-all"}var Zh=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),ey=new Set(["npx","bunx"]);function Sl(e){let t=e.split(" ").filter(o=>o.length>0),n=$t(t);if(n.length===0)return!1;let[s,...r]=n,i=Zh.get(s);if(i){let o=r.findIndex(a=>i.test(a));return o>=0?Sl(r.slice(o+1).join(" ")):!1}return tt(s)||nt(s)?Ut(r)==="test-all":s==="node"&&r.length>0&&nt(r[0])?Ut(r.slice(1))==="test-all":ey.has(s)?Os(be(r)):s==="pnpm"?Os(Gt(r)):s==="npm"?Os(qt(r)):!1}function El(e){let t=rn(e);return Me(t).some(n=>Sl(n))}function Cl(e){if(El(e))throw new g('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',f.USAGE)}function rn(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function ty(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function ny(e){let t=/\bpm_path\s*=/.test(e)||/\$env:pm_path\s*=/.test(e),n=/\bpm_global_path\s*=/.test(e)||/\$env:pm_global_path\s*=/.test(e);return t&&n}function sy(e){let t=e.split(" ").filter(i=>i.length>0),n=$t(t);if(n.length===0)return!1;let[s,...r]=n;return s==="vitest"||s.endsWith("/vitest")||s.endsWith("/vitest.mjs")?!0:s==="node"?ry(r):iy(s,r)}function ry(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function iy(e,t){return e==="npx"||e==="bunx"?ll(be(t)?.command):e==="pnpm"||e==="npm"?ll((e==="pnpm"?Gt(t):qt(t))?.command)||dl(e,t)==="vitest":(e==="yarn"||e==="bun")&&dl(e,t)==="vitest"}function Il(e){let t=rn(e);if(Me(t).some(r=>!ty(r)&&sy(r)&&!ny(r)))throw new g('Linked test runner commands must be sandbox-safe: use "node scripts/run-tests.mjs <test|coverage>", use a package-manager script such as "pnpm test", or include PM_PATH=... PM_GLOBAL_PATH=... INLINE in the command string (exporting them in your shell environment is not checked). Example: "PM_PATH=/tmp/pm-x PM_GLOBAL_PATH=/tmp/pm-x-g vitest run".',f.USAGE)}function oy(e){if(El(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function ay(e){return e?e.map(cy):[]}function cy(e){let t=e.trim(),n=qo(t)?Bo(hn(e,"--add"),"--add"):{command:t},s=U(n.command);if(!s)throw new g("--add requires command=<value> or a bare command (path=<value> is optional metadata)",f.USAGE);return Cl(s),Il(s),{command:s,path:U(n.path),scope:Wh(n.scope),timeout_seconds:dy(U(n.timeout_seconds),U(n.timeout)),pm_context_mode:zo(U(n.pm_context_mode),"--add"),env_set:In(U(n.env_set),"--add"),env_clear:An(U(n.env_clear),"--add"),shared_host_safe:Wo(U(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Rn(U(n.assert_stdout_contains)),assert_stdout_regex:On(U(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Rn(U(n.assert_stderr_contains)),assert_stderr_regex:On(U(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Ho(U(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Vo(U(n.assert_json_field_equals),"--add"),assert_json_field_gte:Ko(U(n.assert_json_field_gte),"--add"),note:U(n.note)}}function U(e){let t=e?.trim();return t&&t.length>0?t:void 0}function dy(e,t){if(e&&t&&e!==t)throw new g("--add timeout and timeout_seconds must match when both are provided",f.USAGE);let n=e??t;if(n===void 0)return;let s=Math.floor(He(n,"timeout_seconds"));if(s<=0)throw new g("--add timeout_seconds must be a positive integer",f.USAGE);return s}function ly(e){return e?e.flatMap(t=>{let n=Yo(t,"--add-json");for(let s of n){let r=s.command;if(!r)throw new g("--add-json requires a non-empty command string",f.USAGE);Cl(r),Il(r)}return n}):[]}function uy(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new g("--remove requires command or path value",f.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:path|command)\s*[:=]/i.test(n)||n.startsWith("```")){let s=hn(n,"--remove"),r=s.path??s.command;if(!r?.trim())throw new g("--remove requires command=<value> and/or path=<value>",f.USAGE);return r.trim()}return n}):[]}function my(e){try{e.stdin?.end()}catch{}}function Al(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=cl?t:`${t.slice(0,cl-3)}...`}function Rl(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Ps(e){try{process.stderr.write(`${e}
12
- `)}catch{}}function _y(e,t){if(!Rl(t))return null;let n=Al(e.command),s=Date.now();Ps(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let r=setInterval(()=>{let i=Date.now()-s;Ps(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${i} command="${n}"`)},Uh());return r.unref?.(),r}function py(e,t,n,s){if(!Rl(s))return;let r=Al(e.command),i=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let d=t.exitCode===null?"null":String(t.exitCode),l=c.length>0?` ${c.join(" ")}`:"";Ps(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${d} elapsed_ms=${i}${l} command="${r}"`)}async function ul(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=vl("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 fy(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function gy(e,t){let n=!1;return async()=>{if(n)return;n=!0;let s=e.pid;if(!s||s<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await ul(s);return}try{process.kill(-s,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{ul(s)},$h()),t.forceKillTimer.unref?.()}}function hy(e){return new Promise(t=>{let n=!1,s=null,r=(i,o=!1)=>{n||(n=!0,s&&(clearTimeout(s),s=null),o&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(i))};e.on("exit",(i,o)=>{n||(s=setTimeout(()=>{r({code:i,signal:o},!0)},Gh()),s.unref?.())}),e.on("close",(i,o)=>{r({code:i,signal:o})})})}function yy(e,t,n,s){return vl(e,{cwd:process.cwd(),env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,s]})}async function ml(e){let t=await Ns(e,"r");try{let n=(await t.stat()).size,s=Math.min(n,nn),r=Buffer.alloc(s);return s>0&&await t.read(r,0,s,0),{text:r.toString("utf8"),truncated:n>nn}}finally{await t.close()}}async function by(e,t,n,s,r){let i=Date.now(),o=await kl(G.join(xl(),"pm-linked-test-output-"));try{let a=G.join(o,"stdout.log"),c=G.join(o,"stderr.log"),[d,l]=await Promise.all([Ns(a,"w"),Ns(c,"w")]),u;try{u=yy(e,n,d.fd,l.fd)}finally{await Promise.all([d.close(),l.close()])}my(u);let m={heartbeat:_y(s,r),forceKillTimer:null,timedOutTimer:null},_=gy(u,m),p=!1,h;u.on("error",q=>{h=q.message}),m.timedOutTimer=setTimeout(()=>{p=!0,_()},t),m.timedOutTimer.unref?.();let{code:y,signal:w}=await hy(u);fy(m);let[T,C]=await Promise.all([ml(a),ml(c)]),k=T.truncated||C.truncated,b=k?`
13
- [pm linked-test output truncated at ${nn} bytes per stream; the child process continued to completion]
14
- `:"",R={stdout:`${T.text}${b}`,stderr:C.text,exitCode:y,signal:w,timedOut:p,maxBufferExceeded:!1,outputTruncated:k,spawnError:h};return py(s,R,i,r),R}finally{await Tl(o,{recursive:!0,force:!0})}}function wy(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${nn} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let s=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,r=e.spawnError?.trim()||s||"Linked test command failed.";return n.length===0?r:`${r} ${n.join(" ")}`}function vy(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
15
- `);return Mh.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>Dh.test(n)&&Fh.test(n))}function ky(e){return vy(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function Ty(){return{infra_collision:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function on(e){let t=Ty();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function _l(e,t){for(let[n,s]of Object.entries(t.env_set))En.has(n.toUpperCase())||(e[n]=s);for(let n of t.env_clear)En.has(n.toUpperCase())||delete e[n]}function xy(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 Sy(e,t){let n={...e.env_set,...t.env_set},s=[...new Set([...e.env_clear,...t.env_clear??[]])],r=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:s,shared_host_safe:r}}function Ey(e,t,n){return{env_set:Yh(e,"--env-set"),env_clear:Xh(t,"--env-clear"),shared_host_safe:n===!0}}async function je(e,t,n=!1){if(await x(e)){await Ah(G.dirname(t),{recursive:!0});try{if(n){await al(e,t,{recursive:!0,force:!0});return}await al(e,t,{force:!0})}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")return;throw s}}}async function pl(e,t,n){await je(O(n.projectPmRoot),O(e)),await je(G.join(n.projectPmRoot,"extensions"),G.join(e,"extensions"),!0),await je(O(n.globalPmRoot),O(t)),await je(G.join(n.globalPmRoot,"extensions"),G.join(t,"extensions"),!0)}async function fl(e,t){if(!await x(e))return;let n=await Ls(e,{withFileTypes:!0});for(let s of n){if(Lh.has(s.name))continue;let r=G.join(e,s.name),i=G.join(t,s.name);if(s.isDirectory()){await je(r,i,!0);continue}s.isFile()&&await je(r,i)}}async function Fe(e){if(!await x(e))return 0;let t=0,n=await Ls(e,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||Ph.has(s.name))continue;let r=G.join(e,s.name),i;try{i=await Ls(r,{withFileTypes:!0})}catch{continue}for(let o of i)o.isFile()&&ge.some(a=>o.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function Cy(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function Iy(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let s of n){if(s.startsWith("[")&&s.endsWith("]")){let r=Number.parseInt(s.slice(1,-1),10);if(!Number.isInteger(r)||r<0)return[];t.push(r);continue}t.push(s)}return t}function gl(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let s=Iy(n);if(s.length===0)return{found:!1,value:void 0};let r=e;for(let i of s){if(typeof i=="number"){if(!Array.isArray(r)||i>=r.length)return{found:!1,value:void 0};r=r[i];continue}if(typeof r!="object"||r===null||!Object.prototype.hasOwnProperty.call(r,i))return{found:!1,value:void 0};r=r[i]}return{found:!0,value:r}}function Ay(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 Ry(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?pn(e,t):Object.is(e,t)}function Oy(e,t,n){let s=[];s.push(...hl("stdout",t,e.assert_stdout_contains)),s.push(...yl("stdout",t,e.assert_stdout_regex)),s.push(...hl("stderr",n,e.assert_stderr_contains)),s.push(...yl("stderr",n,e.assert_stderr_regex)),s.push(...Ny(t,e.assert_stdout_min_lines));let r=e.assert_json_field_equals??{},i=e.assert_json_field_gte??{};if(!(Object.keys(r).length>0||Object.keys(i).length>0))return s;let a;try{a=JSON.parse(t)}catch(c){return s.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),s}for(let[c,d]of Object.entries(r)){let l=gl(a,c);if(!l.found){s.push(`assert_json_field_equals missing path "${c}"`);continue}let u=Ay(d);Ry(l.value,u)||s.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(u)} actual=${JSON.stringify(l.value)})`)}for(let[c,d]of Object.entries(i)){let l=gl(a,c);if(!l.found){s.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof l.value!="number"||!Number.isFinite(l.value)){s.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}l.value<d&&s.push(`assert_json_field_gte failed at "${c}" (expected >= ${d}, actual ${l.value})`)}return s}function hl(e,t,n){let s=[];for(let r of n??[])t.includes(r)||s.push(`${e} missing required text: "${r}"`);return s}function yl(e,t,n){let s=[];for(let r of n??[])try{new RegExp(r,"m").test(t)||s.push(`${e} failed regex assertion: /${r}/m`)}catch(i){s.push(`${e} regex assertion is invalid: /${r}/ (${i instanceof Error?i.message:String(i)})`)}return s}function Ny(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var Ly=[{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}];function Py(e,t){let n=`${e}
16
- ${t}`;for(let s of Ly)if(s.regex.test(n))return s.code;return null}function My(e){return{root:e,schemaProjectPmPath:G.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:G.join(e,"schema","global"),trackerProjectPmPath:G.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:G.join(e,"tracker","global")}}async function Dy(e,t=sa){let n={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},n),await t(void 0,{path:e.schemaGlobalPmPath},n),await t(void 0,{path:e.trackerProjectPmPath},n),await t(void 0,{path:e.trackerGlobalPmPath},n)}async function Fy(e,t){t&&(await pl(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),await pl(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await fl(t.projectPmRoot,e.trackerProjectPmPath),await fl(t.globalPmRoot,e.trackerGlobalPmPath))}async function jy(e,t){return{sourceProjectItemCount:t?await Fe(t.projectPmRoot):0,sourceGlobalItemCount:t?await Fe(t.globalPmRoot):0,schemaProjectItemCount:await Fe(e.schemaProjectPmPath),schemaGlobalItemCount:await Fe(e.schemaGlobalPmPath),trackerProjectItemCount:await Fe(e.trackerProjectPmPath),trackerGlobalItemCount:await Fe(e.trackerGlobalPmPath)}}function $y(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,s=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,r=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,i=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount;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:s,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:r,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:i,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==r||e.counts.sourceGlobalItemCount!==i),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots}}function Uy(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?sn(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,s=n?Jh(n):!1,r=s&&n?Qh(n):!1,i=e.options?.autoPmContext===!0&&r,o=i?"auto":zh(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Hh(o,r);return{linkedOverridePmContextMode:t,executionContext:$y({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:s,isPmTrackerReadCommand:r,requestedPmContextMode:o,effectivePmContextMode:a,autoPmContextApplied:i})}}function bl(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Ms(e,t,n,s){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...s?{stdout:s.stdout,stderr:s.stderr}:{},error:n}}function Gy(e){if(!e.linkedTest.command)return bl(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=oy(e.linkedTest.command);if(t)return bl(e.linkedTest,e.executionContext,t);let n=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,s=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(n||s){let r=Kh({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),i=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Ms(e.linkedTest,e.executionContext,`${i} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!Vh(e.linkedTest)?Ms(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function qy(e){let t=Sy(e.runtimeDirectives,e.linkedTest),n={...process.env};return _l(n,e.runtimeDirectives),_l(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&xy(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,n.PM_SOURCE_WORKSPACE_ROOT=process.env.PM_SOURCE_WORKSPACE_ROOT??process.cwd(),n.PM_SOURCE_PM_PATH=e.executionContext.source_project_pm_path,n}function By(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function Wy(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}) while --fail-on-empty-test-run is enabled. Update test selection or disable --fail-on-empty-test-run for this run.`}}function zy(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:Cy(e.execution),failure_category:ky(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:wy(e.execution,e.timeoutMs)}}function Hy(e){if(e.options?.failOnEmptyTestRun===!0){let n=Py(e.execution.stdout,e.execution.stderr);if(n)return Wy({...e,emptyRunSignal:n})}let t=Oy(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Ms(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):By(e.linkedTest,e.executionContext,e.execution)}async function Vy(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,s=await by(t,n,qy(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode);return s.exitCode===0&&!s.timedOut&&!s.maxBufferExceeded?Hy({...e,execution:s}):zy({...e,execution:s,timeoutMs:n})}async function js(e,t,n){let s=[],r=await kl(G.join(xl(),"pm-linked-test-")),i=My(r),o=sn(n?.pmContext),a=n?.progress===!0?"always":"auto",c=Ey(n?.envSet,n?.envClear,n?.sharedHostSafe),d=n?.sourceRoots;try{await Dy(i),await Fy(i,d);let l=await jy(i,d);for(let u=0;u<e.length;u+=1){let m=e[u],_=Uy({linkedTest:m,layout:i,counts:l,sourceRoots:d,runLevelPmContextMode:o,options:n}),p=Gy({linkedTest:m,executionContext:_.executionContext,runLevelPmContextMode:o,linkedOverridePmContextMode:_.linkedOverridePmContextMode,options:n});if(p){s.push(p);continue}s.push(await Vy({linkedTest:m,index:u,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:c,progressMode:a,executionContext:_.executionContext,options:n}))}}finally{await Tl(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return s}async function Ky(e){let{id:t,pmRoot:n,settings:s,typeToFolder:r}=e,i=await Br(n,t,s.id_prefix,s.item_format,r);if(!i)throw new g(`Item ${t} not found`,f.NOT_FOUND);let o=await Wr(i,{schema:s.schema});return{itemId:i.id,tests:o.document.metadata.tests??[],testRuns:o.document.metadata.test_runs??[],changed:!1}}function Yy(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode}function Xy(e,t){let n=[...e];for(let s of t)n.some(r=>Yy(r,s))||n.push(s);return n}function Jy(e,t){return t.length===0?e:e.filter(n=>!t.includes(n.path??"")&&!t.includes(n.command??""))}function Qy(e,t,n){return Jy(Xy(e,t),n)}function Zy(e){return(e.envSet?.length??0)>0||(e.envClear?.length??0)>0||e.sharedHostSafe===!0||e.pmContext!==void 0||e.overrideLinkedPmContext===!0||e.failOnContextMismatch===!0||e.failOnSkipped===!0||e.failOnEmptyTestRun===!0||e.requireAssertionsForPm===!0||e.checkContext===!0||e.autoPmContext===!0}function eb(e){if(Zy(e)&&e.run!==!0)throw new g("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",f.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new g("--match, --only-index, and --only-last require --run",f.USAGE)}async function tb(e){let{id:t,options:n,pmRoot:s,settings:r,typeToFolder:i,adds:o,removes:a}=e;if(o.length===0&&a.length===0)return Ky({id:t,pmRoot:s,settings:r,typeToFolder:i});let c=await ye({pmRoot:s,settings:r,id:t,op:"tests_add",author:J(n.author,r.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(d){let l=d.metadata.tests??[],u=Qy(l,o,a);return d.metadata.tests=u,{changedFields:pn(l,u)?[]:["tests"]}}});return{itemId:c.item.id,tests:c.item.tests??[],testRuns:c.item.test_runs??[],changed:c.changedFields.length>0}}function nb(e,t){eb(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Rs(e.onlyIndex),onlyLast:e.onlyLast},s=e.run===!0?ol(t,n):void 0,r=e.timeout===void 0?void 0:He(e.timeout,"timeout");if(r!==void 0&&r<=0)throw new g("Test timeout must be a positive number",f.USAGE);return{defaultTimeoutSeconds:r,pmContextMode:sn(e.pmContext),runSelection:s,testsToRun:s?.selected??t}}async function sb(e){let{options:t,runOptions:n,pmRoot:s}=e;return t.run!==!0?[]:await js(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,sourceRoots:{projectPmRoot:s,globalPmRoot:Z(process.cwd())}})}function rb(e,t,n){let s=[];if(t&&t.selector!==null&&s.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let r=Fs(n);s.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 s}function ib(e){let t=Bh(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),s=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),r=v(),i=ut(e.options.measure,r);return{run_id:qh("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:r,recorded_at:r,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:s&&s.length>0?s: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}}async function ob(e){let{options:t,pmRoot:n,settings:s,itemId:r,runStartedAt:i,runResults:o,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!i)return;let d=ib({options:t,runStartedAt:i,runResults:o,failOnSkippedTriggered:a});if(s.testing.record_results_to_items!==!0)return d;try{return await en({pmRoot:n,settings:s,itemId:r,author:J(t.author,s.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),d}catch(l){return c.push(`test_result_tracking_failed:${r}:${l instanceof Error?l.message:String(l)}`),d}}function wl(e,t,n){let s;if(e.metricBelow!==void 0){let r=e.metricBelow.indexOf("="),i=e.metricBelow.slice(0,r).trim(),o=e.metricBelow.slice(r+1).trim(),a=Number(o);if(r<=0||i.length===0||o.length===0||!Number.isFinite(a))throw new g("--metric-below must use name=value",f.USAGE);s=Wd(t,i,a)}return{measurements:n?.measurements,metric_below:s,metric_diff:e.metricDiff===void 0?void 0:zd(t,e.metricDiff)}}async function Ol(e,t,n){let s=jr(),r=I(process.cwd(),n.path);if(!await x(O(r)))throw new g(`Tracker is not initialized at ${r}. Run pm init first.`,f.NOT_FOUND);let i=await N(r);if((t.measure?.length??0)>0&&t.run!==!0)throw new g("--measure requires --run",f.USAGE);ut(t.measure,"validation"),wl(t,[],void 0);let o=V(i,W()),a=await s.resolveList(t.add,"--add"),c=await s.resolveList(t.addJson,"--add-json"),d=await s.resolveList(t.remove,"--remove"),l=[...ay(a),...ly(c)],u=uy(d),m=await tb({id:e,options:t,pmRoot:r,settings:i,typeToFolder:o.type_to_folder,adds:l,removes:u}),_=nb(t,m.tests),p=t.run===!0?v():void 0,h=await sb({options:t,runOptions:_,pmRoot:r}),y=on(h),w=t.run===!0&&t.failOnSkipped===!0&&h.some(R=>R.status==="skipped"),T=rb(t,_.runSelection,h),C=await ob({options:t,pmRoot:r,settings:i,itemId:m.itemId,runStartedAt:p,runResults:h,failOnSkippedTriggered:w,warnings:T}),k=C?As([...m.testRuns,C]):m.testRuns,b=wl(t,k,C);return{ok:h.every(R=>R.status!=="failed")&&w!==!0,id:m.itemId,tests:m.tests,run_results:h,failure_categories:y,selection:_.runSelection?{selector:_.runSelection.selector,requested:_.runSelection.requested,selected_indexes:_.runSelection.selected_indexes,selected_count:_.runSelection.selected_count,skipped_count:_.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:w?!0:void 0,warnings:T.length>0?T:void 0,changed:m.changed,count:m.tests.length,...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]="7fea0ecb-35e2-5d40-931f-ffdd1a465fdc")}catch{}})();var ab=(e,t)=>{if(e===void 0)return;let n=vt(e,t);if(!n){let s=t.definitions.map(r=>r.id);throw new g(`Invalid --status value "${e}". Allowed: ${s.join(", ")}`,f.USAGE)}return n},cb=e=>{if(e===void 0)return;let t=He(e,"timeout");if(t<=0)throw new g("timeout must be a positive number",f.USAGE);return t},Nl=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new g(`${t} must be a non-negative integer`,f.USAGE);return n},db=e=>e instanceof Error?e.message:String(e),lb=()=>{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)}`},ub=e=>e.trim().replaceAll(/\s+/g," "),mb=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),_b=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),pb=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},an=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Ll=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),fb=e=>typeof e=="number"?e:void 0,gb=e=>{let t={assert_stdout_contains:an(e.assert_stdout_contains),assert_stdout_regex:an(e.assert_stdout_regex),assert_stderr_contains:an(e.assert_stderr_contains),assert_stderr_regex:an(e.assert_stderr_regex),assert_stdout_min_lines:fb(e.assert_stdout_min_lines),assert_json_field_equals:Ll(e.assert_json_field_equals),assert_json_field_gte:Ll(e.assert_json_field_gte)};return JSON.stringify(t)},hb=e=>{let t=$s(e.command);return t!==void 0?`command:${e.scope}:${ub(t)}`:`path:${e.scope}:${$s(e.path)??""}`},Pl=e=>{let t=mb(e.env_set),n=_b(e.env_clear),s=pb(e.pm_context_mode),r=e.shared_host_safe===!0?"true":"false",i=gb(e);return`${hb(e)}:${t}:${n}:${s}:${r}:${i}`},yb=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,bb=e=>{let t=0,n=0,s=0;for(let r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"){n+=1;continue}s+=1}return{passed:t,failed:n,skipped:s}},wb=(e,t)=>{for(let[n,s]of Object.entries(t))e[n]+=s},cn=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
17
- `)}catch{}},vb=async(e,t,n)=>{let s=[],r=0;for(let i of e){let o=await Ol(i.id,{run:!1},{...t,path:n});r+=o.tests.length,s.push({item:i,tests:o.tests})}return{itemTests:s,linkedTests:r}},kb=async e=>{let t=ee(e.settings.schema),n=V(e.settings,W()),s=ab(e.options.status,t),r=Nl(e.options.limit,"--limit"),i=Nl(e.options.offset,"--offset")??0,a=(await St(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>s?d.status===s:!0).sort((d,l)=>d.id.localeCompare(l.id));return{filteredItems:r===void 0?a.slice(i):a.slice(i,i+r),statusFilter:s,limitFilter:r,offsetFilter:i}},Tb=e=>{let t=new Map;for(let{tests:n}of e)for(let s of n){let r=Pl(s);if(!t.has(r)){t.set(r,s.timeout_seconds);continue}t.set(r,yb(t.get(r),s.timeout_seconds))}return t},xb=async(e,t)=>{let n=[],s=e.tests.map(l=>{let u=Pl(l),m=t.seenTestKeys.has(u);if(!m){t.seenTestKeys.add(u);let _=t.effectiveTimeoutByKey.get(u);n.push(_===void 0?l:{...l,timeout_seconds:_})}return{test:l,key:u,duplicate:m}}),r=n.length>0?await js(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}):[],i=0,o=s.map(({test:l,key:u,duplicate:m})=>{if(!m){let _=r[i];return i+=1,_}return{command:l.command,path:l.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),a=bb(o),c=on(o),d=await Cb(e,a,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:d,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:o,failure_categories:c}}},Sb=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),Eb=e=>e?!0:void 0,Cb=async(e,t,n)=>{if(!n.trackingEnabled)return[];try{let s=Sb(t,n.options);await en({pmRoot:n.pmRoot,settings:n.settings,itemId:e.item.id,author:n.trackingAuthor,message:`Track test-all run summary (${n.trackingRunId})`,entry:{run_id:n.trackingRunId,kind:"test-all",status:s?"failed":"passed",started_at:n.runStartedAt,finished_at:v(),recorded_at:v(),attempt:n.trackingAttempt,resumed_from:n.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:Eb(n.options.failOnSkipped===!0&&t.skipped>0)}})}catch(s){return[`test_result_tracking_failed:${e.item.id}:${db(s)}`]}return[]},Ib=()=>{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},$s=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},Ab=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:Z(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:Tb(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:J(e.options.author,e.settings.author_default),trackingRunId:lb(),trackingAttempt:Ib(),trackingResumedFrom:$s(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),Rb=(e,t,n)=>{let s={results:[],passed:0,failed:0,skipped:0,failureCategories:on([]),trackingWarnings:[]},r=e.failOnEmptyTestRun===!0&&t===0;return r&&(s.failed+=1,s.failureCategories.empty_run+=1,s.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:s,failOnEmptyTestRunTriggered:r}},Ob=async(e,t,n)=>{for(let[s,r]of e.entries()){cn(t.options,`item ${s+1}/${e.length} start id=${r.item.id} linked_tests=${r.tests.length}`);let i=await xb(r,t);wb(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),cn(t.options,`item ${s+1}/${e.length} end id=${r.item.id} status=${i.failed===0?"passed":"failed"} passed=${i.passed} failed=${i.failed} skipped=${i.skipped}`)}},Nb=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(r=>r.run_results),s=Fs(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${s.checked_pm_commands};tracker_read_commands=${s.tracker_read_commands};mismatches=${s.mismatches};auto_remediated=${s.auto_remediated}`)},Lb=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}),Pb=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(" "),Mb=async(e,t)=>{let n=I(process.cwd(),t.path);if(!await x(O(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,f.NOT_FOUND);let s=await N(n),r=await kb({pmRoot:n,settings:s,options:e}),i=cb(e.timeout),o=v(),a=await vb(r.filteredItems,t,n);return cn(e,Pb({...r,linkedTests:a.linkedTests})),{pmRoot:n,settings:s,filteredItems:r.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:i,runStartedAt:o}},Db=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}},bE=async(e,t)=>{let n=await Mb(e,t),{accumulation:s,failOnEmptyTestRunTriggered:r}=Rb(e,n.linkedTests,n.filteredItems),i=Ab({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await Ob(n.itemTests,i,s),Nb(e,s);let o=Db({options:e,accumulation:s,failOnEmptyTestRunTriggered:r});return cn(e,`end status=${o.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`),Lb({ok:o.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:s,failOnSkippedTriggered:o.failOnSkippedTriggered,failOnEmptyTestRunTriggered: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]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function kE(e){return yr("in_progress",e)??e.open_status}import mw from"node:os";import $e from"node:fs/promises";import{spawn as $l}from"node:child_process";import{createHash as Fb,randomBytes as jb}from"node:crypto";import mt 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]="0224a672-e326-5555-a4b4-1fa3550d9e61")}catch{}})();var Ul=new Set(["queued","running"]),Bs=new Set(["passed","failed","stopped","canceled"]),$b=3e3,Ub=3e3,Gb=3e4,Gl=100,Ml=100;function ql(){return Date.now()}function Bl(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function qb(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function Bb(){let e=Date.now().toString(36),t=jb(3).toString("hex");return`tr-${e}-${t}`}function Wb(e,t,n){let s={kind:e,command:Bl(t),pm_root:mt.resolve(n)};return Fb("sha256").update(JSON.stringify(s)).digest("hex")}function Ue(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function zb(e){await de(lr(e)),await de(un(e)),await de(ur(e)),await de(mr(e)),await de(fr(e))}async function Wl(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new g(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,f.GENERIC_FAILURE)}}async function ne(e,t){let n={...t,updated_at:v()};await se(mn(e,t.id),`${JSON.stringify(n,null,2)}
18
- `)}async function Ge(e,t){let n=mn(e,t),s=await j(n);return s?Wl(s,n):null}async function Hb(e){let t=un(e);return await x(t)?(await $e.readdir(t,{withFileTypes:!0})).filter(s=>s.isFile()&&s.name.endsWith(".json")).map(s=>mt.join(t,s.name)).sort((s,r)=>r.localeCompare(s)):[]}function Vb(e){let t=e.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(t)return Number.parseInt(t[1],10)*1024}async function Kb(e){if(process.platform==="linux")try{let t=await $e.readFile(`/proc/${e}/status`,"utf8");return Vb(t)}catch{return}}function Yb(e){let t=e.lastIndexOf(")");if(t<0)return{};let s=e.slice(t+2).trim().split(/\s+/),r=Number.parseInt(s[11],10),i=Number.parseInt(s[12],10);return!Number.isFinite(r)||!Number.isFinite(i)?{}:{cpu_user_seconds:r/Ml,cpu_system_seconds:i/Ml}}async function Xb(e){if(process.platform!=="linux")return{};try{let t=await $e.readFile(`/proc/${e}/stat`,"utf8");return Yb(t)}catch{return{}}}async function Gs(e){let t=e.child_pid??e.worker_pid;if(!Ue(t))return;let n=await Kb(t),s=await Xb(t),r=e.started_at?Date.parse(e.started_at):Number.NaN,i=Number.isFinite(r)?Math.max(0,(ql()-r)/1e3):void 0;return{recorded_at:v(),rss_bytes:n,cpu_user_seconds:s.cpu_user_seconds,cpu_system_seconds:s.cpu_system_seconds,uptime_seconds:i}}function Us(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Jb(e,t){if(!t||typeof t!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};let n=t;if(e==="test-all"){let a=n.totals??{};return{summary:{items:typeof a.items=="number"?a.items:void 0,linked_tests:typeof a.linked_tests=="number"?a.linked_tests:void 0,passed:Us(a.passed),failed:Us(a.failed),skipped:Us(a.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}let s=Array.isArray(n.run_results)?n.run_results:[],r=0,i=0,o=0;for(let a of s){if(!a||typeof a!="object")continue;let c=a.status;if(c==="passed"){r+=1;continue}if(c==="failed"){i+=1;continue}o+=1}return{summary:{passed:r,failed:i,skipped:o,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}function Qb(e){let t=e.trim();if(t.length===0)return null;let n=t.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){let d=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:d,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:v(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}let s=t.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!s)return null;let r=Number.parseInt(s[1],10),i=Number.parseInt(s[2],10),o=s[4]?Number.parseInt(s[4],10):void 0,a=t.match(/\scommand="((?:\\.|[^"\\])*)"/),c=a?a[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:r,linked_test_total:i,current_command:c,elapsed_ms:Number.isFinite(o)?o:void 0,heartbeat_at:v(),phase:s[3]?.toLowerCase()==="end"?"finished":"running"}}function Zb(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.length>0)}function qs(e,t){if(t<=0)return[];let n=Zb(e);return n.length<=t?n:n.slice(n.length-t)}async function zl(e){let t=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(t&&t.length>0){let r=mt.resolve(e,t);if(await x(r))return r}let n=mt.resolve(e,"dist","cli.js");if(await x(n))return n;let s=process.argv[1]?.trim();if(s&&s.length>0){let r=mt.resolve(e,s);if(await x(r))return r}throw new g("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",f.GENERIC_FAILURE)}async function _t(e,t){if(!Ul.has(t.status)||Ue(t.worker_pid)||t.finished_at)return t;let s={...t,status:"failed",finished_at:v(),error:t.error??"Background test run worker exited before writing terminal status."};return await ne(e,s),s}async function Ws(e){await zb(e.pmRoot);let t=Bl(e.commandArgs);if(t.length===0)throw new g("Background test run requires command arguments.",f.USAGE);let n=Wb(e.kind,t,e.pmRoot),s=await Hs(e.pmRoot,{});for(let l of s){let u=await _t(e.pmRoot,l);if(u.fingerprint===n&&!(!Ul.has(u.status)||!Ue(u.worker_pid)))return{started:!1,run:{...u,duplicate_of:u.id},duplicate_of:u.id}}let r=Bb(),i=v(),o=_r(e.pmRoot,r),a=pr(e.pmRoot,r),c=gr(e.pmRoot,r);await $e.writeFile(o,"","utf8"),await $e.writeFile(a,"","utf8");let d={id:r,kind:e.kind,status:"queued",created_at:i,updated_at:i,requested_by:e.requestedBy,fingerprint:n,command_args:t,command_label:qb(t),pm_root:e.pmRoot,global_pm_root:e.globalPmRoot,target_id:e.targetId,status_filter:e.statusFilter,attempt:typeof e.attempt=="number"&&Number.isFinite(e.attempt)&&e.attempt>=1?Math.floor(e.attempt):1,resumed_from:e.resumedFrom,resumed_by:e.resumedBy,stdout_path:o,stderr_path:a,result_path:c,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:i}};return await ne(e.pmRoot,d),{started:!0,run:d}}async function zs(e){let t=await Ge(e.pmRoot,e.runId);if(!t)throw new g(`Background test run ${e.runId} not found`,f.NOT_FOUND);if(Bs.has(t.status))throw new g(`Background test run ${t.id} is already terminal (${t.status}).`,f.CONFLICT);let n=await zl(process.cwd()),s=[];e.noExtensions===!0&&s.push("--no-extensions"),s.push("--path",t.pm_root,"test-runs-worker",t.id);let r={...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:t.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(t.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:t.resumed_from??"",FORCE_COLOR:"0"},i=$l(process.execPath,[n,...s],{cwd:process.cwd(),env:r,detached:!0,stdio:"ignore",windowsHide:!0});i.unref();let o={...t,status:"queued",worker_pid:i.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:v()}};return await ne(e.pmRoot,o),o}async function Dl(e,t,n){await e,await $e.appendFile(t,n,"utf8")}function Hl(e,t){let n=Number.parseInt(process.env[e]??"",10);return Number.isFinite(n)&&n>0?n:t}function ew(e){return{...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,FORCE_COLOR:"0"}}function tw(e,t){return t?["--no-extensions",...e.command_args]:[...e.command_args]}function nw(e,t){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await ne(e,t)}catch{}})},async flush(){await n}}}function Fl(e,t){try{e.kill(t)}catch{}}async function sw(e,t,n,s){if(n.stopRequested)return;n.stopRequested=!0,e.stop_requested_at=v(),e.progress={...e.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:v()},s(),Fl(t,"SIGTERM"),setTimeout(()=>Fl(t,"SIGKILL"),Hl("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",Ub)).unref?.()}function rw(e,t,n){return{phase:n,message:e,heartbeat_at:v(),item_index:t.item_index,item_total:t.item_total,item_id:t.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function iw(e,t,n,s){return{phase:s,message:e,heartbeat_at:v(),item_index:n.item_index??t.progress?.item_index,item_total:n.item_total??t.progress?.item_total,item_id:n.item_id??t.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function jl(e,t,n){let s=Qb(t);if(!s)return!1;let r=e.progress?.phase==="stopping"?"stopping":"running";return e.progress=s.item_id?rw(t,s,r):iw(t,e,s,r),s.phase==="finished"&&!n&&(e.progress.phase="running"),!0}function ow(e){if(e.trim().length===0)return null;try{return JSON.parse(e)}catch{return null}}function aw(e,t){return t?"stopped":e.exit_code===0&&(e.summary?.failed??0)===0&&e.summary?.fail_on_skipped_triggered!==!0?"passed":"failed"}function cw(e,t){return{phase:"finished",message:t?"Background run stopped.":`Background run finished with status=${e.status}.`,heartbeat_at:v(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function dw(e,t,n){if(t!==null){await se(e.result_path,`${JSON.stringify(t,null,2)}
19
- `);return}await se(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:qs(n,Gl)},null,2)}
20
- `)}async function Vl(e,t,n=!1){let s=await Ge(e,t);if(!s)throw new g(`Background test run ${t} not found`,f.NOT_FOUND);let r={...s,status:"running",started_at:s.started_at??v(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:v()}},i=await zl(process.cwd()),o=ew(r);await ne(e,r);let a=tw(r,n),c=$l(process.execPath,[i,...a],{cwd:process.cwd(),env:o,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});r.child_pid=c.pid;let d=nw(e,r),l=d.schedule,u=Promise.resolve(),m=Promise.resolve(),_="",p="",h={stopRequested:!1},y=()=>{sw(r,c,h,l)};process.on("SIGTERM",y),process.on("SIGINT",y);let w=setInterval(()=>{(async()=>(r.resource=await Gs(r),r.progress.heartbeat_at=v(),l()))()},Hl("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",$b));w.unref?.(),c.stdout?.on("data",q=>{let D=q.toString("utf8");_+=D,u=Dl(u,r.stdout_path,D)}),c.stderr?.on("data",q=>{let D=q.toString("utf8");m=Dl(m,r.stderr_path,D),p+=D;let $=p.split(/\r?\n/);p=$.pop();let Y=!1;for(let ce of $){let S=ce.trimEnd();S.length>0&&jl(r,S,h.stopRequested)&&(Y=!0)}Y&&l()});let T=null,C=null;try{({code:T,signal:C}=await new Promise(q=>{c.on("close",(D,$)=>{q({code:D,signal:$})})}))}finally{clearInterval(w),process.off("SIGTERM",y),process.off("SIGINT",y)}await u,await m;let k=p.trimEnd();k.length>0&&jl(r,k,h.stopRequested)&&l(),p="";let b=ow(_),R=Jb(r.kind,b);return r.summary=R.summary,r.exit_code=typeof T=="number"?T:void 0,r.signal=C??void 0,r.finished_at=v(),r.status=aw(r,h.stopRequested),r.progress=cw(r,h.stopRequested),r.resource=await Gs(r),await dw(r,b,_),await ne(e,r),await d.flush(),r}async function Hs(e,t){let n=await Hb(e),s=[];for(let c of n){let d=await j(c);if(!d)continue;let l=await Wl(d,c);s.push(l)}let r=[];for(let c of s)r.push(await _t(e,c));let o=(t.status?r.filter(c=>c.status===t.status):r).sort((c,d)=>{let l=Date.parse(d.updated_at)-Date.parse(c.updated_at);return Number.isFinite(l)&&l!==0?l:d.id.localeCompare(c.id)}),a=typeof t.limit=="number"&&t.limit>=0?t.limit:void 0;return a===void 0?o:o.slice(0,a)}async function Kl(e,t){let n=await Ge(e,t);if(!n)throw new g(`Background test run ${t} not found`,f.NOT_FOUND);let s=await _t(e,n),r=Ue(s.worker_pid),i=Ue(s.child_pid);s.status==="running"&&!i&&!s.finished_at&&!r&&(s.status="failed",s.finished_at=v(),s.error=s.error??"Background run process exited unexpectedly.",await ne(e,s)),s.status==="running"&&(s.resource=await Gs(s),await ne(e,s));let o=s.progress?.heartbeat_at,a=o?Date.parse(o):Number.NaN,c=Number.isFinite(a)?Math.max(0,ql()-a):void 0,d=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(d)&&d>0?d:Gb,u=s.status==="running"?c!==void 0&&c>l?"stale":"healthy":"inactive";return{run:s,health:{state:u,last_heartbeat_at:o,heartbeat_lag_ms:c,worker_alive:r,child_alive:i}}}function lw(e,t){let n=t?"SIGKILL":"SIGTERM";if(!Ue(e.worker_pid)||!e.worker_pid)return"none";try{return process.kill(e.worker_pid,n),n}catch{return"none"}}function uw(e,t){return{phase:"stopping",message:t==="none"?"Run marked stopped.":`Stop requested via ${t}.`,heartbeat_at:v(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function Yl(e,t,n=!1){let s=await Ge(e,t);if(!s)throw new g(`Background test run ${t} not found`,f.NOT_FOUND);let r=await _t(e,s);if(Bs.has(r.status))return{run:r,signal_sent:"none"};let i=lw(r,n);return i==="none"&&(r.status="stopped",r.finished_at=r.finished_at??v()),r.stop_requested_at=v(),r.progress=uw(r,i),await ne(e,r),{run:r,signal_sent:i}}async function Xl(e,t,n,s=!1){let r=await Ge(e,t);if(!r)throw new g(`Background test run ${t} not found`,f.NOT_FOUND);let i=await _t(e,r);if(!Bs.has(i.status))throw new g(`Background test run ${t} is not terminal and cannot be resumed.`,f.CONFLICT);let o=await Ws({pmRoot:i.pm_root,globalPmRoot:i.global_pm_root,kind:i.kind,commandArgs:i.command_args,requestedBy:n,targetId:i.target_id,statusFilter:i.status_filter,resumedFrom:i.id,resumedBy:n,attempt:i.attempt+1});if(!o.started)return o.run;let a=await zs({pmRoot:e,runId:o.run.id,noExtensions:s}),c={...i,resumed_by:a.id};return await ne(e,c),a}async function Jl(e,t,n,s){let r=await Ge(e,t);if(!r)throw new g(`Background test run ${t} not found`,f.NOT_FOUND);let i=typeof s=="number"&&Number.isFinite(s)&&s>=0?Math.floor(s):Gl,o=n==="stdout"||n==="both"?await j(r.stdout_path)??"":"",a=n==="stderr"||n==="both"?await j(r.stderr_path)??"":"";return{run:r,stream:n,tail:i,stdout:n==="stdout"||n==="both"?qs(o,i):[],stderr:n==="stderr"||n==="both"?qs(a,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]="8f02f498-5cee-59fa-9f4e-fd882c58d401")}catch{}})();var _w=["queued","running","passed","failed","stopped","canceled"],pw=["stdout","stderr","both"];function fw(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(_w.includes(t))return t;throw new g(`Invalid --status value "${e}"`,f.USAGE)}function gw(e){if(e===void 0||e.trim().length===0)return"stderr";let t=e.trim().toLowerCase();if(pw.includes(t))return t;throw new g(`Invalid --stream value "${e}"`,f.USAGE)}function hw(){try{let e=mw.userInfo().username.trim();if(e.length>0)return e}catch{}}function Ql(e,t){let n=[e,kr(),t,process.env.USER,process.env.LOGNAME,process.env.USERNAME,hw()];for(let s of n){if(typeof s!="string")continue;let r=s.trim();if(r.length>0)return r}return"unknown"}async function xe(e){if(!await x(O(e)))throw new g(`Tracker is not initialized at ${e}. Run pm init first.`,f.NOT_FOUND)}async function BE(e,t){let n=I(process.cwd(),t.path),s=Z(process.cwd());await xe(n);let r=await N(n),i=Ql(e.author,r.author_default),o=await Ws({pmRoot:n,globalPmRoot:s,kind:e.kind,commandArgs:e.commandArgs,requestedBy:i,targetId:e.targetId,statusFilter:e.statusFilter});return o.started?{started:!0,run:await zs({pmRoot:n,runId:o.run.id,noExtensions:e.noExtensions===!0})}:{started:!1,duplicate_of:o.duplicate_of,run:o.run}}async function WE(e,t){let n=I(process.cwd(),t.path);await xe(n);let s=fw(e.status),r=yn(e.limit,"limit"),i=await Hs(n,{status:s,limit:r});return{runs:i,count:i.length,filters:{status:s,limit:r}}}async function zE(e,t){let n=I(process.cwd(),t.path);await xe(n);let s=await Kl(n,e);return{run:s.run,health:s.health}}async function HE(e,t,n){let s=I(process.cwd(),n.path);await xe(s);let r=gw(t.stream),i=yn(t.tail,"tail"),o=await Jl(s,e,r,i);return{run:o.run,stream:o.stream,tail:o.tail,stdout:o.stdout,stderr:o.stderr}}async function VE(e,t,n){let s=I(process.cwd(),n.path);await xe(s);let r=await Yl(s,e,t.force===!0);return{run:r.run,signal_sent:r.signal_sent}}async function KE(e,t,n){let s=I(process.cwd(),n.path);await xe(s);let r=await N(s),i=Ql(t.author,r.author_default),o=await Xl(s,e,i,t.noExtensions===!0);return{resumed_from:e,run:o}}async function YE(e,t){let n=I(process.cwd(),t.path);await xe(n);let s=await Vl(n,e,t.noExtensions===!0);return{id:s.id,status:s.status,exit_code:s.exit_code}}export{ia as a,tu as b,Cw as c,Iw as d,ca as e,Jw as f,wu as g,fa as h,iv as i,Je as j,ov as k,gv as l,hv as m,Ze as n,yv as o,bv as p,uk as q,mk as r,Ma as s,es as t,N_ as u,pT as v,fT as w,yT as x,bT as y,wT as z,Xc as A,xp as B,ys as C,Sp as D,Ep as E,Cp as F,OT as G,NT as H,Pp as I,rd as J,bs as K,od as L,jp as M,$p as N,DT as O,FT as P,jT as Q,$T as R,Up as S,cd as T,GT as U,dd as V,qp as W,at as X,Vp as Y,ud as Z,Xp as _,HT as $,dx as aa,Fd as ba,jd as ca,Tg as da,$d as ea,Rx as fa,Ud as ga,Ox as ha,Xt as ia,Ug as ja,jx as ka,Ss as la,$x as ma,Es as na,Gg as oa,ut as pa,Wd as qa,zd as ra,dS as sa,_S as ta,Kd as ua,xS as va,Fs as wa,ky as xa,on as ya,Cy as za,js as Aa,Ol as Ba,bE as Ca,kE as Da,BE as Ea,WE as Fa,zE as Ga,HE as Ha,VE as Ia,KE as Ja,YE as Ka};
21
- //# sourceMappingURL=chunk-KFLK5TRH.js.map