@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,2 +0,0 @@
1
- import{_ as u}from"./chunk-ZJIMJHDB.js";(function(){try{var a=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new a.Error().stack;e&&(a._sentryDebugIds=a._sentryDebugIds||{},a._sentryDebugIds[e]="f73e79d8-2a65-5a25-8c6f-ec9b06651634")}catch{}})();function i(a){return[...new Set(Array.from(a,e=>e.trim()).filter(e=>e.length>0))]}(function(){try{var a=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new a.Error().stack;e&&(a._sentryDebugIds=a._sentryDebugIds||{},a._sentryDebugIds[e]="8de867f9-e4d7-5c05-bae5-c3845a2280b7")}catch{}})();function n(a){return a.startsWith("--")?`--${a.slice(2).replaceAll("_","-")}`:a}function c(a){let e=new Map;for(let l of a){let t=n(l.flag),g=e.get(t)??new Set;l.flag!==t&&g.add(l.flag);for(let f of l.aliases??[])f!==t&&g.add(f);e.set(t,g)}return a.map(l=>{let t=n(l.flag);if(l.flag!==t)return l;let g=i([...l.aliases??[],...e.get(t)]).filter(f=>f!==t);return g.length===0?l:{...l,aliases:g}})}function ee(a){let e=c(a),l=new Set(e.map(t=>t.flag));return e.filter(t=>{let g=n(t.flag);return t.flag===g||!l.has(g)})}var d=u.map(a=>({flag:a.flag,...a.aliases?{aliases:[...a.aliases]}:{},...a.value_name?{value_name:a.value_name}:{}})),le=[...d,{flag:"--version"}],C=[{flag:"--filter-reviewer-missing"},{flag:"--filter-risk-missing"},{flag:"--filter-confidence-missing"},{flag:"--filter-sprint-missing"},{flag:"--filter-release-missing"},{flag:"--has-notes"},{flag:"--no-notes"},{flag:"--has-learnings"},{flag:"--no-learnings"},{flag:"--has-files"},{flag:"--no-files"},{flag:"--filter-files-missing"},{flag:"--has-docs"},{flag:"--no-docs"},{flag:"--filter-docs-missing"},{flag:"--has-tests"},{flag:"--no-tests"},{flag:"--has-comments"},{flag:"--no-comments"},{flag:"--has-deps"},{flag:"--no-deps"},{flag:"--has-body"},{flag:"--empty-body"},{flag:"--has-linked-command"},{flag:"--no-linked-command"}],h=[{flag:"--filter-reviewer-missing"},{flag:"--filter-risk-missing"},{flag:"--filter-confidence-missing"},{flag:"--filter-sprint-missing"},{flag:"--filter-release-missing"},{flag:"--filter-has-notes"},{flag:"--filter-no-notes"},{flag:"--filter-has-learnings"},{flag:"--filter-no-learnings"},{flag:"--filter-has-files"},{flag:"--filter-no-files"},{flag:"--filter-has-docs"},{flag:"--filter-no-docs"},{flag:"--filter-has-tests"},{flag:"--filter-no-tests"},{flag:"--filter-has-comments"},{flag:"--filter-no-comments"},{flag:"--filter-has-deps"},{flag:"--filter-no-deps"},{flag:"--filter-has-body"},{flag:"--filter-empty-body"},{flag:"--filter-has-linked-command"},{flag:"--filter-no-linked-command"},{flag:"--ids",list:!0},{flag:"--limit"},{flag:"--offset"}],k=p([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--status",list:!0},{flag:"--type",list:!0},{flag:"--tag",aliases:["--tags"],list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--today"},{flag:"--recent"},{flag:"--updated-after"},{flag:"--updated-before"},{flag:"--created-after"},{flag:"--created-before"},{flag:"--ids",list:!0},{flag:"--assignee",list:!0},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--parent"},{flag:"--sprint",list:!0},{flag:"--release",list:!0},{flag:"--filter-ac-missing"},{flag:"--filter-estimates-missing",aliases:["--filter-estimate-missing"]},{flag:"--filter-resolution-missing"},{flag:"--filter-metadata-missing"},...C,{flag:"--limit"},{flag:"--offset"},{flag:"--after"},{flag:"--no-truncate"},{flag:"--compact"},{flag:"--brief"},{flag:"--full"},{flag:"--fields",list:!0},{flag:"--sort"},{flag:"--order"},{flag:"--tree"},{flag:"--tree-depth"},{flag:"--tree_depth"},{flag:"--include-body"},{flag:"--strict-read"},{flag:"--format"},{flag:"--stream"}],new Set(["--limit","--token-budget","--offset","--after","--no-truncate","--compact","--brief","--full","--fields","--include-body","--strict-read"])),G=[{flag:"--group-by",list:!0},{flag:"--count"},{flag:"--completion"},{flag:"--sum"},{flag:"--avg"},{flag:"--include-unparented"},{flag:"--include_unparented"},{flag:"--status",list:!0},{flag:"--type",list:!0},{flag:"--tag",list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--assignee",list:!0},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--parent"},{flag:"--sprint",list:!0},{flag:"--release",list:!0}],F=[{flag:"--add",aliases:["--comment","--body"]},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--author"},{flag:"--message"},{flag:"--force"}];function p(a,e){return a.map(l=>e.has(l.flag)?{...l,cursor_semantics:"presentation"}:l)}var w=[{flag:"--add",aliases:["--note"]},{flag:"--add-json"},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--since"},{flag:"--event-type"},{flag:"--include-meta"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],I=[{flag:"--add",aliases:["--learning"]},{flag:"--limit"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],M=[{flag:"--add"},{flag:"--add-glob"},{flag:"--remove"},{flag:"--migrate"},{flag:"--note"},{flag:"--list"},{flag:"--append-stable"},{flag:"--validate-paths"},{flag:"--scope"},{flag:"--limit"},{flag:"--offset"},{flag:"--no-truncate"},{flag:"--strict-read"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],D=[{flag:"--add"},{flag:"--add-glob"},{flag:"--remove"},{flag:"--migrate"},{flag:"--note"},{flag:"--list"},{flag:"--validate-paths"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],P=[{flag:"--limit"},{flag:"--compact"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--diff"},{flag:"--field"},{flag:"--verify"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--format"}],X=[{flag:"--dry-run"},{flag:"--output"},{flag:"--item-path"},{flag:"--prefer"}],U=[{flag:"--literal"},{flag:"--regex"},{flag:"--replacement"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],j=[{flag:"--all"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],H=[{flag:"--event",repeatable:!0},{flag:"--all-actionable"},{flag:"--attributed-author",aliases:["--attributed_author"]},{flag:"--reviewer"},{flag:"--reason"}],z=[{flag:"--before"},{flag:"--ids",list:!0},{flag:"--all-over",value_type:"number"},{flag:"--closed"},{flag:"--all-streams"},{flag:"--min-entries",value_type:"number"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Y=[{flag:"--description"},{flag:"--default-status",aliases:["--default_status"]},{flag:"--folder"},{flag:"--alias"},{flag:"--role"},{flag:"--order"},{flag:"--type"},{flag:"--commands"},{flag:"--cli-flag"},{flag:"--required"},{flag:"--required-on-create"},{flag:"--no-allow-unset"},{flag:"--required-types"},{flag:"--infer"},{flag:"--min-count"},{flag:"--apply"},{flag:"--to"},{flag:"--migration-id",aliases:["--migration_id"]},{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],q=[{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],B=[{flag:"--title"},{flag:"--description"},{flag:"--scope"},{flag:"--parent"},{flag:"--related"},{flag:"--blocks"},{flag:"--blocked-by",aliases:["--blocked_by"]},{flag:"--harness"},{flag:"--mode"},{flag:"--resume-context",aliases:["--resume_context"]},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--priority"},{flag:"--status",short:"-s"},{flag:"--create-mode",aliases:["--create_mode"]},{flag:"--deadline"},{flag:"--estimate",aliases:["--estimated-minutes","--estimated_minutes"]},{flag:"--acceptance-criteria",aliases:["--acceptance_criteria","--ac"],repeatable:!0},{flag:"--definition-of-ready",aliases:["--definition_of_ready"]},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now",aliases:["--why_now"]},{flag:"--assignee"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--blocked-reason",aliases:["--blocked_reason"]},{flag:"--unblock-note",aliases:["--unblock_note"]},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps",aliases:["--repro_steps"]},{flag:"--resolution"},{flag:"--expected-result",aliases:["--expected_result","--expected"]},{flag:"--actual-result",aliases:["--actual_result","--actual"]},{flag:"--affected-version",aliases:["--affected_version"]},{flag:"--fixed-version",aliases:["--fixed_version"]},{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact",aliases:["--customer_impact"]},{flag:"--comment",repeatable:!0},{flag:"--note",repeatable:!0},{flag:"--learning",repeatable:!0},{flag:"--reminder",repeatable:!0},{flag:"--event",repeatable:!0},{flag:"--type-option",aliases:["--type_option"],repeatable:!0},{flag:"--body"},{flag:"--claim"},{flag:"--from-search",aliases:["--from_search"]},{flag:"--template"},{flag:"--step-title",aliases:["--step_title"]},{flag:"--step"},{flag:"--step-body",aliases:["--step_body"]},{flag:"--step-owner",aliases:["--step_owner"]},{flag:"--step-status",aliases:["--step_status"]},{flag:"--step-evidence",aliases:["--step_evidence"]},{flag:"--step-blocked-reason",aliases:["--step_blocked_reason"]},{flag:"--step-replacement",aliases:["--step_replacement"]},{flag:"--depends-on",aliases:["--depends_on"]},{flag:"--link"},{flag:"--link-kind",aliases:["--link_kind"]},{flag:"--link-note",aliases:["--link_note"]},{flag:"--promote-to-item-dep",aliases:["--promote_to_item_dep"]},{flag:"--allow-multiple-active",aliases:["--allow_multiple_active"]},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--decision-text",aliases:["--decision_text","--decision"]},{flag:"--decision-rationale",aliases:["--decision_rationale"]},{flag:"--decision-evidence",aliases:["--decision_evidence"]},{flag:"--discovery-text",aliases:["--discovery_text","--discovery"]},{flag:"--validation-text",aliases:["--validation_text","--validation"]},{flag:"--validation-command",aliases:["--validation_command"]},{flag:"--validation-expected",aliases:["--validation_expected"]},{flag:"--depth"},{flag:"--field"},{flag:"--fields",list:!0},{flag:"--steps"},{flag:"--materialize-type",aliases:["--materialize_type"]},{flag:"--materialize-parent",aliases:["--materialize_parent"]},{flag:"--materialize-tags",aliases:["--materialize_tags"]},{flag:"--author"},{flag:"--message"},{flag:"--force"}],V=[{flag:"--id-prefix",aliases:["--prefix"]},{flag:"--preset"},{flag:"--type-preset"},{flag:"--defaults",short:"-y",aliases:["--yes"]},{flag:"--author"},{flag:"--agent-guidance"},{flag:"--with-packages"},{flag:"--no-merge-fence"},{flag:"--workspace"},{flag:"--force"},{flag:"--verbose"}],K=[{flag:"--criterion"},{flag:"--clear-criteria"},{flag:"--format"},{flag:"--policy"},{flag:"--default-depth"},{flag:"--activity-limit"},{flag:"--stale-threshold-days"},{flag:"--section-hierarchy"},{flag:"--section-activity"},{flag:"--section-progress"},{flag:"--section-blockers"},{flag:"--section-files"},{flag:"--section-workload"},{flag:"--section-staleness"},{flag:"--section-tests"}],y=[{flag:"--init"},{flag:"--scaffold"},{flag:"--capability"},{flag:"--install"},{flag:"--uninstall"},{flag:"--explore"},{flag:"--list"},{flag:"--manage"},{flag:"--describe"},{flag:"--markdown"},{flag:"--output"},{flag:"--reload"},{flag:"--watch"},{flag:"--doctor"},{flag:"--catalog"},{flag:"--adopt"},{flag:"--adopt-all"},{flag:"--activate"},{flag:"--deactivate"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"},{flag:"--detail"},{flag:"--trace"},{flag:"--runtime-probe"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],s=[{flag:"--project"},{flag:"--local"},{flag:"--global"}],x=[...s,{flag:"--capability"}],m=[...y,{flag:"--declarative"}],W=[...x,{flag:"--declarative"}],$=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],J=s,Q=s,Z=[...s,{flag:"--markdown"},{flag:"--output"}],aa=s,ea=s,la=s,ta=[...s,{flag:"--dry-run"}],fa=[...s,{flag:"--runtime-probe"},{flag:"--fix-managed-state"}],ga=[...s,{flag:"--watch"}],sa=[...s,{flag:"--detail"},{flag:"--trace"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],ra=[...s,{flag:"--fields",list:!0}],ia=[...s,{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],oa=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],na=[{flag:"--dry-run"},{flag:"--cli-only"},{flag:"--packages-only"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--repair"},{flag:"--tag"},{flag:"--package-name"}],te=[{flag:"--mode"},{flag:"--progress"}],ca=[{flag:"--reason"},{flag:"--close-reason"},{flag:"--completed-at"},{flag:"--duplicate-of"},{flag:"--author"},{flag:"--message"},{flag:"--validate-close"},{flag:"--resolution"},{flag:"--expected-result",aliases:["--expected_result","--expected"]},{flag:"--actual-result",aliases:["--actual_result","--actual"]},{flag:"--force"}],da=[{flag:"--filter-status",list:!0},{flag:"--filter-type"},{flag:"--filter-tag"},{flag:"--filter-priority"},{flag:"--filter-deadline-before"},{flag:"--filter-deadline-after"},{flag:"--filter-updated-after"},{flag:"--filter-updated-before"},{flag:"--filter-created-after"},{flag:"--filter-created-before"},{flag:"--filter-assignee"},{flag:"--filter-assignee-filter"},{flag:"--filter-assignee_filter"},{flag:"--filter-parent"},{flag:"--filter-sprint"},{flag:"--filter-release"},...h,{flag:"--reason"},{flag:"--completed-at"},{flag:"--resolution"},{flag:"--expected-result",aliases:["--expected_result","--expected"]},{flag:"--actual-result",aliases:["--actual_result","--actual"]},{flag:"--validate-close"},{flag:"--author"},{flag:"--message"},{flag:"--force"},{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"}],pa=[{flag:"--body",short:"-b"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],ua=[{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"},{flag:"--if-available"},{flag:"--next"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee-filter"},{flag:"--parent"},{flag:"--sprint"},{flag:"--release"},{flag:"--max-attempts"},{flag:"--include-decisions"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--explain-ranking",aliases:["--explain_ranking"]}],ma=[{flag:"--author"},{flag:"--message"},{flag:"--force"}],_a=[{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Ta=[{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],Aa=[{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],Ca=[{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],ha=[{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--validate-close"},{flag:"--force"}],b=[{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--tags"},{flag:"--priority"},{flag:"--body"},{flag:"--description"},{flag:"--author"},{flag:"--message"}],v=[{flag:"--start"},{flag:"--duration"},{flag:"--end"},{flag:"--location"},{flag:"--timezone"},{flag:"--all-day"},...b],ya=v,xa=[{flag:"--at"},{flag:"--text"},...b],ba=[{flag:"--add"},{flag:"--add-json"},{flag:"--remove"},{flag:"--run"},{flag:"--match"},{flag:"--only-index"},{flag:"--only-last"},{flag:"--background"},{flag:"--timeout"},{flag:"--progress"},{flag:"--env-set"},{flag:"--env-clear"},{flag:"--shared-host-safe"},{flag:"--pm-context"},{flag:"--override-linked-pm-context"},{flag:"--fail-on-context-mismatch"},{flag:"--fail-on-skipped"},{flag:"--fail-on-empty-test-run"},{flag:"--require-assertions-for-pm"},{flag:"--check-context"},{flag:"--auto-pm-context"},{flag:"--measure",list:!0},{flag:"--metric-below"},{flag:"--metric-diff"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],va=[{flag:"--status"},{flag:"--limit"},{flag:"--offset"},{flag:"--background"},{flag:"--timeout"},{flag:"--progress"},{flag:"--env-set"},{flag:"--env-clear"},{flag:"--shared-host-safe"},{flag:"--pm-context"},{flag:"--override-linked-pm-context"},{flag:"--fail-on-context-mismatch"},{flag:"--fail-on-skipped"},{flag:"--fail-on-empty-test-run"},{flag:"--require-assertions-for-pm"},{flag:"--check-context"},{flag:"--auto-pm-context"}],Sa=[{flag:"--limit"}],Na=[{flag:"--status"},{flag:"--limit"},{flag:"--stream"},{flag:"--tail"},{flag:"--force"},{flag:"--author"}],Oa=[{flag:"--dry-run"},{flag:"--scope"}],La=[{flag:"--storage"},{flag:"--metadata-coverage"},{flag:"--field-utilization"},{flag:"--by-assignee"},{flag:"--by-tag"},{flag:"--by-priority"},{flag:"--tag-prefix"},{flag:"--analytics"}],Ea=[{flag:"--status",repeatable:!0,list:!0},{flag:"--since"},{flag:"--threshold"},{flag:"--limit"}],Ra=[{flag:"--strict-directories"},{flag:"--require-merge-drivers"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--check-only"},{flag:"--check-telemetry"},{flag:"--no-refresh"},{flag:"--refresh-vectors"},{flag:"--verbose-stale-items"},{flag:"--verbose-author-events"},{flag:"--brief"},{flag:"--summary"},{flag:"--skip-vectors"},{flag:"--skip-integrity"},{flag:"--skip-drift"},{flag:"--full"}],ka=[{flag:"--check-metadata"},{flag:"--metadata-profile"},{flag:"--check-resolution"},{flag:"--check-lifecycle"},{flag:"--check-stale-blockers"},{flag:"--dependency-cycle-severity"},{flag:"--parent-cycle-severity"},{flag:"--check-files"},{flag:"--scan-mode"},{flag:"--include-pm-internals"},{flag:"--verbose-file-lists"},{flag:"--verbose-diagnostics"},{flag:"--all-affected-ids"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--fix-hints"},{flag:"--auto-fix"},{flag:"--dry-run"},{flag:"--fix-scope"},{flag:"--prune-missing"},{flag:"--check-history-drift"},{flag:"--check-command-references"},{flag:"--check-storage-integrity"},{flag:"--counts"},{flag:"--full"}],S=[{flag:"--assignee"},{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--blocked-by"},{flag:"--blocked-reason"},{flag:"--unblock-note"},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps"},{flag:"--resolution"},{flag:"--expected-result"},{flag:"--actual-result"},{flag:"--affected-version"},{flag:"--fixed-version"}],N=[{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact"},{flag:"--customer_impact"},{flag:"--definition-of-ready"},{flag:"--definition_of_ready"},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now"},{flag:"--why_now"}],O=[{short:"-p",flag:"--priority"},{flag:"--type"},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--add-tags",aliases:["--add_tags"]},{flag:"--remove-tags",aliases:["--remove_tags"]},{flag:"--deadline"},{flag:"--estimate"},{flag:"--estimated-minutes"},{flag:"--estimated_minutes"},{flag:"--acceptance-criteria"},{flag:"--acceptance_criteria"},{flag:"--ac"},{flag:"--add-ac",aliases:["--add_ac"]},{flag:"--remove-ac",aliases:["--remove_ac"]}],_=[{flag:"--stdin-json"},{short:"-t",flag:"--title"},{flag:"--id"},{short:"-d",flag:"--description"},{flag:"--type"},{flag:"--template"},{flag:"--create-mode"},{flag:"--create_mode"},{flag:"--schedule-preset"},{flag:"--schedule_preset"},{short:"-s",flag:"--status"},{flag:"--close-reason"},{flag:"--close_reason"},{flag:"--completed-at"},{flag:"--completed_at"},{short:"-p",flag:"--priority"},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--add-tags",aliases:["--add_tags"]},{short:"-b",flag:"--body"},{flag:"--body-file"},{flag:"--deadline"},{flag:"--estimate"},{flag:"--estimated-minutes"},{flag:"--estimated_minutes"},{flag:"--acceptance-criteria"},{flag:"--acceptance_criteria"},{flag:"--ac"},{flag:"--author"},{flag:"--message"},...S,...N,{flag:"--blocked_by"},{flag:"--blocked_reason"},{flag:"--unblock_note"},{flag:"--repro_steps"},{flag:"--expected_result"},{flag:"--actual_result"},{flag:"--expected"},{flag:"--actual"},{flag:"--affected_version"},{flag:"--fixed_version"},{flag:"--dep"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--field"},{flag:"--reminder"},{flag:"--event"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--allow-duplicate",value_type:"boolean"}],Ga=[{flag:"--transaction-id",value_name:"value"},{flag:"--stdin-json"},{flag:"--dry-run"},{flag:"--create-compensation",value_name:"mode"},{flag:"--lock-ttl-seconds",value_name:"n"},{flag:"--lock-wait-ms",value_name:"n"},{flag:"--author",value_name:"value"}],Fa=[{flag:"--transaction-id",value_name:"value",required:!0},{flag:"--reason",value_name:"value"},{flag:"--file",value_name:"value",repeatable:!0},{flag:"--doc",value_name:"value",repeatable:!0},{flag:"--test",value_name:"value",repeatable:!0},{flag:"--comment",value_name:"value",repeatable:!0},{flag:"--note",value_name:"value",repeatable:!0},{flag:"--learning",value_name:"value",repeatable:!0},{flag:"--resolution",value_name:"value"},{flag:"--expected-result",value_name:"value"},{flag:"--actual-result",value_name:"value"},{flag:"--completed-at",value_name:"value"},{flag:"--validate-close",value_name:"mode"},{flag:"--lock-ttl-seconds",value_name:"n"},{flag:"--lock-wait-ms",value_name:"n"},{flag:"--dry-run"},{flag:"--force"},{flag:"--author",value_name:"value"}],wa=[{flag:"--title"},{flag:"--author"},{flag:"--message"},{flag:"--allow-duplicate",value_type:"boolean"}],Ia=[{flag:"--clear"}],Ma=[{flag:"--stdin-json"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},{flag:"--body-file"},{short:"-s",flag:"--status"},{flag:"--close-reason"},{flag:"--close_reason"},{flag:"--completed-at"},...O,...S,{flag:"--fixed_version"},...N,{flag:"--author"},{flag:"--message"},{flag:"--blocked_by"},{flag:"--blocked_reason"},{flag:"--unblock_note"},{flag:"--repro_steps"},{flag:"--expected_result"},{flag:"--actual_result"},{flag:"--expected"},{flag:"--actual"},{flag:"--affected_version"},{flag:"--dep"},{flag:"--dep-remove"},{flag:"--dep_remove"},{flag:"--replace-deps"},{flag:"--replace-tests"},{flag:"--replace-files"},{flag:"--replace-docs"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--reminder"},{flag:"--event"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--field"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--force"}],Da=[{flag:"--filter-status",list:!0},{flag:"--filter-type",list:!0},{flag:"--filter-tag",list:!0},{flag:"--filter-priority",list:!0},{flag:"--filter-deadline-before"},{flag:"--filter-deadline-after"},{flag:"--filter-updated-after"},{flag:"--filter-updated-before"},{flag:"--filter-created-after"},{flag:"--filter-created-before"},{flag:"--filter-assignee",list:!0},{flag:"--filter-assignee-filter"},{flag:"--filter-assignee_filter"},{flag:"--filter-parent"},{flag:"--filter-sprint",list:!0},{flag:"--filter-release",list:!0},{flag:"--filter-ac-missing"},{flag:"--filter-estimates-missing",aliases:["--filter-estimate-missing"]},{flag:"--filter-resolution-missing"},{flag:"--filter-metadata-missing"},...h,{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},...O,{flag:"--definition-of-ready"},{flag:"--definition_of_ready"},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now"},{flag:"--why_now"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps"},{flag:"--repro_steps"},{flag:"--resolution"},{flag:"--expected-result"},{flag:"--expected_result"},{flag:"--expected"},{flag:"--actual-result"},{flag:"--actual_result"},{flag:"--actual"},{flag:"--affected-version"},{flag:"--affected_version"},{flag:"--fixed-version"},{flag:"--fixed_version"},{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact"},{flag:"--customer_impact"},{flag:"--dep"},{flag:"--dep-remove"},{flag:"--dep_remove"},{flag:"--replace-deps"},{flag:"--replace-tests"},{flag:"--replace-files"},{flag:"--replace-docs"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--reminder"},{flag:"--event"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],T=[{flag:"--view"},{flag:"--date"},{flag:"--from"},{flag:"--to"},{flag:"--past"},{flag:"--full-period"},{flag:"--full_period"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--status"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--include"},{flag:"--recurrence-lookahead-days"},{flag:"--recurrence-lookback-days"},{flag:"--occurrence-limit"},{flag:"--limit"},{flag:"--format"}],Pa=[{flag:"--id"},{flag:"--op"},{flag:"--author"},{flag:"--from"},{flag:"--to"},{flag:"--limit"},{flag:"--unbounded"},{flag:"--compact"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--stream"}],Xa=[{flag:"--since"},{flag:"--type",repeatable:!0},{flag:"--author",repeatable:!0},{flag:"--item",repeatable:!0},{flag:"--limit",value_type:"number"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--follow"},{flag:"--interval-ms",value_type:"number"}],A=p([{flag:"--for",value_name:"intent"},{flag:"--date"},{flag:"--from"},{flag:"--to"},{flag:"--past"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--parent"},{flag:"--limit",aliases:["--max-items"]},{flag:"--after"},{flag:"--format"},{flag:"--depth"},{flag:"--fields",list:!0},{flag:"--section"},{flag:"--activity-limit"},{flag:"--stale-threshold"},{flag:"--explain-ranking"},{flag:"--explain_ranking"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--no-extension-health"},{flag:"--no-tags"}],new Set(["--limit","--after","--format","--fields","--section","--activity-limit","--stale-threshold","--explain-ranking","--explain_ranking","--no-extension-health","--no-tags"])),Ua=[{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--depth"},{flag:"--full"},{flag:"--fields",list:!0},{flag:"--at"},{flag:"--tree"},{flag:"--tree-depth"},{flag:"--tree_depth"},{flag:"--format"}],ja=[{flag:"--list"},{flag:"--format"},{flag:"--depth"}],Ha=[{flag:"--format"},{flag:"--max-depth"},{flag:"--collapse"},{flag:"--summary"},{flag:"--full"},{flag:"--node-limit"},{flag:"--edge-limit"},{flag:"--token-budget"},{flag:"--cursor"},{flag:"--direction"},{flag:"--kind",list:!0}],za=[{flag:"--kind",list:!0},{flag:"--max-depth"},{flag:"--limit"},{flag:"--after"},{flag:"--direction"},{flag:"--max-paths"},{flag:"--sample"},{flag:"--exempt-isolate",list:!0},{flag:"--exempt-isolate-type",list:!0},{flag:"--save-baseline"},{flag:"--rebuild"},{flag:"--clear"},{flag:"--summary"},{flag:"--full"}],Ya=[{flag:"--mode"},{flag:"--k"},{flag:"--fail-under"},{flag:"--queries"},{flag:"--format"}],r=[{flag:"--dry-run"},{flag:"--force"},{flag:"--author"},{flag:"--message"}],qa=[{flag:"--for",value_name:"intent"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--parent"},{flag:"--limit"},{flag:"--blocked-limit"},{flag:"--blocked_limit"},{flag:"--ready-only"},{flag:"--ready_only"},{flag:"--format"},{flag:"--explain-ranking"},{flag:"--explain_ranking"},{flag:"--token-budget",aliases:["--token_budget"]}],Ba=p([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--mode"},{flag:"--semantic"},{flag:"--hybrid"},{flag:"--match-mode"},{flag:"--min-score"},{flag:"--count"},{flag:"--semantic-weight"},{flag:"--include-linked"},{flag:"--title-exact"},{flag:"--phrase-exact"},{flag:"--highlight"},{flag:"--compact"},{flag:"--full"},{flag:"--fields",list:!0},{flag:"--format"},{flag:"--limit"},{flag:"--after"},{flag:"--status",list:!0},{flag:"--type",list:!0},{flag:"--tag",aliases:["--tags"],list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--updated-after"},{flag:"--updated-before"},{flag:"--created-after"},{flag:"--created-before"},{flag:"--assignee",list:!0},{flag:"--sprint",list:!0},{flag:"--release",list:!0},{flag:"--parent"},...C],new Set(["--highlight","--compact","--full","--fields","--format","--limit","--token-budget","--after"])),Va=[{flag:"--action"},{flag:"--command"},{flag:"--summary"},{flag:"--schema-only"},{flag:"--flags-only"},{flag:"--availability-only"},{flag:"--runtime-only"},{flag:"--active-only"},{flag:"--full"}],Ka=[{flag:"--eager-tags"}];function Wa(a){let e=new Set,l=[];for(let t of a){let g=(t.aliases??[]).join(","),f=`${t.flag}|${t.short??""}|${g}`;e.has(f)||(e.add(f),l.push(t))}return l}function o(a){return c(Wa([...d,...a]))}var $a=["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"],L=new Map([...$a.map(a=>[a,k]),["templates",_],["cal",T],["ctx",A],["test-runs-worker",Na],["init",V],["config",K],["extension",y],["package",m],["packages",m],["install",oa],["upgrade",na],["create",_],["item mutate",Ga],["item complete",Fa],["copy",wa],["focus",Ia],["aggregate",G],["calendar",T],["context",A],["get",Ua],["guide",ja],["search",Ba],["next",qa],["eval",Ya],["workspace",r],["workspace snapshot",r],["workspace snapshot create",r],["workspace snapshot list",r],["workspace snapshot inspect",r],["workspace snapshot restore",r],["workspace snapshot delete",r],["history",P],["history-redact",U],["history-repair",j],["history-author-acknowledge",H],["history-compact",z],["merge",X],["schema",Y],["profile",q],["plan",B],["activity",Pa],["events",Xa],["restore",ma],["update",Ma],["update-many",Da],["close",ca],["close-many",da],["delete",_a],["append",pa],["comments",F],["notes",w],["learnings",I],["files",M],["docs",D],["deps",Ha],["graph",za],["test",ba],["test-all",va],["telemetry",Sa],["health",Ra],["validate",ka],["gc",Oa],["stats",La],["duplicates",Ea],["contracts",Va],["completion",Ka],["claim",ua],["release",Ta],["start-task",Aa],["pause-task",Ca],["close-task",ha],["meet",v],["event",ya],["remind",xa]]),E=new Map([["install",$],["uninstall",J],["explore",Q],["manage",fa],["describe",Z],["reload",ga],["doctor",sa],["catalog",ra],["adopt",ia],["adopt-all",aa],["activate",ea],["deactivate",la],["migrate",ta]]);function R(a){return typeof a!="string"?"":a.trim().toLowerCase()}function fe(a){let e=R(a);if(L.has(e))return!0;let[l,t,...g]=e.split(/\s+/);return(l==="extension"||l==="package"||l==="packages")&&t!==void 0&&g.length===0&&(t==="init"||E.has(t))}function Ja(a,e){return e==="init"?a==="extension"?x:W:E.get(e)??[]}function ge(a){let e=R(a);if(e.length===0)return o([]);let[l,t,...g]=e.split(/\s+/);return(l==="extension"||l==="package"||l==="packages")&&t!==void 0&&g.length===0?o(Ja(l,t)):o(L.get(e)??[])}function se(a,e=!0){let t=c(a).flatMap(f=>[f.short,f.flag,...f.aliases??[]]).filter(f=>!!f),g=e?[...t,...d.flatMap(f=>[f.short,f.flag,...f.aliases??[]]).filter(f=>!!f)]:t;return i(g).join(" ")}export{i as a,c as b,ee as c,d,le as e,k as f,G as g,F as h,w as i,I as j,M as k,D as l,P as m,X as n,U as o,j as p,H as q,z as r,Y as s,q as t,B as u,V as v,K as w,y as x,s as y,x as z,m as A,W as B,$ as C,J as D,Q as E,Z as F,aa as G,ea as H,la as I,ta as J,fa as K,ga as L,sa as M,ra as N,ia as O,oa as P,na as Q,te as R,ca as S,da as T,pa as U,ua as V,ma as W,_a as X,Ta as Y,Aa as Z,Ca as _,ha as $,v as aa,ya as ba,xa as ca,ba as da,va as ea,Sa as fa,Na as ga,Oa as ha,La as ia,Ea as ja,Ra as ka,ka as la,_ as ma,Ga as na,Fa as oa,wa as pa,Ia as qa,Ma as ra,Da as sa,T as ta,Pa as ua,Xa as va,A as wa,Ua as xa,ja as ya,Ha as za,za as Aa,Ya as Ba,r as Ca,qa as Da,Ba as Ea,Va as Fa,Ka as Ga,Wa as Ha,fe as Ia,ge as Ja,se as Ka};
2
- //# sourceMappingURL=chunk-DLTS3IHM.js.map
@@ -1,14 +0,0 @@
1
- import{f as Xt}from"./chunk-MHMTKV5V.js";import{h as de,i as Vt,j as ue,k as Yt,n as Jt}from"./chunk-4EX25PXM.js";import{Ca as ie,Da as Ut,Fa as zt,Ia as Bt,Ja as Gt,K as ne,L as Y,La as $,P as Ft,Ua as Wt,V as Lt,W as $t,Z as Dt,Za as qt,_ as Mt,ab as ve,ba as Be,bb as be,cb as Ht,da as Ot,eb as Kt,hb as Ee,k as q,na as Nt,q as Pt,za as jt}from"./chunk-MOTJFQ3F.js";import{D as z,I as Rt,J as B,K as le,Ka as At,M as O,P as xt,T as P,aa as je,h as bt,o as Et,p as L,q as St,r as ce,u as Ne,v as It}from"./chunk-RW5IYD4J.js";import{i as Tt}from"./chunk-R2LEMEV5.js";import{N as kt,U as vt,V as ke,Y as g,Z as y,aa as Ue,ba as Ct,ca as ze,t as Oe}from"./chunk-ZJIMJHDB.js";import{readFile as Se,realpath as He,writeFile as Ki}from"node:fs/promises";import{execFile as Vi}from"node:child_process";import x from"node:path";import{promisify as Yi}from"node:util";import{readFile as Gi,writeFile as Wi}from"node:fs/promises";import me 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]="bbfa5b19-d801-582a-98e8-0c4925dd57c0")}catch{}})();var Qt="# pm-cli:runtime-cache:start",Ge="# pm-cli:runtime-cache:end",en=".agents/pm",We=["runtime/","search/","locks/","transactions/","checkpoints/"],qi=["search/eval-queries.json"];async function Zt(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new y("The workspace .gitignore is not writable.",g.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function tn(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function qe(e){let t=e.replaceAll("\\","/");return me.isAbsolute(e)||t===".."||t.startsWith("../")}function Hi(e=en){let t=tn(e);return[Qt,...We.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...qi.map(n=>`!${t}/${n}`),Ge].join(`
2
- `)}async function $o(e,t={}){let n=me.join(e,".gitignore"),i=en;if(t.pmRoot!==void 0){let d=tn(me.relative(me.resolve(e),me.resolve(t.pmRoot)));if(qe(d))return{path:n,changed:!1};d.length>0&&(i=d)}let r="";try{r=await Zt(()=>Gi(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&d.code==="ENOENT"))throw d}let s=r.indexOf(Qt),o=r.indexOf(Ge),c=(s>=0&&o>=s?`${r.slice(0,s)}${r.slice(o+Ge.length)}`:r).trimEnd(),l=`${c.length>0?`${c}
3
-
4
- `:""}${Hi(i)}
5
- `;return l===r?{path:n,changed:!1}:(await Zt(()=>Wi(n,l,"utf8")),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a250384a-0279-5d01-ade4-f64be3119ed9")}catch{}})();var Ke=Yi(Vi),Q="# pm-cli:merge-drivers:start",fe="# pm-cli:merge-drivers:end",Ji="merge-fence";function nn(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function sn(){let e=It(import.meta.url,["../../.."]);return`${nn(process.execPath)} ${nn(x.join(e,"dist","cli.js"))}`}var on=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];async function pe(e){try{let{stdout:t}=await Ke("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await He(t.trim())}catch{return null}}async function an(e){let t=await pe(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function Ve(e,t){return x.relative(e,t).replaceAll("\\","/")}function G(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function rn(e,t){if(e[t]!=="'")return null;let n="";for(let i=t+1;i<e.length;i+=1){if(e.startsWith(`'"'"'`,i)){n+="'",i+=4;continue}if(e[i]==="'")return{value:n,nextOffset:i+1};n+=e[i]}return null}async function Xi(e,t){let n=rn(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let i=rn(e,n.nextOffset+1);if(i===null||e.slice(i.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(x.basename(n.value))||x.basename(i.value)!=="cli.js"||x.basename(x.dirname(i.value))!=="dist"||!await L(n.value)||!await L(i.value))return!1;try{let r=x.dirname(x.dirname(i.value)),s=JSON.parse(await Se(x.join(r,"package.json"),"utf8")),o=typeof s.bin=="object"&&s.bin!==null&&"pm"in s.bin?s.bin.pm:void 0;return s.name==="@unbrained/pm-cli"&&(s.bin==="dist/cli.js"||o==="dist/cli.js")}catch{return!1}}function Ye(e,t){let n=e.length>0?`${e}/`:"",i=[`${G(`${n}**/*.toon`)} merge=pm-item-toon`,`${G(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)i.push(`${G(`${n}${r}/*.toon`)} merge=pm-item-toon`),i.push(`${G(`${n}${r}/*.md`)} merge=pm-item-markdown`);return i.push(`${G(`${n}**/*.jsonl`)} merge=pm-relationship`),i.push(`${G(`${n}history/*.jsonl`)} merge=pm-history`),i.push(`${G(`${n}settings.json`)} merge=pm-json`),i.push(`${G(`${n}**/*.json`)} merge=pm-json`),i.push(`${G(`${n}extensions/**`)} -merge`),i.push(`${G(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),i}async function cn(e,t,n){let i=x.join(e,".gitattributes"),r="";try{r=await Se(i,"utf8")}catch(u){if(!(u instanceof Error&&"code"in u&&u.code==="ENOENT"))throw u}let s=[Q,...t,fe].join(`
6
- `),o=r.indexOf(Q),a=r.indexOf(fe),l=(o>=0&&a>o?`${r.slice(0,o)}${r.slice(a+fe.length)}`:r.replace(Q,"").replace(fe,"")).trimEnd(),d=`${l.length>0?`${l}
7
-
8
- `:""}${s}
9
- `;return d===r?{path:i,changed:!1}:(n||await Ki(i,d,"utf8"),{path:i,changed:!0})}function Ie(e){let t=z(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,i)=>n.localeCompare(i))}async function ln(e,t){let n=x.resolve(e),i=null,r="",s=n;for(let p=0;p<8;p+=1){let _=x.join(s,".gitattributes");try{let v=await Se(_,"utf8");if(v.includes(Q)){i=s,r=v;break}}catch{}let h=x.dirname(s);if(h===s)break;s=h}if(i===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=x.join(i,".gitattributes"),a=r.indexOf(Q),c=r.indexOf(fe),l=c>a?r.slice(a+Q.length,c).split(`
10
- `).map(p=>p.trim()).filter(p=>p.length>0):[],d=Ye(Ve(i,n),t),u=new Set(l),m=new Set(d),f=d.filter(p=>!u.has(p)),w=l.filter(p=>!m.has(p));return{status:f.length>0||w.length>0?"drift":"ok",path:o,missing_patterns:f,stale_patterns:w,schema_scope:"project"}}async function dn(e){let t=sn(),n=[],i=[];for(let r of on){let s=`merge.${r.key}.driver`,o=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`,a=`${t}${o}`;try{let{stdout:c}=await Ke("git",["config","--local","--get",s],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await Xi(l,o)&&i.push(s)}catch{n.push(s)}}return{status:n.length>0?"missing":i.length>0?"drift":"ok",missing_keys:n,drifted_keys:i}}async function Xo(e){let t;try{t=await an(x.resolve(e))}catch{return{status:"no_git"}}let n=Ve(t,x.resolve(e)),i=await $(e),r=ne(void 0,i.author_default),s=await Ft(e,Ji,i.locks.ttl_seconds,r,!1,Gt(i).force_required_for_stale_lock,i.locks.wait_ms);try{let o=x.join(t,".gitattributes"),a;try{a=await Se(o,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&u.code==="ENOENT")return{status:"not_installed",path:o};throw u}if(!a.includes(Q))return{status:"not_installed",path:o};let c=await $(e),l=Ie(c),d=await cn(t,Ye(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await s()}}async function Zo(e,t){let n=t.path?.trim(),i=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=process.env.PM_SOURCE_PM_PATH?.trim(),s=n===void 0&&i!==void 0&&i.length>0&&r!==void 0&&r.length>0,o=n!==void 0?B(process.cwd(),n):s?x.resolve(r):B(process.cwd());if(!await L(O(o)))throw new y(`Tracker is not initialized at ${o}. Run pm init first.`,g.NOT_FOUND);let a=await an(n!==void 0?o:s?x.resolve(i):process.cwd());return Zi({pmRoot:o,workspaceRoot:a,dryRun:e.dryRun===!0})}async function Zi(e){let t=x.resolve(e.pmRoot),n=x.resolve(e.workspaceRoot),i=e.dryRun===!0,r,s;try{[r,s]=await Promise.all([He(t),He(n)])}catch(f){throw new y(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,g.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let o=Ve(s,r);if(qe(o))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let a=await $(r),c=Ie(a),l=Ye(o,c),d=[],u=sn();for(let f of on)d.push({key:`merge.${f.key}.name`,value:f.name}),d.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!i)try{for(let f of d)await Ke("git",["config","--local",f.key,f.value],{cwd:s,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new y(`Cannot install repository-local merge drivers in ${s}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,g.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await cn(s,l,i);return{ok:!0,dry_run:i,workspace_root:s,pm_root:r,gitattributes:{path:m.path,changed:m.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm validate" and, if history drift is reported, "pm history-repair --all" to reconcile item state with merged history.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:Y()}}import Re from"node:fs/promises";import xe 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 _e(e,t){throw new y(e,g.USAGE,{code:t})}var Qi="2026-07-15T06:22:12.276Z",er=Date.parse(Qi),tr=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],un=e=>typeof e=="string"?e:"",mn=e=>{let t=e??{},n=un(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(un(t.ts))>=er);return tr[i][r]};function fn(e,t,n=20,i=new Set,r=!1){let s=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let w;try{w=JSON.parse(f)}catch{continue}l+=1;let p=mn(w);if(p!=="attributed"){if(d+=1,p==="actionable_unknown"&&i.has(`${e}:${m+1}`)){u+=1;continue}a[p]+=1,r&&p==="actionable_unknown"&&o.push({item_id:e,line:m+1}),s.length<c&&s.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:s,samples_truncated:a.legacy_unknown+a.actionable_unknown>s.length,actionable_events:o}}var oa=(e,t,n=20,i=new Set)=>fn(e,t,n,i);function nr(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let s=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof s!="object"||s===null||!Array.isArray(s.events)))for(let o of s.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 i=xe.join(e,"history"),r;try{r=(await Re.readdir(i)).filter(h=>h.endsWith(".jsonl")).sort((h,v)=>h.localeCompare(v))}catch{r=[]}let s=new Set,o=[],a=[],c=0,l=0,d=0,u=0,m=0,f=0,w="_workspace.jsonl",p=new Set;if(r.includes(w))try{p=nr(await Re.readFile(xe.join(i,w),"utf8"))}catch{p=new Set}for(let h of r){let v;try{v=await Re.readFile(xe.join(i,h),"utf8")}catch{continue}let E=h.slice(0,-6),S=fn(E,v,t-o.length,p,n);c+=1,l+=S.checked_events,d+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,f+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&s.add(E),o.push(...S.samples),n&&a.push(...S.actionable_events)}let _=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...s].sort((h,v)=>h.localeCompare(v)),samples:o,samples_truncated:_>o.length,...n?{actionable_events:a}:{}}};async function aa(e,t){let n=t.reviewer.trim(),i=t.attributed_author.trim(),r=t.reason.trim(),s=t.events??[];+(t.all_actionable===!0)+ +(s.length>0)>1&&_e("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:s;[a.length>0,n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1)&&_e("Author acknowledgment requires events, reviewer, attributed_author, and reason.","history_author_acknowledge_required_values_missing");let l=[...new Map(a.map(m=>[`${m.item_id}:${m.line}`,{item_id:m.item_id,line:m.line}])).values()].sort((m,f)=>m.item_id.localeCompare(f.item_id)||m.line-f.line);for(let m of l){[/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1)&&_e(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,"history_author_acknowledge_target_unreadable");let w;try{let _=(await Re.readFile(xe.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];w=JSON.parse(_??"")}catch{_e(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,"history_author_acknowledge_target_unreadable")}mn(w)!=="actionable_unknown"&&_e(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`,"history_author_acknowledge_target_not_actionable")}let d=await $(e),u=await zt({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:l,attributed_author:i}},message:r,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms});return{acknowledged:l.length,history_path:u.historyPath}}import{execFile as ir}from"node:child_process";import{randomUUID as rr}from"node:crypto";import{readdir as sr,readFile as or}from"node:fs/promises";import he from"node:path";import{promisify as ar}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 cr=ar(ir);async function Xe(e){try{let{stdout:t}=await cr("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 pn(e){return`${e}.json`}function ga(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:ze(Ue(t.retained)),discarded_hash:ze(Ue(t.discarded))}))}}async function ya(e){let t=await Xe(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),i=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,r=he.basename(i,he.extname(i)),s={version:1,id:rr(),item_path:i.replaceAll("\\","/"),item_id:r,preferred:e.preferred,fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:Y()};return await Et(t),await ce(he.join(t,pn(s.id)),`${JSON.stringify(s,null,2)}
11
- `),s}async function Ze(e,t={}){let n=await Xe(e);if(n===null||!await L(n))return[];let i=[],r;try{r=await sr(n)}catch{return[]}for(let s of r.sort((o,a)=>o.localeCompare(a)))if(s.endsWith(".json"))try{let o=JSON.parse(await or(he.join(n,s),"utf8"));o.version===1&&(t.includeReconciled||o.state==="pending")&&i.push(o)}catch{}return i.sort((s,o)=>s.created_at.localeCompare(o.created_at))}async function wa(e,t){let n=await Xe(e);n!==null&&await ce(he.join(n,pn(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:Y()},null,2)}
12
- `)}async function ka(e){let t=await Ze(e.cwd??process.cwd(),e);return{ok:!0,count:t.length,receipts:t,generated_at:Y()}}import re from"node:fs/promises";import se 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 lr(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let s;try{s=await re.readdir(se.join(e,r))}catch{return}for(let o of s)for(let a of Rt)if(o.toLowerCase().endsWith(a)){i.push({relativePath:`${r}/${o}`,id:o.slice(0,-a.length)});break}})),i.sort((r,s)=>r.relativePath.localeCompare(s.relativePath))}function dr(e,t){let{id:n,relativePath:i,liveItemIds:r,out:s}=e,o=Be(t);if(o){s.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=null,c=t.split(/\r?\n/).map((l,d)=>({content:l.trim(),number:d+1})).filter(l=>l.content.length>0);for(let l of c)try{let d=JSON.parse(l.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");a=d}catch{s.unparseable.push({id:n,path:i,line:l.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&r.has(n)&&s.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&&(s.repairReconciliations+=1))}function Qe(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 ur(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await re.readdir(se.join(e,"history"))}catch{return n}for(let r of i.sort((s,o)=>s.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await re.readFile(se.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Qe("history stream",o)});continue}dr({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},s)}return n}function _n(e){let t=Be(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 mr(e){let t=[],n=0,i=null;try{i=await St(O(e))}catch(s){n+=1,t.push({path:"settings.json",detail:Qe("configuration file",s)})}if(i!==null){n+=1;let s=_n(i);s!==null&&t.push({path:"settings.json",detail:s})}let r;try{r=await re.readdir(se.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of r.sort((o,a)=>o.localeCompare(a))){if(!s.endsWith(".json"))continue;n+=1;let o;try{o=await re.readFile(se.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:Qe("configuration file",c)});continue}let a=_n(o);a!==null&&t.push({path:`schema/${s}`,detail:a})}return{scanned:n,unparseable:t}}async function hn(e,t,n,i={}){let r=await lr(e,n),s=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((f,w)=>f.localeCompare(w))})).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=se.join(e,u.relativePath);return Ot(await re.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await ur(e,s),d=await mr(e);return{item_files_on_disk:r.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import pt from"node:fs/promises";import{realpathSync as As}from"node:fs";import{execFile as Ts}from"node:child_process";import F from"node:path";import{promisify as Ps}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]="6a350683-275b-5d4d-ae02-45798b115f89")}catch{}})();var fr=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 pr(e){if(typeof e!="string")return;let t=e.trim();for(let n of fr)if(t===n.code||t.startsWith(`${n.code}:`))return n}function _r(e){let t={};for(let n of e){let i=pr(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function gn(e){return Object.values(_r(e))}import oe from"node:fs/promises";import{createHash as hr}from"node:crypto";import wn 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]="90364096-b94c-591c-9024-e697fa9322a5")}catch{}})();var kn=3,gr="history-drift-cache.json";function vn(e){return wn.join(e,"runtime",gr)}async function yr(e){try{let t=await oe.readFile(vn(e),"utf8"),n=JSON.parse(t);return n.version!==kn||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}function bn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function wr(e,t,n,i,r){let s=Ut(e),o;try{o=await oe.stat(s)}catch(l){return bn(l,"ENOENT")||r.unreadableStreams.push(ie),!1}let a=r.missingStreams.length,c=await Sn({itemId:ie,historyPath:s,stat:o,cached:t[ie],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.chainOk||r.chainMismatches.push(ie),n[ie]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk},c.cacheDirty):(r.missingStreams.splice(a),c.cacheDirty)}function En(e){return hr("sha256").update(e).digest("hex")}async function kr(e){let t=await oe.readFile(e,"utf8");return En(t)}async function vr(e){let t=await oe.readFile(e,"utf8"),n=En(t);if(t.trim().length===0)return null;let i=[],r=null;for(let s of t.split(/\r?\n/)){let o=s.trim();if(o.length===0)continue;let a=JSON.parse(o);if(typeof a.after_hash!="string"||a.after_hash.trim().length===0)throw new Error("missing after_hash");i.push(a),r=a.after_hash}return r?{latestAfterHash:r,chainOk:jt(i).ok,contentHash:n}:null}function br(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function yn(e,t,n){try{let i=await vr(t);return i||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Sn(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(br(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await yn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let i;if(e.verifyCacheHitByContent)try{i=await kr(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else i=t;return!e.verifyCacheHitByContent||i===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:i},cacheDirty:!1}:{verification:await yn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function In(e,t,n={}){let i={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[]},s=(await yr(e))?.entries??{},o={},a=!1,c=n.cacheHitVerification!=="metadata";for(let u of t){let m=xt(e,u.id),f;try{f=await oe.stat(m)}catch(E){bn(E,"ENOENT")?i.missingStreams.push(u.id):i.unreadableStreams.push(u.id);continue}let w=s[u.id],p=await Sn({itemId:u.id,historyPath:m,stat:f,cached:w,verifyCacheHitByContent:c,accumulator:i});if(a||=p.cacheDirty,!p.verification)continue;p.verification.chainOk||i.chainMismatches.push(u.id),o[u.id]={mtime_ms:f.mtimeMs,ctime_ms:f.ctimeMs,size:f.size,content_hash:p.verification.contentHash,latest_after_hash:p.verification.latestAfterHash,chain_ok:p.verification.chainOk};let{body:_,...h}=u;Nt({metadata:h,body:_})!==p.verification.latestAfterHash&&i.hashMismatches.push(u.id)}let l=await wr(e,s,o,c,i);if(a||=l,a||Object.keys(s).length!==Object.keys(o).length){let u=vn(e);try{await oe.mkdir(wn.dirname(u),{recursive:!0}),await ce(u,JSON.stringify({version:kn,entries:o}))}catch{}}let d=[...new Set([...i.missingStreams,...i.unreadableStreams,...i.hashMismatches,...i.chainMismatches])].sort((u,m)=>u.localeCompare(m));return{...i,driftedItems:d}}(function(){try{var e=typeof window<"u"?window:typeof 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 Er=["metadata","resolution"],et=["metadata","resolution","estimates","lifecycle"],Sr="completed";function tt(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Rn(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function xn(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=Rn(n.close_reason)??Sr;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${tt(i)}`,gate:"resolution"})}return t}function Cn(e){let t=[];for(let n of e){let i=Rn(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${tt(i)}`,gate:"metadata"})}return t}function An(e,t){return e.map(n=>{let i=Bt(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function Tn(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 Pn(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=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 ${i} ${n.item_id} --remove ${tt(n.path)}`})}return t}function Fn(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new y(`--fix-scope values must not be empty. Supported values: ${et.join(", ")}.`,g.USAGE);return new Set(Er)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(et.includes(r)){n.add(r);continue}throw new y(`Unknown --fix-scope value "${i}". Supported values: ${et.join(", ")}.`,g.USAGE)}return n}function Ln(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function ge(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 Ir=/^([A-Z][A-Z0-9]*-\d+)\b/;function Rr(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=Ir.exec(t);return n?n[1]:null}function $n(e){return typeof e=="string"&&e.trim().length>0}function Dn(e){let t=new Map;for(let i of e){if(typeof i.title!="string"||$n(i.duplicate_of))continue;let r=Rr(i.title);if(r===null)continue;let s=t.get(r);s||(s=[],t.set(r,s)),s.some(o=>o.id===i.id)||s.push({id:i.id,title:i.title,parent:$n(i.parent)?i.parent.trim():null})}let n=[];for(let[i,r]of t){if(r.length<2)continue;let s=new Set(r.map(c=>c.id.toLowerCase())),o=r.filter(c=>c.parent===null||!s.has(c.parent.toLowerCase()));if(o.length<2)continue;let a=[...o].sort((c,l)=>c.id.localeCompare(l.id));n.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return n.sort((i,r)=>i.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 Mn(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,s)=>r.localeCompare(s))){let r=t.get(i),s={};for(let o of[...r.keys()].sort((a,c)=>a.localeCompare(c)))s[o]=r.get(o);n[i]=s}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 On=3;function Nn(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function jn(e,t,n=On){let i=Number.isFinite(n)&&n>=1?Math.floor(n):On,r=new Map;for(let s of t){let o=Nn(s);if(o.length===0)continue;let a=r.get(o);a?a.push(s):r.set(o,[s])}return e.map(s=>{let o=(r.get(Nn(s))??[]).filter(a=>a!==s).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:o.slice(0,i),candidates_truncated:o.length>i}})}function Un(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]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var xr=/^[a-z][a-z0-9+.-]+:\/\//i;function ye(e){return xr.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof 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 Cr(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function zn(e){return`${e.item_id} ${e.link_kind}`}function Bn(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=Cr(r.classification,i.classification),r.owners.set(zn(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[zn(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(s=>{let o=t(s.item_id);return{id:s.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:s.link_kind}}).sort((s,o)=>{let a=s.id.localeCompare(o.id);return a!==0?a:s.field.localeCompare(o.field)})}))}function Ar(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Gn(e){let t=[];for(let n of e)for(let i of n.items)t.push(`${n.path}:${n.classification} owner=${i.id} status=${i.status} field=${i.field} title="${Ar(i.title)}"`);return t}import{execFile as Tr}from"node:child_process";import{realpath as Pr}from"node:fs/promises";import Wn from"node:path";import{promisify as Fr}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 Lr=Fr(Tr),$r=32*1024*1024,Dr=1e4,Mr=["search/eval-queries.json"];function nt(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Or(e){return`'${e.replaceAll("'","'\\''")}'`}async function Nr(e,t=Pr){return t(e).catch(()=>Wn.resolve(e))}async function qn(e){let t=await pe(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 Nr(e),i=nt(Wn.relative(t,n));if(i.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let r=We.map(s=>`${i}/${nt(s)}`);try{let{stdout:s}=await Lr("git",["ls-files","-z","--",...r.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:$r,windowsHide:!0,timeout:Dr}),o=new Set(Mr.map(l=>`${i}/${l}`)),a=[...new Set(s.split("\0").filter(l=>l.length>0&&!o.has(nt(l))))].sort((l,d)=>l.localeCompare(d)),c=r.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>Or(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import jr from"node:fs/promises";import D from"node:path";import Ur from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3fe80124-596b-591c-9f0d-fbbc129c6bb4")}catch{}})();var zr=["path","scope","note"],Br=["pattern","glob","path","scope","note"],Gr=["path"],Wr=["from","to"],qr=new Set(["note","scope"]);function Kn(e){let t=e??"project";if(!Oe.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${Oe.join(", ")} (default: project).`,g.USAGE);return t}function Vn(e){return e.startsWith("```")||e.includes(`
13
- `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:Vt(e)}function Hr(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Vn(n)||!n.includes(",")?[t]:Jt(n)})}function Kr(e,t){return e?Hr(e).map(n=>{let i=n.trim(),r=Vn(i)?de(n,"--add"):{path:i};if(ue(r,"--add",zr),!r.path)throw new y(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return{path:r.path,scope:Kn(r.scope),note:r.note?.trim()||void 0}}):[]}function Vr(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=de(n,"--add-glob");ue(i,"--add-glob",Br);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new y("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:r,scope:Kn(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Yr(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=de(n,"--remove"),r=Object.keys(i).filter(s=>qr.has(s.toLowerCase()));if(r.length>0)throw new y(`--remove identifies a linked artifact by path only and does not accept ${r.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,g.USAGE);if(ue(i,"--remove",Gr),!i.path)throw new y("--remove key/value form requires path=<value>",g.USAGE);return i.path}return n}):[]}function Jr(e){return e?e.map(t=>{let n=de(t,"--migrate");ue(n,"--migrate",Wr);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new y("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:i,to:r}}):[]}function it(e,t){let n=e;for(let i of t)n.startsWith(i.from)&&(n=`${i.to}${n.slice(i.from.length)}`);return n}function H(e){return e.split(D.sep).join("/")}function rt(e,t,n=process.cwd()){let i=e.trim();if(ye(i))return i;if(D.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return H(i.replaceAll("\\",D.sep));let r=D.relative(t,n);return r.startsWith(`..${D.sep}`)||r===".."||D.isAbsolute(r)?H(D.normalize(i)):H(D.relative(t,D.resolve(n,i)))}async function Xr(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){let s=D.isAbsolute(r.pattern),o=await Ur(r.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(o.map(c=>rt(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of a)i.push({path:c,scope:r.scope,note:r.note})}return i}function Zr(e,t,n){if(t===void 0)return e;if(!n)throw new y("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",g.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function Qr(e){return`${e.path}::${e.scope}`}function st(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function ot(e){return[...new Map(e.map(t=>[Qr(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function es(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),i=[],r=[],s=[],o=[];for(let a of n){if(ye(a)){o.push(a.trim());continue}let c=D.isAbsolute(a)?a:D.resolve(t,a);try{(await jr.stat(c)).isFile()?i.push(a):s.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&l.code==="ENOENT"){r.push(a);continue}s.push(a)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:s,remote_references:o}}function ts(e,t,n,i){let r=0;for(let o=0;o<e.length;o+=1){let a=it(e[o].path,i);a!==e[o].path&&(e[o]={...e[o],path:a},r+=1)}return{adds:t.map(o=>{let a=it(o.path,i);return a!==o.path&&(r+=1),{...o,path:a}}),removes:n.map(o=>it(o,i)),count:r}}function ns(e,t,n,i){for(let s of t)e.some(o=>o.path===s.path&&o.scope===s.scope)||e.push(s);if(n.length>0)for(let s=e.length-1;s>=0;s-=1)n.includes(e[s].path)&&e.splice(s,1);let r=ot(e);return i?r:st(r)}async function Hn(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths?await es(t,e.workspaceRoot):void 0}}async function Ce(e,t,n,i){let{metadataKey:r}=i,s=Yt(),o=B(process.cwd(),n.path),a=le(o),c=process.cwd();if(!await L(O(o)))throw new y(`Tracker is not initialized at ${o}. Run pm init first.`,g.NOT_FOUND);let l=await $(o),d=z(l,q()),u=await s.resolveList(t.add,"--add"),m=await s.resolveList(t.addGlob,"--add-glob"),f=await s.resolveList(t.remove,"--remove"),w=await s.resolveList(t.migrate,"--migrate"),p=Kr(u,i.bareNoun).map(T=>({...T,path:rt(T.path,a,c)})),_=Vr(m),h=await Xr(_,a,c),v=Zr([...p,...h],t.note,p.length>0||_.length>0),E=Yr(f).map(T=>rt(T,a,c)),S=Jr(w);if(!(v.length>0||E.length>0||S.length>0)){let T=await ve(o,e,l.id_prefix,l.item_format,d.type_to_folder);if(!T)throw new y(`Item ${e} not found`,g.NOT_FOUND);let R=(await be(T,{schema:l.schema})).document.metadata[r]??[];return Hn({id:T.id,artifacts:R,changed:!1,options:t,workspaceRoot:a})}let W=ne(t.author,l.author_default),j=await Ee({pmRoot:o,settings:l,id:e,op:i.op,author:W,message:t.message,force:t.force,skipNoop:!0,mutate(T){let k=T.metadata,R=k[r]??[],te=[...R],Z=ts(te,v,E,S),Me=ns(te,Z.adds,Z.removes,i.supportsAppendStable&&t.appendStable===!0);Me.length>0?k[r]=Me:delete k[r];let wt=!Ct(R,Me);return{changedFields:wt?[r]:[],warnings:wt&&Z.count>0?[`path_migrations_applied:${Z.count}`]:[]}}}),b=j.item[r]??[],A=j.warnings.find(T=>T.startsWith("path_migrations_applied:")),U=A?Number(A.slice(24)):0;return Hn({id:j.item.id,artifacts:b,changed:j.changedFields.includes(r),migrationsApplied:U,options:t,workspaceRoot:a})}function Ae(e,t){let n={};for(let[i,r]of Object.entries(e))n[i==="artifacts"?t:i]=r;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]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function Yn(e,t,n){let i=await Ce(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Ae(i,"docs")}import Jn from"node:fs/promises";import M from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5e45d0f1-a1a7-50ea-a9a3-ec6283d3471d")}catch{}})();var is=32768;function at(e){return H(M.normalize(e))}async function Te(e){try{return await Jn.realpath(e)}catch{return M.resolve(e)}}function ae(e,t){let n=M.isAbsolute(e.path)?M.resolve(e.path):M.resolve(t,e.path);return`${at(n)}::${e.scope}`}function Pe(e,t,n){if(typeof e=="string"){let i=e.trim();i.length>0&&n.push({field:t,value:i});return}if(Array.isArray(e)){e.forEach((i,r)=>Pe(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))Pe(r,t?`${t}.${i}`:i,n)}function rs(e){let t=[];return Pe(e.metadata,"metadata",t),Pe(e.body,"body",t),t}function ss(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function os(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,i=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let r of e){let s=new Set,o=r.value.slice(0,is);for(let[a,c]of[[n,r.value],[i,o]]){a.lastIndex=0;for(let l of c.matchAll(a)){let d=ss(l[0]);!d||s.has(d)||(s.add(d),t.push({field:r.field,value:d}))}}}return t}async function as(e,t,n=t){let i=M.isAbsolute(e)?M.resolve(e):M.resolve(n,e),r;try{r=await Jn.stat(i)}catch{return}if(!r.isFile())return;let[s,o]=await Promise.all([Te(t),Te(i)]);if(Ne(s,o)){let a=M.relative(s,o);return!a||a.startsWith("..")||M.isAbsolute(a)?void 0:{path:at(a),scope:"project"}}return{path:at(i),scope:"global"}}async function cs(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>ae(c,t))),r=new Map,s=os(rs(e)),o=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{o.set(c,await as(c,t,n))}));let a=s.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:l}of a){if(!l)continue;let d=ae(l,t),u=r.get(d)??{path:l.path,scope:l.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,r.set(d,u)}return[...r.entries()].map(([c,l])=>({path:l.path,scope:l.scope,status:i.has(c)?"already_linked":"addable",source_count:l.sourceCount,source_fields:[...l.sourceFields].sort((d,u)=>d.localeCompare(u)),original_paths:[...l.originalPaths].sort((d,u)=>d.localeCompare(u))})).sort((c,l)=>{let d=c.status.localeCompare(l.status);if(d!==0)return d;let u=c.path.localeCompare(l.path);return u!==0?u:c.scope.localeCompare(l.scope)})}async function Xn(e,t,n){let i=await Ce(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Ae(i,"files")}async function ls(e,t){let n=await Te(t),i=await Promise.all(e.map(async s=>{let o=s.trim();if(!o)throw new y("Files lookup paths must not be empty.",g.USAGE);if(!M.isAbsolute(o))return H(o);let a=await Te(o);return Ne(n,a)?H(M.relative(n,a)):H(a)})),r=[...new Set(i)].sort((s,o)=>s.localeCompare(o));if(r.length===0)throw new y("Files lookup requires at least one path.",g.USAGE);return r}function ds(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new y(`Files lookup ${i} must be a non-negative integer.`,g.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function Zn(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}async function us(e){if([e.strictRead,e.noTruncate,Pt()].includes(!0))return null;let t=await qt(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Wt({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function ms(e){let t=[],i=(await Ht(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema)).map(o=>({item:o,files:(o.files??[]).filter(a=>e.paths.includes(H(a.path))&&(e.scope===void 0||a.scope===e.scope)).sort((a,c)=>{let l=a.path.localeCompare(c.path);return l===0?a.scope.localeCompare(c.scope):l})})).filter(o=>o.files.length>0).sort((o,a)=>{let c=o.item.priority-a.item.priority;if(c!==0)return c;let l=a.item.updated_at.localeCompare(o.item.updated_at);return l===0?o.item.id.localeCompare(a.item.id):l}),r=t.filter(o=>/^item_list_(?:item|directory)_read_failed:/u.test(o));if(e.strictRead&&r.length>0)throw new y(`Files lookup could not read every item: ${r.join("; ")}`,g.GENERIC_FAILURE);let s=i.slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:s.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+s.length<i.length,truncated:e.offset+s.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:s.map(o=>({item:Zn(o.item),files:o.files}))}}async function Mc(e,t){let n=B(process.cwd(),t.path),i=le(n);if(!await L(O(n)))throw new y(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let r=await ls(e.paths,i),s=await $(n),o=z(s,q()),{offset:a,limit:c}=ds(e),l=await us({pmRoot:n,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0});return l?{paths:r,total:l.total,count:l.matches.length,offset:a,limit:c,has_more:a+l.matches.length<l.total,truncated:a+l.matches.length<l.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:l.matches.map(d=>({item:Zn(d.item),files:d.files}))}:ms({pmRoot:n,settings:s,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0})}async function Oc(e,t,n){let i=B(process.cwd(),n.path),r=le(i);if(!await L(O(i)))throw new y(`Tracker is not initialized at ${i}. Run pm init first.`,g.NOT_FOUND);let s=await $(i),o=z(s,q()),a=await ve(i,e,s.id_prefix,s.item_format,o.type_to_folder);if(!a)throw new y(`Item ${e} not found`,g.NOT_FOUND);let c=await be(a,{schema:s.schema}),l=await cs(c.document,r,process.cwd()),d=l.filter(b=>b.status==="addable"),u=l.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let b=c.document.metadata.files??[];return{id:a.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let w=ne(t.author,s.author_default),p=d.map(b=>({path:b.path,scope:b.scope,note:f})),_=[],h=new Set,v=await Ee({pmRoot:i,settings:s,id:e,op:"files_discover",author:w,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let A=[...b.metadata.files??[]],U=new Set(A.map(R=>ae(R,r)));_=[],h.clear();for(let[R,te]of p.entries()){let Z=ae(te,r);U.has(Z)||(A.push(te),U.add(Z),_.push(te),h.add(R))}let T=ot(A),k=t.appendStable?T:st(T);return k.length>0?b.metadata.files=k:delete b.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==p.length?[`files_discover_skipped_existing:${p.length-_.length}`]:[]}}}),E=v.item.files??[],S=new Set(_.map(b=>ae(b,r))),I=E.filter(b=>S.has(ae(b,r))),W=d.filter((b,A)=>!h.has(A)),j=[...u,...W];return{id:v.item.id,files:E,changed:I.length>0,apply:!0,count:E.length,candidate_count:l.length,addable_count:d.length,added_count:I.length,skipped_existing_count:j.length,candidates:l,added:I,skipped_existing:j}}(function(){try{var e=typeof window<"u"?window:typeof 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 fs=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),ct=new Set(["--pm-path","--path","--author"]),ps={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"]),hs=new Set(["-c","--call"]),gs=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),ys=new Set(["-C","--prefix","--userconfig","--cache"]),jc=new Set(["--cwd"]),Uc=new Set(["--cwd"]),ws=new Set(["exec","x"]),zc=new Set(["run","run-script"]),Bc=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function ks(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function vs(e){let t=bs(e.split(" ").filter(s=>s.length>0));if(t.length===0)return null;let[n,...i]=t;if(Qn(n)||ei(n))return i;if(n==="node"&&i[0]&&ei(i[0]))return i.slice(1);let r=n==="npx"||n==="bunx"?lt(i):n==="pnpm"?Is(i):n==="npm"?Rs(i):null;return r&&(Qn(r.command)||Ss(r.command))?r.args:null}var ti=(e,t="pm")=>{let n=t.trim().toLowerCase(),i=n.length;for(;i>0&&n[i-1]==="-";)i-=1;let r=n.slice(0,i);if(r.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of ks(s)){let c=vs(a),l=c?xs(c):null,d=l&&fs.has(l.subcommand)?Cs(l.remaining,ps[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&o.add(d)}return[...o].sort((a,c)=>a.localeCompare(c))};function bs(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 Gc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(ct.has(n)){t+=2;continue}t+=1;continue}return n}}function Qn(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function Es(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 i=t.indexOf("@",n+1);return i===-1?t:t.slice(0,i)}function Ss(e){let t=Es(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function ei(e){return e==="dist/cli.js"||e==="./dist/cli.js"||e.endsWith("/dist/cli.js")}function lt(e){let t=0;for(;t<e.length;){let i=e[t];if(i==="--"){t+=1;break}if(!i.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(i);if(r){let s=r[1];return s?{command:s,args:e.slice(t+1)}:null}if(hs.has(i)){t+=1;break}t+=_s.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function ni(e,t){let n=0;for(;n<e.length;){let i=e[n];if(i==="--"){n+=1;continue}if(i.startsWith("-")){if(i.includes("=")){n+=1;continue}if(t.has(i)){n+=2;continue}n+=1;continue}return{subcommand:i,args:e.slice(n+1)}}return null}function Is(e){let t=ni(e,gs);return t?.subcommand!=="dlx"?null:lt(t.args)}function Rs(e){let t=ni(e,ys);return!t||!ws.has(t.subcommand)?null:lt(t.args)}function xs(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(ct.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Cs(e,t=new Set){for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")return e[n+1];if(!i.startsWith("-"))return i;!i.includes("=")&&(ct.has(i)||t.has(i))&&(n+=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]="f8048210-9e9f-585b-b0df-a34eca521cc3")}catch{}})();var Fs=["src","tests","docs"],Ls=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],$s=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),Ds=["resolution","expected_result","actual_result"],Ms=["default","tracked-all","tracked-all-strict"],ii=["core","strict","custom"],Le=["off","warn","error"];var ut=["author","acceptance_criteria","estimated_minutes","close_reason"],ci=[...ut,"reviewer","risk","confidence","sprint","release"],_t=Array.from(new Set(ci)),Os={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"},Ns={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"},js={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"},Us={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"},zs={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"},Bs=32*1024*1024,Gs=1e4,li=40,V=5,Ws=4096,qs=255,Hs=Ps(Ts);function di(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||(t[n]=typeof i=="object"&&i!==null?di(i):i);return t}function Ks(e){return{...e,checks:e.checks.map(t=>({...t,details:di(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 ee(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function ri(e){return ee(e).replace(/\/+$/,"")}function N(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 De(e,t){return Mt(e,t)??e}function we(e,t){return t.terminal_statuses.has(De(e,t))}function J(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Fe(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function Vs(e){let t=J(vt),n={blocked_reason:J(ke.blocked_reason),resolution:J(ke.resolution),actual_result:J(ke.actual_result)},i=J(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:J(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:J(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:J(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:Fe(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:Fe(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Fe(r.resolution,n.resolution)?"default":"settings",actual_result:Fe(r.actual_result,n.actual_result)?"default":"settings"}}}function ui(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(ii.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${ii.join(", ")}.`,g.USAGE)}function mi(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Le.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Le.join(", ")}.`,g.USAGE)}function fi(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Le.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Le.join(", ")}.`,g.USAGE)}function Ys(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>Os[n]).filter(n=>n!==void 0).sort((n,i)=>n.localeCompare(i))}function Js(e,t,n){let i=Ys(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...ut],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...ci],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:i.length>0?{profile:e,profile_source:t,required_fields:i,configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...ut],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var Xs=new Set(["acceptance_criteria","estimated_minutes"]);function pi(e,t,n,i){return!i&&Xs.has(t)&&we(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"?De(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 _i(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 y(`Unknown --scan-mode value "${e}". Supported values: ${Ms.join(", ")}.`,g.USAGE)}function hi(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return F.resolve(t);let n=F.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return F.dirname(F.dirname(n));let r=F.resolve(process.cwd()),s=si(n),o=si(r),a=F.relative(s,o);return a.length===0||!a.startsWith("..")&&!F.isAbsolute(a)?n:r}function si(e){try{return As.native(e)}catch{return F.resolve(e)}}function gi(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function ht(e,t,n){let i=t.length>0?F.join(e,t):e,r;try{r=await pt.readdir(i,{withFileTypes:!0})}catch(s){if(gi(s,["ENOENT"]))return;throw s}for(let s of r){if(s.name.startsWith("."))continue;let o=t.length>0?F.join(t,s.name):s.name;if(s.isDirectory()){if($s.has(s.name))continue;await ht(e,o,n);continue}s.isFile()&&n.push(ee(o))}}async function mt(e){let t=[];for(let n of Fs)await ht(e,n,t);for(let n of Ls){let i=F.join(e,n);try{(await pt.stat(i)).isFile()&&t.push(ee(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function yi(e){try{let{stdout:t}=await Hs("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:Bs,windowsHide:!0,timeout:Gs}),n=t.split("\0").map(i=>ee(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function Zs(e,t){let n=new Set,i=ri(kt);i.length>0&&n.add(i);let r=ri(F.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((s,o)=>s.localeCompare(o))}function oi(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function Qs(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await yi(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await mt(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await mt(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function C(e,t=V){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function X(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=C(e,li);return{values:n.values,truncated:n.truncated,total:e.length}}var eo={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},to={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function no(e){let t=e.missing_fields.map(n=>`${eo[n]} "${to[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function wi(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(o=>typeof o=="string"):gn(t);if(r.length===0)return;let s=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...s?{fix_hints_truncated:!0}:{}}}function ki(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 io="validate_metadata_duplicate_issue_codes";function vi(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:V,i=e.slice(0,n);return{rows:i.map(s=>({code:s.code,count:s.count,ids:s.ids,titles:s.titles,remediation_hint:`Items ${s.ids.join(", ")} share issue code "${s.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${io}:${e.length}`]}}function ro(){return Object.fromEntries(_t.map(e=>[e,[]]))}function so(e,t,n){let i=ro();for(let r of e)for(let s of _t)pi(r,s,t,n)&&i[s].push(r.id);return i}function oo(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let s=t[r];s.length>0&&i.push(`${Ns[r]}:${s.length}`)}return i.push(...n),i}function bi(e,t){let n={};for(let i of e.required_fields){let r=t[i],s=r?r.length:0,o=js[i];s>0&&o&&(n[o]=s)}return n}function Ei(e,t,n){let i=[];for(let r of e.required_fields){let s=t[r];if(s)for(let o of s){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";i.push({item_type:c,field:r})}}return i}function ao(e,t,n,i){for(let r of t.required_fields){let s=n[r];if(!s||s.length===0)continue;let o=Us[r],a=zs[r];if(!o||!a)continue;let c=C(s,i?s.length:V);e[o]=c.values,e[a]=c.truncated}}function Si(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:P(n.get(r)?.resolution)})):[]}function Ii(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:P(n.get(r)?.type)})):[]}function co(e,t,n,i){let r=new Map(e.map(_=>[_.id,_])),s=t.profile==="strict",o=so(e,n,s),a=Dn(e),c=vi(a,i),l=oo(t,o,c.warnings),d=bi(t,o),u=Ei(t,o,r),m=Mn(u),f={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:[..._t],counts:d,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&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),ao(f,t,o,i);let w=Si(t,o,r),p=Ii(t,o,r);return{check:{name:"metadata",status:l.length===0?"ok":"warn",details:f},warnings:l,closeReasonBackfillRows:w,estimateBackfillRows:p}}function lo(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(m=>i.has(De(m.status,t))),s=[],o=[];for(let m of r){let f=Ds.filter(w=>!P(m[w]));f.length!==0&&(s.push({id:m.id,missing_fields:f}),o.push({id:m.id,missing_fields:f,close_reason:P(m.close_reason)}))}let a=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:V,l=C(s.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=s.map(m=>no(m)),u=C(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",details:{checked_closed_items:r.length,missing_resolution_items:s.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function Ri(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xi(e,t="pm",n=je()){let i=new Set(e.map(s=>s.id)),r=[...e].sort((s,o)=>s.id.localeCompare(o.id));return new Map(r.map(s=>{let o=new Set,a=N(s.blocked_by);a&&i.has(a)&&o.add(a),(s.dependencies??[]).filter(l=>{let d=N(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>N(l.id)).filter(l=>l!==void 0&&i.has(l)).forEach(l=>o.add(l));let c=N(s.definition_of_ready);return Ai(c??"",t).filter(l=>i.has(l)).forEach(l=>o.add(l)),[s.id,[...o].sort((l,d)=>l.localeCompare(d))]}))}function Ci(e,t,n){let i=Xt(e,n?d=>we(d,n):void 0),r=i.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),s=i.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),o=t?Number.POSITIVE_INFINITY:V,a=C(r,o),c=C(s,o),l=C(i.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.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+s.length,active_dangling_reference_count:r.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:i.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:i.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function Ai(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${Ri(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,s)=>r.localeCompare(s))}function gt(e){let t=0,n=new Map,i=new Map,r=[],s=new Set,o=[],a=d=>{n.set(d,t),i.set(d,t),t+=1,r.push(d),s.add(d);for(let m of e.get(d)??[])n.has(m)?s.has(m)&&i.set(d,Math.min(i.get(d),n.get(m))):(a(m),i.set(d,Math.min(i.get(d),i.get(m))));if(i.get(d)!==n.get(d))return;let u=[];for(;r.length>0;){let m=r.pop();if(s.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),o.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return o.filter(d=>{if(d.length>1)return!0;let u=d[0];return(e.get(u)??[]).includes(u)}).sort((d,u)=>d[0].localeCompare(u[0])||d.length-u.length||d.join(",").localeCompare(u.join(",")))}function yt(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],s=new Set([n]),o=a=>{let c=(t.get(a)??[]).filter(l=>i.has(l));for(let l of c){if(l===n&&r.length>1)return r.push(n),!0;if(!s.has(l)){if(s.add(l),r.push(l),o(l))return!0;r.pop(),s.delete(l)}}return!1};return o(n)?[...r]:[...e,n]}function Ti(e,t="pm"){let n=xi(e,t),i=gt(n),r=[...new Set(i.flat())].sort((o,a)=>o.localeCompare(a)),s=i.map(o=>yt(o,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:s}}function Pi(e,t=je()){let n=new Map(e.map(s=>[s.id.toLowerCase(),s.id])),i=new Map(e.map(s=>[s.id,[]]));return[...e].sort((s,o)=>s.id.localeCompare(o.id)).forEach(s=>{let o=i.get(s.id),a=N(s.parent),c=a?n.get(a.toLowerCase()):void 0;c&&o.push(c),(s.dependencies??[]).forEach(l=>{let d=t.resolve(l.kind);if(!d?.hierarchy)return;let u=n.get(l.id.toLowerCase());u&&(d.hierarchyDirection==="source_parent"?i.get(u).push(s.id):o.push(u))})}),i.forEach((s,o)=>{i.set(o,[...new Set(s)].sort((a,c)=>a.localeCompare(c)))}),i}function Fi(e){let t=Pi(e),n=gt(t),i=[...new Set(n.flat())].sort((s,o)=>s.localeCompare(o)),r=n.map(s=>yt(s,t).join("->"));return{cycle_count:n.length,cycle_item_ids:i,cycle_sample_paths:r}}function Li(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 $e(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function $i(e,t){let n=$e(e).split("/").filter(Boolean),i=$e(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function uo(e,t){let n=$e(t),i=$e(e),r=t.endsWith("/")?t:`${t}/`,s=e.startsWith(r),o=n.length>0&&n===i,a=$i(e,t);return!s&&!o&&a===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function mo(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function fo(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(s=>(i==="docs"?s.docs??[]:s.files??[]).map(o=>({item:s,link:o}))).forEach(({item:s,link:o})=>{if(o.scope!=="project")return;let a=ee(o.path);if(a.length===0||a===e)return;let c=uo(e,a);c!==null&&mo(r,s,c.score)&&(r={item:s,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 Di(e,t){return e.map(n=>{let i=Li(n),r=i==="docs_unowned"?"docs":"files",s=fo(n,i,t),o=s?.id??"<id>";return{path:n,classification:i,owner_candidate:s,remediation_hint:`pm ${r} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Mi(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function po(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=N(e[n]);return r?i.some(s=>r.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function _o(e,t,n,i,r){let s=N(t.parent),o=s?n.get(i.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!we(o.status,r)}}function ho(e,t,n,i){let r=N(e.blocked_by),s=N(e.blocked_reason),o=s?.toLowerCase(),a=De(e.status,n),c=[];return t.has(a)?(!r&&!s&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&i.stale_blocker_reason_patterns.some(l=>o.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function go(e,t,n,i){let r=new Map(e.map(c=>[c.id,c])),s=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=>!we(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=po(c,i);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=N(c.parent),u=d?r.get(s.get(d.toLowerCase())??d):void 0;if(u&&we(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(_o(c,u,r,s,n))),t){let m=ho(c,o,n,i);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,w)=>f.localeCompare(w))})}}return a}function yo(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 ai(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function wo(e,t,n,i,r,s){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=ai("validate_lifecycle_dependency_cycles",n,r),c=ai("validate_hierarchy_parent_cycle",i,s);return[...o,...a?[a]:[],...c?[c]:[]]}function Oi(e){let t=ee(e);return t.length>Ws||t.split(/[\\/]/).some(n=>n.length>qs)}async function ko(e,t){let n=F.isAbsolute(t)?t:F.resolve(e,t);if(Oi(n))return!1;try{let i=await pt.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return gi(i,["ENOENT","ENOTDIR"])}}async function vo(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(s=>({item:r,artifact:s,link_kind:"files"})),...(r.docs??[]).map(s=>({item:r,artifact:s,link_kind:"docs"}))]);for(let{item:r,artifact:s,link_kind:o}of i){if(s.scope!=="project")continue;if(ye(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let a=ee(s.path);a.length!==0&&(n.linkedProjectPaths.add(a),await ko(t,s.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:r.id,path:a,link_kind:o})))}return n}function bo(e,t,n,i,r,s){let o=i==="tracked-all-strict",a=o&&!r,c=r||o,l=c?[]:Zs(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>oi(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!oi(f,l)),m={};if(d.length>0){let f=X(d,s);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function Ni(e,t,n,i,r,s,o,a="pm"){let c=go(e,t,r,s);yo(c);let l=Ti(c.activeItems,a),d=Fi(e),u=wo(c,t,n,i,l.cycle_count,d.cycle_count),m=o?Number.POSITIVE_INFINITY:V,f=C(c.closureLikeRows.map(I=>`${I.id}:${I.fields.join(",")}`),m),w=C(c.terminalParentRows.map(I=>`${I.id}:${I.parent_id}:${I.parent_status}`),m),p=C(c.staleBlockerRows.map(I=>`${I.id}:${I.status}:${I.reasons.join(",")}`),m),_=C(l.cycle_item_ids,m),h=C(l.cycle_sample_paths,m),v=C(d.cycle_item_ids,m),E=C(d.cycle_sample_paths,m);return{check:{name:"lifecycle",status:l.cycle_count>0&&n==="error"||d.cycle_count>0&&i==="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:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:w.values,active_terminal_parent_rows_truncated:w.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:p.values,stale_blocker_rows_truncated:p.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:_.values,dependency_cycle_item_ids_truncated:_.truncated,dependency_cycle_sample_paths:h.values,dependency_cycle_sample_paths_truncated:h.truncated,parent_cycle_severity_policy:i,parent_cycle_count:d.cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:v.values,parent_cycle_item_ids_truncated:v.truncated,parent_cycle_sample_paths:E.values,parent_cycle_sample_paths_truncated:E.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function ji(e,t,n,i,r,s){let o=await vo(e,t),a=new Map(e.map(k=>[k.id,k])),c=[...new Set(o.missingLinkedPaths)].sort((k,R)=>k.localeCompare(R)),l=await Qs(t,i),d=bo(l,n,t,i,r,s),u=d.candidateFiles.filter(k=>!o.linkedProjectPaths.has(k)),m=Di(u,e),f=jn(c,d.candidateFiles),w=new Map(f.map(k=>[k.path,k.classification])),p=f.filter(k=>k.classification==="moved").length,_=o.staleLinkRows.map(k=>({...k,classification:w.get(k.path)??"deleted"})).sort((k,R)=>k.item_id.localeCompare(R.item_id)||k.path.localeCompare(R.path)||k.link_kind.localeCompare(R.link_kind)),h=[];d.strictModeForcesPmInternals&&h.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&h.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&h.push(`validate_files_orphaned_paths:${u.length}`);let v=[...o.remoteLinkedPaths].sort((k,R)=>k.localeCompare(R)),E=X(v,s),S=X(c,s),I=X(u,s),W=X(m.map(k=>`${k.path}:${k.classification}:owner_candidate=${k.owner_candidate?.id??"unowned"}`),s),j=s?m:X(Mi(m),!1).values,b=X(Un(f),s),A=_.map(k=>({item_id:k.item_id,path:k.path,link_kind:k.link_kind,classification:k.classification})),U=Bn(A,k=>{let R=a.get(k);return R?{type:R.type,title:R.title,status:R.status}:void 0}),T=s?U:X(Gn(U),!1).values;return{check:{name:"files",status:h.length===0?"ok":"warn",details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:d.strictTrackedAllMode,strict_mode_forces_pm_internals:d.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:d.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:s?"full":"summary",file_list_summary_limit:li,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:r,pm_internal_candidate_prefixes:d.pmInternalCandidatePrefixes,pm_internal_excluded_count:d.excludedPmInternalPaths.length,excluded_total:d.excludedPmInternalPaths.length,excluded_by_reason:d.excludedByReason,linked_project_paths:o.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:E.total,remote_linked_paths:E.values,remote_linked_paths_truncated:E.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:d.candidateFiles.length,candidate_scanned:d.candidateFiles.length,scanned_candidate_files:d.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:S.total,missing_linked_paths:S.values,missing_linked_paths_truncated:S.truncated,missing_linked_paths_moved_count:p,missing_linked_paths_deleted_count:c.length-p,missing_linked_path_classifications:b.values,missing_linked_path_classifications_truncated:b.truncated,missing_linked_path_rows_count:U.length,missing_linked_path_rows:T,orphaned_paths_count:u.length,orphaned_paths_total:I.total,orphaned_paths:I.values,orphaned_paths_truncated:I.truncated,orphaned_path_classifications:W.values,orphaned_path_classifications_truncated:W.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:j}},warnings:h,staleLinkPruneRows:_}}async function Eo(e,t,n){let{missingStreams:i,unreadableStreams:r,hashMismatches:s,chainMismatches:o,driftedItems:a}=await In(e,t),c=[];i.length>0&&c.push(`validate_history_drift_missing_streams:${i.length}`),r.length>0&&c.push(`validate_history_drift_unreadable_streams:${r.length}`),s.length>0&&c.push(`validate_history_drift_hash_mismatches:${s.length}`),o.length>0&&c.push(`validate_history_drift_chain_mismatches:${o.length}`);let l=n?Number.POSITIVE_INFINITY:V,d=C(a,l);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,drifted_items_count:a.length,drifted_items:d.values,drifted_items_truncated:d.truncated,counts:{missing_streams:i.length,unreadable_streams:r.length,hash_mismatches:s.length,chain_mismatches:o.length}}},warnings:c}}function So(e,t,n){let i=n.trim().replaceAll(/\s+/g," "),r=i.length>120?`${i.slice(0,117)}...`:i;return`${e}:${t}:${r}`}function Ui(e,t,n){let i=new Set(e.map(_=>_.id.toLowerCase())),r=0,s=0,o=new Set,a=[],c=e.flatMap(_=>(_.tests??[]).map(h=>({item:_,linkedTest:h})));for(let{item:_,linkedTest:h}of c){if(typeof h.command!="string"||h.command.trim().length===0)continue;r+=1;let v=ti(h.command,t);if(v.length!==0){s+=v.length;for(let E of v)o.add(E),i.has(E.toLowerCase())||a.push(So(_.id,E,h.command))}}let l=[...new Set(a)].sort((_,h)=>_.localeCompare(h)),d=[...new Set(l.map(_=>_.split(":")[1]??""))].filter(_=>_.length>0).sort((_,h)=>_.localeCompare(h)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],m=n?Number.POSITIVE_INFINITY:V,f=C(l,m),w=C(d,m),p=C([...o].sort((_,h)=>_.localeCompare(h)),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:s,unique_referenced_pm_ids_count:o.size,unique_referenced_pm_ids:p.values,unique_referenced_pm_ids_truncated:p.truncated,stale_pm_id_references_count:l.length,stale_pm_ids_count:d.length,stale_pm_ids:w.values,stale_pm_ids_truncated:w.truncated,stale_pm_id_reference_rows:f.values,stale_pm_id_reference_rows_truncated:f.truncated}},warnings:u}}function Io(e,t){let n=Dt(e.map(c=>({ref:c.id,version:$t(c)}))),i=[];n.outdated.length>0&&i.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&i.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:V,s=C(n.outdated,r),o=C(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:Lt,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:i}}var ft="pm validate auto-fix";async function zi(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:ft};if(e.kind==="set_resolution"?i.resolution=e.value:e.kind==="set_close_reason"?i.closeReason=e.value:e.kind==="set_estimate"?i.estimatedMinutes=e.value:e.kind==="reparent"?i.parent=e.parent_id:i.unset=["parent"],!n.runUpdate)throw new y("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.USAGE);await n.runUpdate(e.item_id,i,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 dt(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Bi(e,t,n){let i=[],r=[],s=new Map;for(let o of e.filter(a=>dt(a)===null))try{await zi(o,t,n),i.push(o)}catch(a){r.push({fix:o,error:a})}for(let o of e.filter(a=>dt(a)!==null)){let a=dt(o),c=s.get(a);c?c.push(o):s.set(a,[o])}for(let o of s.values()){let a=o[0];if(!a)continue;let c=o.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await Xn(a.item_id,{remove:c,message:ft},t):await Yn(a.item_id,{remove:c,message:ft},t),i.push(...o)}catch(l){r.push(...o.map(d=>({fix:d,error:l})))}}return{applied:i,failed:r}}var Al={applyValidateFix:zi,applyValidateFixes:Bi,attachValidateFixHints:wi,buildCommandReferencesCheck:Ui,buildDependencyReferencesCheck:Ci,buildCloseReasonBackfillRows:Si,buildFilesCheck:ji,buildLifecycleCheck:Ni,buildLifecycleDependencyGraph:xi,buildLifecycleParentGraph:Pi,buildEstimateBackfillRows:Ii,buildMetadataCounts:bi,buildMissingFieldOccurrences:Ei,buildOrphanedPathRows:Di,classifyOrphanedPath:Li,collectDefaultProjectFileCandidates:mt,collectTrackedGitFileCandidates:yi,detectLifecycleDependencyCycles:Ti,detectLifecycleParentCycles:Fi,escapeRegExp:Ri,extractItemIds:Ai,findLifecycleDependencyCycleComponents:gt,isMetadataFieldMissing:pi,linkedArtifactPathExceedsFilesystemLimits:Oi,listFilesRecursive:ht,resolveDependencyCycleSeverity:mi,resolveParentCycleSeverity:fi,resolveFileScanMode:_i,resolveLifecycleDependencyCycleSamplePath:yt,resolveRequestedChecks:ki,resolveValidateMetadataProfile:ui,resolveWorkspaceRoot:hi,sharedDirectoryPrefixLength:$i,summarizeOrphanedPathRows:Mi,summarizeDuplicateIssueCodes:vi,toMeaningfulString:N};async function Ro(e,t,n,i){let r=await hn(e,new Set(t.map(m=>m.id)),n,{schema:i.schema,extensionFieldNames:bt(q())}),s=[];r.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let o=s.length,a=await qn(e);a.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await ln(e,Ie(i));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await pe(e),d=l===null?null:await dn(l);d!==null&&d.status!=="ok"&&s.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await Ze(l);return u.length>0&&s.push(`validate_merge_decisions_unreviewed:${u.length}`),{check:{name:"storage_integrity",status:o>0?"error":s.length>0?"warn":"ok",details:{...r,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:u.length,pending_merge_decision_items:[...new Set(u.map(m=>m.item_id))].sort((m,f)=>m.localeCompare(f)),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:s}}function K(e,t,n){n&&wi(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function xo(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,i=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let r=co(e.items,e.metadataPolicy,e.statusRegistry,i);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows,K(t,r,n)}if(e.requestedChecks.has("resolution")){let r=lo(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,K(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=Ni(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,K(t,r,n),K(t,Ci(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await ji(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=r.staleLinkPruneRows,K(t,r,n)}return e.requestedChecks.has("command_references")&&K(t,Ui(e.items,e.settings.id_prefix,i),n),e.requestedChecks.has("history_drift")&&K(t,await Eo(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&K(t,Io(e.items,i),n),e.requestedChecks.has("storage_integrity")&&K(t,await Ro(e.pmRoot,e.items,z(e.settings,q()).type_to_folder,e.settings),n),t}function Co(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...Cn(t.closeReasonBackfillRows)),i.push(...xn(t.resolutionBackfillRows)),i.push(...An(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...Tn(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...Pn(t.staleLinkPruneRows)),i}async function Ao(e,t,n,i,r,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=Co(e,t,n),{applicable:a,gated:c}=Ln(o,i),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await Bi(a,r,s);d.push(...m.applied.map(ge)),u.push(...m.failed.map(({fix:f,error:w})=>({...ge(f),error:w instanceof Error?w.message:String(w)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...i].sort((m,f)=>m.localeCompare(f)),planned_count:o.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(ge),applied_fixes:d,gated_fixes:c.map(m=>({...ge(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function Tl(e,t,n={}){Tt(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new y("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new y("--fix-scope requires --auto-fix.",g.USAGE);let r=Fn(e.fixScope),s=B(process.cwd(),t.path);if(!await L(O(s)))throw new y(`Tracker is not initialized at ${s}. Run pm init first.`,g.NOT_FOUND);let o=await $(s),a=At(o.schema),c=z(o,q()),l=[],d=await Kt(s,o.item_format,c.type_to_folder,l,o.schema),u=ki(e);if(u.has("history_drift")){let A=await Je(s);A.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${A.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",f=ui(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),w=Js(f,m,o.validation.metadata_required_fields),p=Vs(o),_=mi(e.dependencyCycleSeverity),h=fi(e.parentCycleSeverity),v=_i(e.scanMode),E=hi(s),S=await xo({requestedChecks:u,options:e,global:t,pmRoot:s,workspaceRoot:E,settings:o,items:d,statusRegistry:a,metadataPolicy:w,lifecyclePatternPolicy:p,dependencyCycleSeverity:_,parentCycleSeverity:h,fileScanMode:v,initialWarnings:[...new Set(l)]}),I=i?await Ao(e,S,o,r,t,n):void 0,W=[...new Set(S.warnings)].sort((A,U)=>A.localeCompare(U)),b={ok:!S.checks.some(A=>A.status==="error"),has_warnings:W.length>0,checks:S.checks,warnings:W,...I!==void 0?{fixes:I}:{},generated_at:Y(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...Ks(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{$o as a,Q as b,fe as c,pe as d,Ye as e,Ie as f,ln as g,dn as h,Xo as i,Zo as j,Zi as k,In as l,_r as m,Qi as n,mn as o,oa as p,Je as q,aa as r,qn as s,ga as t,ya as u,Ze as v,wa as w,ka as x,hn as y,Yn as z,Xn as A,Mc as B,Oc as C,gs as D,ys as E,jc as F,Uc as G,zc as H,Bc as I,ks as J,vs as K,bs as L,Gc as M,Qn as N,Ss as O,ei as P,lt as Q,ni as R,Is as S,Rs as T,xs as U,Ks as V,Al as W,Tl as X};
14
- //# sourceMappingURL=chunk-DQ6FKGL3.js.map