@unbrained/pm-cli 2026.8.7 → 2026.8.8

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 (226) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +35 -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 +155 -691
  11. package/dist/cli-bundle/chunks/chunk-2ZMXX3Q6.js +2068 -0
  12. package/dist/cli-bundle/chunks/chunk-ALDHXLPS.js +3 -0
  13. package/dist/cli-bundle/chunks/chunk-CBLA33YK.js +8 -0
  14. package/dist/cli-bundle/chunks/chunk-GKA54IJM.js +5 -0
  15. package/dist/cli-bundle/chunks/chunk-KRY7SRUO.js +2 -0
  16. package/dist/cli-bundle/chunks/chunk-MNJ4NNSY.js +26 -0
  17. package/dist/cli-bundle/chunks/chunk-NUXRRNAB.js +77 -0
  18. package/dist/cli-bundle/chunks/chunk-OJPCFDDY.js +13 -0
  19. package/dist/cli-bundle/chunks/chunk-PFSD3DAN.js +194 -0
  20. package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +2 -0
  21. package/dist/cli-bundle/chunks/chunk-SQ7QZFQ6.js +2 -0
  22. package/dist/cli-bundle/chunks/{register-list-query-FJZCJ67O.js → register-list-query-WFZAMJHZ.js} +8 -8
  23. package/dist/cli-bundle/chunks/register-mutation-SOKKOTHQ.js +20 -0
  24. package/dist/cli-bundle/chunks/register-operations-5XQETS6E.js +2 -0
  25. package/dist/cli-bundle/chunks/register-setup-2HL5ZHMK.js +2 -0
  26. package/dist/cli-bundle/focused-chunks/chunk-54EU2UVO.js +2 -0
  27. package/dist/cli-bundle/focused-chunks/{chunk-VZFU2R4M.js → chunk-5FLBTZJQ.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/chunk-5GJ57YKN.js +2 -0
  29. package/dist/cli-bundle/focused-chunks/{chunk-HNL6IFGS.js → chunk-ANTMGYLI.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/chunk-CMDS3KYT.js +14 -0
  31. package/dist/cli-bundle/focused-chunks/{chunk-NBJKQP4S.js → chunk-DMKOMTTY.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-CIXVQPB7.js → chunk-F5B3HBEZ.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-R2LEMEV5.js → chunk-FI6DWU2M.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-3K4XV2BF.js → chunk-FNOKJG6N.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-RW5IYD4J.js → chunk-FPDYXZBK.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-QHRTT7WT.js → chunk-GWI6YIKJ.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-MHMTKV5V.js → chunk-HCUC62AB.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-MOTJFQ3F.js → chunk-HGNKPSCB.js} +12 -12
  39. package/dist/cli-bundle/focused-chunks/{chunk-4VJQTS3P.js → chunk-IAS7PMLG.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-TIKDBG4D.js → chunk-PL2EYDJK.js} +27 -27
  41. package/dist/cli-bundle/focused-chunks/chunk-SM2PJGP3.js +2 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-RPNYG5MO.js → chunk-TCSAPH33.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/chunk-U646T7Z6.js +18 -0
  44. package/dist/cli-bundle/focused-chunks/chunk-YKPE4PPY.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-YZEZAPJK.js → chunk-YSAHYUXX.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-73JUDYXT.js → chunk-ZOLDTUU7.js} +2 -2
  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/output/output.js +9 -2
  60. package/dist/core/sentry/helpers.d.ts +10 -0
  61. package/dist/core/sentry/helpers.js +59 -4
  62. package/dist/core/shared/constants.d.ts +2 -0
  63. package/dist/core/shared/constants.js +4 -2
  64. package/dist/sdk/annotations.d.ts +40 -0
  65. package/dist/sdk/annotations.js +61 -9
  66. package/dist/sdk/author-attribution.d.ts +12 -0
  67. package/dist/sdk/author-attribution.js +73 -11
  68. package/dist/sdk/cli-contracts/command-exit-contracts.d.ts +118 -0
  69. package/dist/sdk/cli-contracts/command-exit-contracts.js +152 -0
  70. package/dist/sdk/cli-contracts/completeness.js +5 -3
  71. package/dist/sdk/cli-contracts/flag-contracts.js +5 -2
  72. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +11 -0
  73. package/dist/sdk/cli-contracts/runtime-contracts.js +29 -2
  74. package/dist/sdk/cli-contracts/tool-parameter-tables.js +15 -2
  75. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  76. package/dist/sdk/cli-contracts/tool-schema.js +6 -3
  77. package/dist/sdk/comments.d.ts +7 -0
  78. package/dist/sdk/comments.js +2 -2
  79. package/dist/sdk/completion.js +9 -5
  80. package/dist/sdk/contracts.d.ts +1 -0
  81. package/dist/sdk/contracts.js +3 -2
  82. package/dist/sdk/environment/host-environment-errors.d.ts +27 -0
  83. package/dist/sdk/environment/host-environment-errors.js +124 -0
  84. package/dist/sdk/environment/project-runtime-compatibility.d.ts +65 -0
  85. package/dist/sdk/environment/project-runtime-compatibility.js +385 -0
  86. package/dist/sdk/environment/source-context.d.ts +23 -0
  87. package/dist/sdk/environment/source-context.js +29 -0
  88. package/dist/sdk/error-code-catalog.d.ts +6 -0
  89. package/dist/sdk/error-code-catalog.js +62 -8
  90. package/dist/sdk/generated-error-code-catalog.js +629 -3
  91. package/dist/sdk/governance/health.d.ts +11 -3
  92. package/dist/sdk/governance/health.js +5 -5
  93. package/dist/sdk/index.d.ts +7 -3
  94. package/dist/sdk/index.js +9 -5
  95. package/dist/sdk/learnings.d.ts +15 -0
  96. package/dist/sdk/learnings.js +2 -2
  97. package/dist/sdk/lifecycle/close-many.d.ts +6 -1
  98. package/dist/sdk/lifecycle/close-many.js +43 -5
  99. package/dist/sdk/lifecycle/update-many.d.ts +2 -1
  100. package/dist/sdk/lifecycle/update-many.js +29 -5
  101. package/dist/sdk/merge/index.d.ts +1 -1
  102. package/dist/sdk/merge/index.js +3 -3
  103. package/dist/sdk/merge/install.d.ts +21 -0
  104. package/dist/sdk/merge/install.js +50 -20
  105. package/dist/sdk/notes.d.ts +7 -0
  106. package/dist/sdk/notes.js +2 -2
  107. package/dist/sdk/read-output-contracts.js +83 -4
  108. package/dist/sdk/runtime.d.ts +1 -1
  109. package/dist/sdk/runtime.js +9 -25
  110. package/dist/sdk/test/execution.js +4 -2
  111. package/dist/sdk/test/parsers.js +5 -2
  112. package/dist/sdk/workspace-snapshot.d.ts +9 -0
  113. package/dist/sdk/workspace-snapshot.js +48 -16
  114. package/docs/AGENT_RUNTIME_PRIMITIVES.md +11 -4
  115. package/docs/README.md +1 -0
  116. package/docs/RELEASING.md +27 -2
  117. package/docs/SCRIPTING.md +27 -1
  118. package/docs/SDK_CONTEXT_INTEGRITY.md +66 -0
  119. package/docs/SDK_RUNTIME_BOUNDARIES.md +58 -0
  120. package/docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md +13 -0
  121. package/docs/TESTING.md +17 -0
  122. package/marketplace.json +2 -2
  123. package/package.json +5 -3
  124. package/packages/pm-beads/package.json +1 -1
  125. package/packages/pm-calendar/package.json +1 -1
  126. package/packages/pm-command-kit/package.json +1 -1
  127. package/packages/pm-digital-twin/package.json +1 -1
  128. package/packages/pm-governance-audit/package.json +1 -1
  129. package/packages/pm-guide-shell/package.json +1 -1
  130. package/packages/pm-kanban/package.json +1 -1
  131. package/packages/pm-lifecycle-hooks/package.json +1 -1
  132. package/packages/pm-linked-test-adapters/package.json +1 -1
  133. package/packages/pm-search-advanced/package.json +1 -1
  134. package/packages/pm-templates/package.json +1 -1
  135. package/packages/pm-todos/package.json +1 -1
  136. package/packages/pm-vcs/package.json +1 -1
  137. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  138. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  139. package/sdk/public-surface.json +529 -34
  140. package/dist/cli-bundle/chunks/append-7BXBFDGD.js +0 -2
  141. package/dist/cli-bundle/chunks/chunk-2AXF3VSK.js +0 -2
  142. package/dist/cli-bundle/chunks/chunk-2XS43CCV.js +0 -2
  143. package/dist/cli-bundle/chunks/chunk-3A6KWB72.js +0 -8
  144. package/dist/cli-bundle/chunks/chunk-3ISTDB42.js +0 -8
  145. package/dist/cli-bundle/chunks/chunk-4MTI7XOV.js +0 -5
  146. package/dist/cli-bundle/chunks/chunk-6BX5UDCN.js +0 -3
  147. package/dist/cli-bundle/chunks/chunk-6QPO7KLR.js +0 -2
  148. package/dist/cli-bundle/chunks/chunk-7MXHZHSQ.js +0 -5
  149. package/dist/cli-bundle/chunks/chunk-7ZPMJW4U.js +0 -2
  150. package/dist/cli-bundle/chunks/chunk-A6KGKEWT.js +0 -2
  151. package/dist/cli-bundle/chunks/chunk-AGYNSNCI.js +0 -2
  152. package/dist/cli-bundle/chunks/chunk-B4H7FEFH.js +0 -5
  153. package/dist/cli-bundle/chunks/chunk-B4KLBBMN.js +0 -2
  154. package/dist/cli-bundle/chunks/chunk-BXCSXK4J.js +0 -2
  155. package/dist/cli-bundle/chunks/chunk-CALJHNBL.js +0 -23
  156. package/dist/cli-bundle/chunks/chunk-CFIGP5LY.js +0 -2
  157. package/dist/cli-bundle/chunks/chunk-CHOQ2VAW.js +0 -2
  158. package/dist/cli-bundle/chunks/chunk-CS6MRHG7.js +0 -2
  159. package/dist/cli-bundle/chunks/chunk-CUGNQQKH.js +0 -2
  160. package/dist/cli-bundle/chunks/chunk-D4FPS43D.js +0 -164
  161. package/dist/cli-bundle/chunks/chunk-E2ZSLTOP.js +0 -2
  162. package/dist/cli-bundle/chunks/chunk-FB7G2HY2.js +0 -2
  163. package/dist/cli-bundle/chunks/chunk-H5Y5YE6A.js +0 -2
  164. package/dist/cli-bundle/chunks/chunk-H5Y6UV6E.js +0 -2
  165. package/dist/cli-bundle/chunks/chunk-H7KGWPDF.js +0 -2
  166. package/dist/cli-bundle/chunks/chunk-HFSD77TQ.js +0 -2
  167. package/dist/cli-bundle/chunks/chunk-HX2GTA6L.js +0 -2
  168. package/dist/cli-bundle/chunks/chunk-J2IEKAVR.js +0 -2
  169. package/dist/cli-bundle/chunks/chunk-JC6FKIFM.js +0 -2
  170. package/dist/cli-bundle/chunks/chunk-K44PYFXH.js +0 -2
  171. package/dist/cli-bundle/chunks/chunk-K4KGEEBT.js +0 -2
  172. package/dist/cli-bundle/chunks/chunk-KFLK5TRH.js +0 -21
  173. package/dist/cli-bundle/chunks/chunk-KL6IEBV2.js +0 -2
  174. package/dist/cli-bundle/chunks/chunk-KWQZDZSS.js +0 -2
  175. package/dist/cli-bundle/chunks/chunk-KZ4X3DGU.js +0 -3
  176. package/dist/cli-bundle/chunks/chunk-LD77HJMQ.js +0 -13
  177. package/dist/cli-bundle/chunks/chunk-LEPJJ6QC.js +0 -2
  178. package/dist/cli-bundle/chunks/chunk-ME2JJ4LA.js +0 -3
  179. package/dist/cli-bundle/chunks/chunk-NE5VRDAI.js +0 -2
  180. package/dist/cli-bundle/chunks/chunk-NFLJ3FHD.js +0 -2
  181. package/dist/cli-bundle/chunks/chunk-NG6OXIBR.js +0 -19
  182. package/dist/cli-bundle/chunks/chunk-NYIGHWQY.js +0 -8
  183. package/dist/cli-bundle/chunks/chunk-NZ75GNSA.js +0 -2
  184. package/dist/cli-bundle/chunks/chunk-PCJWJNC2.js +0 -2
  185. package/dist/cli-bundle/chunks/chunk-PD3225AM.js +0 -2
  186. package/dist/cli-bundle/chunks/chunk-PDEGKG7P.js +0 -2
  187. package/dist/cli-bundle/chunks/chunk-PIE5HBNA.js +0 -2
  188. package/dist/cli-bundle/chunks/chunk-PW2H7YJR.js +0 -56
  189. package/dist/cli-bundle/chunks/chunk-RSIC5OPE.js +0 -2
  190. package/dist/cli-bundle/chunks/chunk-TPKN3S7S.js +0 -2
  191. package/dist/cli-bundle/chunks/chunk-TPXAXTCO.js +0 -2
  192. package/dist/cli-bundle/chunks/chunk-UFWUJO4V.js +0 -2
  193. package/dist/cli-bundle/chunks/chunk-UQLZQVFW.js +0 -55
  194. package/dist/cli-bundle/chunks/chunk-VT3Z5G7D.js +0 -2
  195. package/dist/cli-bundle/chunks/chunk-WOD3WWUN.js +0 -2
  196. package/dist/cli-bundle/chunks/chunk-WSJEIGJF.js +0 -3
  197. package/dist/cli-bundle/chunks/chunk-WYNUU7ZW.js +0 -2008
  198. package/dist/cli-bundle/chunks/chunk-YGPNCCXZ.js +0 -2
  199. package/dist/cli-bundle/chunks/close-CMY3BAUG.js +0 -2
  200. package/dist/cli-bundle/chunks/close-many-SA4XZCTK.js +0 -2
  201. package/dist/cli-bundle/chunks/comments-EZ556ZD3.js +0 -2
  202. package/dist/cli-bundle/chunks/copy-ZSGPA52X.js +0 -2
  203. package/dist/cli-bundle/chunks/create-I5DVV4YG.js +0 -2
  204. package/dist/cli-bundle/chunks/delete-RL3JACSW.js +0 -2
  205. package/dist/cli-bundle/chunks/deps-S7UBCECS.js +0 -2
  206. package/dist/cli-bundle/chunks/docs-ZZNVBBYO.js +0 -2
  207. package/dist/cli-bundle/chunks/files-27C337VT.js +0 -2
  208. package/dist/cli-bundle/chunks/focus-5Z2SG7LU.js +0 -2
  209. package/dist/cli-bundle/chunks/history-compact-HJQK67CZ.js +0 -2
  210. package/dist/cli-bundle/chunks/history-redact-PWC6PDWA.js +0 -2
  211. package/dist/cli-bundle/chunks/history-repair-N3CY4WBF.js +0 -2
  212. package/dist/cli-bundle/chunks/learnings-4FH23XDT.js +0 -2
  213. package/dist/cli-bundle/chunks/profile-5Y5XXH5N.js +0 -2
  214. package/dist/cli-bundle/chunks/register-mutation-YGYPW3BL.js +0 -20
  215. package/dist/cli-bundle/chunks/register-operations-WMDSUMQF.js +0 -2
  216. package/dist/cli-bundle/chunks/register-setup-DL7FFABC.js +0 -2
  217. package/dist/cli-bundle/chunks/restore-6KYBV5BY.js +0 -2
  218. package/dist/cli-bundle/chunks/schema-EQGKBYXJ.js +0 -2
  219. package/dist/cli-bundle/chunks/update-QVTYOD6I.js +0 -2
  220. package/dist/cli-bundle/chunks/update-many-DJSBU525.js +0 -2
  221. package/dist/cli-bundle/focused-chunks/chunk-2ECLECMK.js +0 -12
  222. package/dist/cli-bundle/focused-chunks/chunk-4EX25PXM.js +0 -8
  223. package/dist/cli-bundle/focused-chunks/chunk-DLTS3IHM.js +0 -2
  224. package/dist/cli-bundle/focused-chunks/chunk-DQ6FKGL3.js +0 -14
  225. package/dist/cli-bundle/focused-chunks/chunk-JLG2C4EQ.js +0 -2
  226. package/dist/cli-bundle/focused-chunks/chunk-ZJIMJHDB.js +0 -2
@@ -0,0 +1,14 @@
1
+ import{f as xe,g as Ze}from"./chunk-IAS7PMLG.js";import{a as qt,g as Xe,i as Ht}from"./chunk-ZOLDTUU7.js";import{f as hn}from"./chunk-HCUC62AB.js";import{s as he,t as fn,u as ge,v as pn,wa as _n}from"./chunk-U646T7Z6.js";import{Ca as J,Da as an,Fa as sn,Ia as on,Ja as cn,K as le,L as ne,La as L,P as Jt,Ua as ln,V as Xt,W as Zt,Z as Qt,Za as dn,_ as en,ab as Ce,ba as Qe,bb as Ie,cb as un,da as tn,eb as mn,hb as Te,k as Y,na as nn,q as Yt,za as rn}from"./chunk-HGNKPSCB.js";import{D as H,I as Ut,J as j,K as _e,Ka as Vt,M as B,P as zt,T as M,_ as Gt,aa as Ke,h as Lt,o as $t,p as N,q as jt,r as pe,u as Ve,v as Bt}from"./chunk-FPDYXZBK.js";import{i as Kt}from"./chunk-FI6DWU2M.js";import{N as Nt,U as Mt,V as Ee,Y as _,Z as h,aa as Ye,ba as Wt,ca as Je,t as He}from"./chunk-54EU2UVO.js";import{readFile as Oe,realpath as rt,writeFile as wi}from"node:fs/promises";import{execFile as ki}from"node:child_process";import T from"node:path";import{promisify as vi}from"node:util";import{readFile as fi,writeFile as pi}from"node:fs/promises";import ye 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 yn="# pm-cli:runtime-cache:start",et="# pm-cli:runtime-cache:end",wn=".agents/pm",tt=["runtime/","search/","locks/","transactions/","checkpoints/"],_i=["search/eval-queries.json"];async function gn(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 h("The workspace .gitignore is not writable.",_.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 kn(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function nt(e){let t=e.replaceAll("\\","/");return ye.isAbsolute(e)||t===".."||t.startsWith("../")}function hi(e=wn){let t=kn(e);return[yn,...tt.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),..._i.map(n=>`!${t}/${n}`),et].join(`
2
+ `)}async function vo(e,t={}){let n=ye.join(e,".gitignore"),r=wn;if(t.pmRoot!==void 0){let d=kn(ye.relative(ye.resolve(e),ye.resolve(t.pmRoot)));if(nt(d))return{path:n,changed:!1};d.length>0&&(r=d)}let i="";try{i=await gn(()=>fi(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&d.code==="ENOENT"))throw d}let a=i.indexOf(yn),s=i.indexOf(et),c=(a>=0&&s>=a?`${i.slice(0,a)}${i.slice(s+et.length)}`:i).trimEnd(),l=`${c.length>0?`${c}
3
+
4
+ `:""}${hi(r)}
5
+ `;return l===i?{path:n,changed:!1}:(await gn(()=>pi(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]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var gi="PM_SOURCE_CONTEXT_ACCESS",yi="PM_ALLOW_SOURCE_CONTEXT_WRITES";function vn(e){let t=e[gi],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[yi]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fce8fc1d-b9ca-55bc-9c5a-f4f9728a7158")}catch{}})();var it=vi(ki),se="# pm-cli:merge-drivers:start",we="# pm-cli:merge-drivers:end",bi="merge-fence";function bn(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Rn(){let e=Bt(import.meta.url,["../../.."]);return`${bn(process.execPath)} ${bn(T.join(e,"dist","cli.js"))}`}var An=[{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}];function Si(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=vn(e.environment),a=!!(n&&r),s=t===void 0&&a&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let o=j(e.cwd,t);return{pm_root:o,workspace_start:o,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}return s?{pm_root:T.resolve(r),workspace_start:T.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:a?j(e.cwd,".agents/pm"):j(e.cwd),workspace_start:e.cwd,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}async function ke(e){try{let{stdout:t}=await it("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await rt(t.trim())}catch{return null}}async function En(e){let t=await ke(e);if(t===null)throw new h("pm merge install requires a git repository (merge drivers are git configuration).",_.USAGE);return t}function at(e,t){return T.relative(e,t).replaceAll("\\","/")}function V(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Sn(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function Ri(e,t){let n=Sn(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=Sn(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(T.basename(n.value))||T.basename(r.value)!=="cli.js"||T.basename(T.dirname(r.value))!=="dist"||!await N(n.value)||!await N(r.value))return!1;try{let i=T.dirname(T.dirname(r.value)),a=JSON.parse(await Oe(T.join(i,"package.json"),"utf8")),s=typeof a.bin=="object"&&a.bin!==null&&"pm"in a.bin?a.bin.pm:void 0;return a.name==="@unbrained/pm-cli"&&(a.bin==="dist/cli.js"||s==="dist/cli.js")}catch{return!1}}function st(e,t){let n=e.length>0?`${e}/`:"",r=[`${V(`${n}**/*.toon`)} merge=pm-item-toon`,`${V(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${V(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${V(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${V(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${V(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${V(`${n}settings.json`)} merge=pm-json`),r.push(`${V(`${n}**/*.json`)} merge=pm-json`),r.push(`${V(`${n}extensions/**`)} -merge`),r.push(`${V(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}async function xn(e,t,n){let r=T.join(e,".gitattributes"),i="";try{i=await Oe(r,"utf8")}catch(u){if(!(u instanceof Error&&"code"in u&&u.code==="ENOENT"))throw u}let a=[se,...t,we].join(`
6
+ `),s=i.indexOf(se),o=i.indexOf(we),l=(s>=0&&o>s?`${i.slice(0,s)}${i.slice(o+we.length)}`:i.replace(se,"").replace(we,"")).trimEnd(),d=`${l.length>0?`${l}
7
+
8
+ `:""}${a}
9
+ `;return d===i?{path:r,changed:!1}:(n||await wi(r,d,"utf8"),{path:r,changed:!0})}function Fe(e){let t=H(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function Cn(e,t){let n=T.resolve(e),r=null,i="",a=n;for(let p=0;p<8;p+=1){let g=T.join(a,".gitattributes");try{let S=await Oe(g,"utf8");if(S.includes(se)){r=a,i=S;break}}catch{}let y=T.dirname(a);if(y===a)break;a=y}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=T.join(r,".gitattributes"),o=i.indexOf(se),c=i.indexOf(we),l=c>o?i.slice(o+se.length,c).split(`
10
+ `).map(p=>p.trim()).filter(p=>p.length>0):[],d=st(at(r,n),t),u=new Set(l),m=new Set(d),f=d.filter(p=>!u.has(p)),k=l.filter(p=>!m.has(p));return{status:f.length>0||k.length>0?"drift":"ok",path:s,missing_patterns:f,stale_patterns:k,schema_scope:"project"}}async function In(e){let t=Rn(),n=[],r=[];for(let i of An){let a=`merge.${i.key}.driver`,s=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`,o=`${t}${s}`;try{let{stdout:c}=await it("git",["config","--local","--get",a],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==o&&!await Ri(l,s)&&r.push(a)}catch{n.push(a)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function Bo(e){let t;try{t=await En(T.resolve(e))}catch{return{status:"no_git"}}let n=at(t,T.resolve(e)),r=await L(e),i=le(void 0,r.author_default),a=await Jt(e,bi,r.locks.ttl_seconds,i,!1,cn(r).force_required_for_stale_lock,r.locks.wait_ms);try{let s=T.join(t,".gitattributes"),o;try{o=await Oe(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&u.code==="ENOENT")return{status:"not_installed",path:s};throw u}if(!o.includes(se))return{status:"not_installed",path:s};let c=await L(e),l=Fe(c),d=await xn(t,st(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await a()}}async function Uo(e,t){let n=Si({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;if(!await N(B(r)))throw new h(`Tracker is not initialized at ${r}. Run pm init first.`,_.NOT_FOUND);let i=await En(n.workspace_start);return Ai({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function Ai(e){let t=T.resolve(e.pmRoot),n=T.resolve(e.workspaceRoot),r=e.dryRun===!0,i,a;try{[i,a]=await Promise.all([rt(t),rt(n)])}catch(f){throw new h(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,_.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 s=at(a,i);if(nt(s))throw new h(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,_.USAGE);let o=await L(i),c=Fe(o),l=st(s,c),d=[],u=Rn();for(let f of An)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(!r)try{for(let f of d)await it("git",["config","--local",f.key,f.value],{cwd:a,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new h(`Cannot install repository-local merge drivers in ${a}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,_.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 xn(a,l,r);return{ok:!0,dry_run:r,workspace_root:a,pm_root:i,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:ne()}}import Ne from"node:fs/promises";import Me from"node:path";import{Option as ic}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d44229ca-8c70-5d55-a168-32bfe66711e6")}catch{}})();function Ei(e,t){let n=[],r=new Set;for(let i of t.keys){if(!Object.hasOwn(e,i))continue;let a=e[i];if(a!=null){if(typeof a=="string"){n.push(a);continue}if(!Array.isArray(a)||!a.every(s=>typeof s=="string"))return;r.has(a)||(r.add(a),n.push(...a))}}return n.length>0?n.join("; "):void 0}function Pe(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function w(e,t){return e[t]===!0?!0:void 0}function X(e,t){return e[t]===!1?!0:void 0}function xi(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Tn(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function On(e){let t=i=>Xe(e,Pe(xe,i)),n=i=>Ht(e,Pe(Ze,i)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:Ei(e,Pe(Ze,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:w(e,"replaceDeps"),replaceTests:w(e,"replaceTests"),replaceFiles:w(e,"replaceFiles"),replaceDocs:w(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:w(e,"clearDeps"),clearComments:w(e,"clearComments"),clearNotes:w(e,"clearNotes"),clearLearnings:w(e,"clearLearnings"),clearFiles:w(e,"clearFiles"),clearTests:w(e,"clearTests"),clearDocs:w(e,"clearDocs"),clearReminders:w(e,"clearReminders"),clearEvents:w(e,"clearEvents"),clearTypeOptions:w(e,"clearTypeOptions")};return Tn(r,e),r}function C(e,t){let n=Pe(qt,t),r=Xe(e,n);if(r!==void 0)return r;for(let i of n.keys){let a=e[i];if(Array.isArray(a)){let s=a.filter(o=>typeof o=="string");if(s.length>0)return s.join(",")}if(t==="ids"&&typeof a=="string")return a;if(typeof a=="number"&&Number.isFinite(a))return String(a)}}function Ci(e){let t=w(e,"filterFilesMissing"),n=w(e,"filterDocsMissing");return{filterReviewerMissing:w(e,"filterReviewerMissing"),filterRiskMissing:w(e,"filterRiskMissing"),filterConfidenceMissing:w(e,"filterConfidenceMissing"),filterSprintMissing:w(e,"filterSprintMissing"),filterReleaseMissing:w(e,"filterReleaseMissing"),hasNotes:w(e,"hasNotes"),hasLearnings:w(e,"hasLearnings"),hasFiles:w(e,"hasFiles"),hasDocs:w(e,"hasDocs"),hasTests:w(e,"hasTests"),hasComments:w(e,"hasComments"),hasDeps:w(e,"hasDeps"),hasBody:w(e,"hasBody"),hasLinkedCommand:w(e,"hasLinkedCommand"),noNotes:X(e,"notes"),noLearnings:X(e,"learnings"),noFiles:X(e,"files")??t,filterFilesMissing:t,noDocs:X(e,"docs")??n,filterDocsMissing:n,noTests:X(e,"tests"),noComments:X(e,"comments"),noDeps:X(e,"deps"),emptyBody:w(e,"emptyBody"),noLinkedCommand:X(e,"linkedCommand")}}function ot(e){let t={status:C(e,"status"),type:C(e,"type"),tag:C(e,"tag"),priority:C(e,"priority"),deadlineBefore:C(e,"deadlineBefore"),deadlineAfter:C(e,"deadlineAfter"),updatedAfter:C(e,"updatedAfter"),updatedBefore:C(e,"updatedBefore"),createdAfter:C(e,"createdAfter"),createdBefore:C(e,"createdBefore"),today:w(e,"today"),recent:w(e,"recent"),ids:C(e,"ids"),assignee:C(e,"assignee"),assigneeFilter:C(e,"assigneeFilter"),parent:C(e,"parent"),sprint:C(e,"sprint"),release:C(e,"release"),limit:C(e,"limit"),offset:C(e,"offset"),noTruncate:X(e,"truncate"),includeBody:w(e,"includeBody"),strictRead:w(e,"strictRead"),compact:w(e,"compact"),brief:w(e,"brief"),full:w(e,"full"),fields:C(e,"fields"),sort:C(e,"sort"),order:C(e,"order"),tree:w(e,"tree"),treeDepth:C(e,"treeDepth"),filterAcMissing:w(e,"filterAcMissing"),filterEstimatesMissing:xi(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:w(e,"filterResolutionMissing"),filterMetadataMissing:w(e,"filterMetadataMissing"),...Ci(e)};return Tn(t,e),t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bcda2578-3b01-5e64-9d53-cd32c0f927b8")}catch{}})();function b(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function O(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Ii(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fc(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new h(`${t} must be a finite integer.`,_.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new h(`${t} must be a finite integer.`,_.USAGE);return n}}function pc(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:b(e,"limit")??b(t,"limit")}function _c(e){let t=b(e,"outputFormat");return{json:!0,quiet:!0,author:b(e,"author"),path:b(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:b(e,"outputInclude"),outputLimit:O(e,"outputLimit"),outputBudget:O(e,"outputBudget"),outputSession:b(e,"outputSession"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Ti=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Oi=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),Fi=new Set(["files","files-discover","docs","test","test-all"]),Pi=new Set(["claim","release","start-task","pause-task","close-task"]),Di={list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt"],append:["body"]},Ni=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession"];function Pn(e,t){let n={},r=t!==void 0&&Fi.has(t),i=t==="files"||t==="files-discover"||t==="docs";for(let[a,s]of Object.entries(e)){if(Array.isArray(s)&&Ti.has(a)){n[a]=s.join(",");continue}if(a==="note"&&i){n[a]=s;continue}if(typeof s=="string"&&Oi.has(a)){n[a]=[s];continue}if(typeof s=="string"&&r&&(a==="add"||a==="remove")){n[a]=[s];continue}n[a]=s}return n}function hc(e,t){let n=Gt(e.options),r={},i=c=>{n[c]!==void 0||e[c]===void 0||(r[c]=e[c])};for(let c of Di[t??""]??[])i(c);for(let c of Ni)i(c);let a=Pn({...r,...n},t),s=b(e,"author"),o=t!==void 0&&Pi.has(t)?b(e,"assignee")??b(a,"assignee"):void 0;return s&&a.author===void 0?{...a,author:s}:o&&a.author===void 0?{...a,author:o}:a}function gc(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function yc(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function wc(e){let t=[],n=!0;for(let r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function kc(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function dt(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function vc(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[a,s]of Object.entries(e))n.has(a)||(r[a]=s);let i={...r,...t};return delete i.args,i}function bc(e,t){return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:{...t}}}function lt(e){return{type:O(e,"filterType"),tag:O(e,"filterTag"),priority:O(e,"filterPriority"),deadlineBefore:O(e,"filterDeadlineBefore"),deadlineAfter:O(e,"filterDeadlineAfter"),updatedAfter:O(e,"filterUpdatedAfter"),updatedBefore:O(e,"filterUpdatedBefore"),createdAfter:O(e,"filterCreatedAfter"),createdBefore:O(e,"filterCreatedBefore"),ids:Ii(e,"ids"),assignee:O(e,"filterAssignee"),assigneeFilter:O(e,"filterAssigneeFilter")??O(e,"filterAssignee_filter"),parent:O(e,"filterParent"),sprint:O(e,"filterSprint"),release:O(e,"filterRelease"),limit:O(e,"limit"),offset:O(e,"offset")}}function ct(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return dt(e)}function De(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function Sc(e){let t=ct(e.kind),n=ct(e.exemptIsolate),r=ct(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:De(e.maxDepth),limit:De(e.limit),after:b(e,"after"),direction:b(e,"direction"),maxPaths:De(e.maxPaths),sample:De(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function Rc(e){return{status:b(e,"filterStatus"),list:ve(e.list)?ot(e.list):lt(e),reason:b(e,"reason"),resolution:b(e,"resolution"),expectedResult:b(e,"expectedResult")??b(e,"expected_result")??b(e,"expected"),actualResult:b(e,"actualResult")??b(e,"actual_result")??b(e,"actual"),validateClose:b(e,"validateClose")??b(e,"validate_close"),author:b(e,"author"),message:b(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:b(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var Mi=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function Fn(e){let t={};for(let[n,r]of Object.entries(e))Mi.has(n)||(t[n]=r);return Dn(t)}function Dn(e){let t=Pn(e,"update-many");for(let n of xe)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return On(t)}function Ac(e){if(ve(e.list)||ve(e.update)){let t=ve(e.update)?e.update:Fn(e);return{status:O(e,"filterStatus"),list:ve(e.list)?ot(e.list):lt(e),update:Dn(t),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:b(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:O(e,"filterStatus"),list:lt(e),update:Fn(e),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:b(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4fd16197-979e-5269-bed7-f2fb0e2038c2")}catch{}})();function Z(e,t){throw new h(e,_.USAGE,t)}var Li="2026-07-15T06:22:12.276Z",$i=Date.parse(Li),ji=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Nn=e=>typeof e=="string"?e:"",Mn=e=>{let t=e??{},n=Nn(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Nn(t.ts))>=$i);return ji[r][i]};function Ln(e,t,n=20,r=new Set,i=!1){let a=[],s=[],o={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 k;try{k=JSON.parse(f)}catch{continue}l+=1;let p=Mn(k);if(p!=="attributed"){if(d+=1,p==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}o[p]+=1,i&&p==="actionable_unknown"&&s.push({item_id:e,line:m+1}),a.length<c&&a.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:o.legacy_unknown,actionable_unknown_event_count:o.actionable_unknown,acknowledged_actionable_event_count:u,samples:a,samples_truncated:o.legacy_unknown+o.actionable_unknown>a.length,actionable_events:s}}var Dc=(e,t,n=20,r=new Set)=>Ln(e,t,n,r);function Bi(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let a=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof a!="object"||a===null||!Array.isArray(a.events)))for(let s of a.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var ut=async(e,t=20,n=!1)=>{let r=Me.join(e,"history"),i;try{i=(await Ne.readdir(r)).filter(y=>y.endsWith(".jsonl")).sort((y,S)=>y.localeCompare(S))}catch{i=[]}let a=new Set,s=[],o=[],c=0,l=0,d=0,u=0,m=0,f=0,k="_workspace.jsonl",p=new Set;if(i.includes(k))try{p=Bi(await Ne.readFile(Me.join(r,k),"utf8"))}catch{p=new Set}for(let y of i){let S;try{S=await Ne.readFile(Me.join(r,y),"utf8")}catch{continue}let A=y.slice(0,-6),E=Ln(A,S,t-s.length,p,n);c+=1,l+=E.checked_events,d+=E.unknown_event_count,u+=E.legacy_unknown_event_count,m+=E.actionable_unknown_event_count,f+=E.acknowledged_actionable_event_count,E.unknown_event_count>0&&a.add(A),s.push(...E.samples),n&&o.push(...E.actionable_events)}let g=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:[...a].sort((y,S)=>y.localeCompare(S)),samples:s,samples_truncated:g>s.length,...n?{actionable_events:o}:{}}};function Ui(e,t){let n=e.length>0;return n&&t&&Z("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&Z("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:zi(e),all_actionable:t}}function zi(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),a=r===J||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!a||!Number.isSafeInteger(i)||i<1)&&Z(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function Nc(e,t){let n=Ui(dt(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Gi(e,{events:n.events,all_actionable:n.all_actionable,attributed_author:b(t,"attributedAuthor")??b(t,"attributed_author")??"",reviewer:b(t,"reviewer")??"",reason:b(t,"reason")??""})}async function Gi(e,t){let n=t.reviewer.trim(),r=t.attributed_author.trim(),i=t.reason.trim(),a=t.events??[],s=+(t.all_actionable===!0)+ +(a.length>0);s===0&&Z("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),s>1&&Z("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"});let o=t.all_actionable===!0?(await ut(e,0,!0)).actionable_events:a;[o.length>0,n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Z("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"});let l=[...new Map(o.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){[m.item_id===J||/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1)&&Z(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"});let k;try{let g=(await Ne.readFile(Me.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];k=JSON.parse(g??"")}catch{Z(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}Mn(k)!=="actionable_unknown"&&Z(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"})}let d=await L(e),u=await sn({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:l,attributed_author:r}},message:i,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms});return{acknowledged:l.length,history_path:u.historyPath}}import{execFile as Wi}from"node:child_process";import{randomUUID as qi}from"node:crypto";import{readdir as Hi,readFile as Vi}from"node:fs/promises";import be from"node:path";import{promisify as Ki}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 Yi=Ki(Wi);async function mt(e){try{let{stdout:t}=await Yi("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 $n(e){return`${e}.json`}function qc(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:Je(Ye(t.retained)),discarded_hash:Je(Ye(t.discarded))}))}}async function Hc(e){let t=await mt(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,i=be.basename(r,be.extname(r)),a={version:1,id:qi(),item_path:r.replaceAll("\\","/"),item_id:i,preferred:e.preferred,fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:ne()};return await $t(t),await pe(be.join(t,$n(a.id)),`${JSON.stringify(a,null,2)}
11
+ `),a}async function ft(e,t={}){let n=await mt(e);if(n===null||!await N(n))return[];let r=[],i;try{i=await Hi(n)}catch{return[]}for(let a of i.sort((s,o)=>s.localeCompare(o)))if(a.endsWith(".json"))try{let s=JSON.parse(await Vi(be.join(n,a),"utf8"));s.version===1&&(t.includeReconciled||s.state==="pending")&&r.push(s)}catch{}return r.sort((a,s)=>a.created_at.localeCompare(s.created_at))}async function Vc(e,t){let n=await mt(e);n!==null&&await pe(be.join(n,$n(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:ne()},null,2)}
12
+ `)}async function Kc(e){let t=await ft(e.cwd??process.cwd(),e);return{ok:!0,count:t.length,receipts:t,generated_at:ne()}}import de from"node:fs/promises";import ue from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function Ji(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let a;try{a=await de.readdir(ue.join(e,i))}catch{return}for(let s of a)for(let o of Ut)if(s.toLowerCase().endsWith(o)){r.push({relativePath:`${i}/${s}`,id:s.slice(0,-o.length)});break}})),r.sort((i,a)=>i.relativePath.localeCompare(a.relativePath))}function Xi(e,t){let{id:n,relativePath:r,liveItemIds:i,out:a}=e,s=Qe(t);if(s){a.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let o=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");o=d}catch{a.unparseable.push({id:n,path:r,line:l.number,detail:"history line is not a valid JSON object"});return}o!==null&&(o.op==="delete"&&i.has(n)&&a.resurrected.push({id:n,deleted_at:typeof o.ts=="string"?o.ts:"",deleted_by:typeof o.author=="string"?o.author:""}),o.op==="history_repair"&&Array.isArray(o.patch)&&o.patch.length>0&&(a.repairReconciliations+=1))}function pt(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 Zi(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await de.readdir(ue.join(e,"history"))}catch{return n}for(let i of r.sort((a,s)=>a.localeCompare(s))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let a;try{a=await de.readFile(ue.join(e,"history",i),"utf8")}catch(s){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:pt("history stream",s)});continue}Xi({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},a)}return n}function jn(e){let t=Qe(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 Qi(e){let t=[],n=0,r=null;try{r=await jt(B(e))}catch(a){n+=1,t.push({path:"settings.json",detail:pt("configuration file",a)})}if(r!==null){n+=1;let a=jn(r);a!==null&&t.push({path:"settings.json",detail:a})}let i;try{i=await de.readdir(ue.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let a of i.sort((s,o)=>s.localeCompare(o))){if(!a.endsWith(".json"))continue;n+=1;let s;try{s=await de.readFile(ue.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:pt("configuration file",c)});continue}let o=jn(s);o!==null&&t.push({path:`schema/${a}`,detail:o})}return{scanned:n,unparseable:t}}async function Bn(e,t,n,r={}){let i=await Ji(e,n),a=new Set(i.map(u=>u.id)),s=new Map;for(let u of i){let m=s.get(u.id);m===void 0?s.set(u.id,[u.relativePath]):m.push(u.relativePath)}let o=[...s.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,k)=>f.localeCompare(k))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=ue.join(e,u.relativePath);return tn(await de.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await Zi(e,a),d=await Qi(e);return{item_files_on_disk:i.length,item_ids_on_disk:a.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:o,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 It from"node:fs/promises";import{realpathSync as hs}from"node:fs";import{execFile as gs}from"node:child_process";import $ from"node:path";import{promisify as ys}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 ea=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 ta(e){if(typeof e!="string")return;let t=e.trim();for(let n of ea)if(t===n.code||t.startsWith(`${n.code}:`))return n}function na(e){let t={};for(let n of e){let r=ta(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Un(e){return Object.values(na(e))}import me from"node:fs/promises";import{createHash as ra}from"node:crypto";import Gn 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 Wn=3,ia="history-drift-cache.json";function qn(e){return Gn.join(e,"runtime",ia)}async function aa(e){try{let t=await me.readFile(qn(e),"utf8"),n=JSON.parse(t);return n.version!==Wn||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}function Hn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function sa(e,t,n,r,i){let a=an(e),s;try{s=await me.stat(a)}catch(l){return Hn(l,"ENOENT")||i.unreadableStreams.push(J),!1}let o=i.missingStreams.length,c=await Kn({itemId:J,historyPath:a,stat:s,cached:t[J],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.chainOk||i.chainMismatches.push(J),n[J]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk},c.cacheDirty):(i.missingStreams.splice(o),c.cacheDirty)}function Vn(e){return ra("sha256").update(e).digest("hex")}async function oa(e){let t=await me.readFile(e,"utf8");return Vn(t)}async function ca(e){let t=await me.readFile(e,"utf8"),n=Vn(t);if(t.trim().length===0)return null;let r=[],i=null;for(let a of t.split(/\r?\n/)){let s=a.trim();if(s.length===0)continue;let o=JSON.parse(s);if(typeof o.after_hash!="string"||o.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(o),i=o.after_hash}return i?{latestAfterHash:i,chainOk:rn(r).ok,contentHash:n}:null}function la(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function zn(e,t,n){try{let r=await ca(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Kn(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(la(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await zn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await oa(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else r=t;return!e.verifyCacheHitByContent||r===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:r},cacheDirty:!1}:{verification:await zn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function Yn(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[]},a=(await aa(e))?.entries??{},s={},o=!1,c=n.cacheHitVerification!=="metadata";for(let u of t){let m=zt(e,u.id),f;try{f=await me.stat(m)}catch(A){Hn(A,"ENOENT")?r.missingStreams.push(u.id):r.unreadableStreams.push(u.id);continue}let k=a[u.id],p=await Kn({itemId:u.id,historyPath:m,stat:f,cached:k,verifyCacheHitByContent:c,accumulator:r});if(o||=p.cacheDirty,!p.verification)continue;p.verification.chainOk||r.chainMismatches.push(u.id),s[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:g,...y}=u;nn({metadata:y,body:g})!==p.verification.latestAfterHash&&r.hashMismatches.push(u.id)}let l=await sa(e,a,s,c,r);if(o||=l,o||Object.keys(a).length!==Object.keys(s).length){let u=qn(e);try{await me.mkdir(Gn.dirname(u),{recursive:!0}),await pe(u,JSON.stringify({version:Wn,entries:s}))}catch{}}let d=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches])].sort((u,m)=>u.localeCompare(m));return{...r,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 da=["metadata","resolution"],_t=["metadata","resolution","estimates","lifecycle"],ua="completed";function ht(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Jn(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 r=Jn(n.close_reason)??ua;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${ht(r)}`,gate:"resolution"})}return t}function Zn(e){let t=[];for(let n of e){let r=Jn(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${ht(r)}`,gate:"metadata"})}return t}function Qn(e,t){return e.map(n=>{let r=on(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function er(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 tr(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=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 ${r} ${n.item_id} --remove ${ht(n.path)}`})}return t}function nr(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new h(`--fix-scope values must not be empty. Supported values: ${_t.join(", ")}.`,_.USAGE);return new Set(da)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(_t.includes(i)){n.add(i);continue}throw new h(`Unknown --fix-scope value "${r}". Supported values: ${_t.join(", ")}.`,_.USAGE)}return n}function rr(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function Se(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 ma=/^([A-Z][A-Z0-9]*-\d+)\b/;function fa(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=ma.exec(t);return n?n[1]:null}function ir(e){return typeof e=="string"&&e.trim().length>0}function ar(e){let t=new Map;for(let r of e){if(typeof r.title!="string"||ir(r.duplicate_of))continue;let i=fa(r.title);if(i===null)continue;let a=t.get(i);a||(a=[],t.set(i,a)),a.some(s=>s.id===r.id)||a.push({id:r.id,title:r.title,parent:ir(r.parent)?r.parent.trim():null})}let n=[];for(let[r,i]of t){if(i.length<2)continue;let a=new Set(i.map(c=>c.id.toLowerCase())),s=i.filter(c=>c.parent===null||!a.has(c.parent.toLowerCase()));if(s.length<2)continue;let o=[...s].sort((c,l)=>c.id.localeCompare(l.id));n.push({code:r,count:o.length,ids:o.map(c=>c.id),titles:o.map(c=>c.title)})}return n.sort((r,i)=>r.code.localeCompare(i.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 sr(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,a)=>i.localeCompare(a))){let i=t.get(r),a={};for(let s of[...i.keys()].sort((o,c)=>o.localeCompare(c)))a[s]=i.get(s);n[r]=a}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 or=3;function cr(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function lr(e,t,n=or){let r=Number.isFinite(n)&&n>=1?Math.floor(n):or,i=new Map;for(let a of t){let s=cr(a);if(s.length===0)continue;let o=i.get(s);o?o.push(a):i.set(s,[a])}return e.map(a=>{let s=(i.get(cr(a))??[]).filter(o=>o!==a).sort((o,c)=>o.localeCompare(c));return s.length===0?{path:a,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:a,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function dr(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 pa=/^[a-z][a-z0-9+.-]+:\/\//i;function Re(e){return pa.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 _a(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function ur(e){return`${e.item_id} ${e.link_kind}`}function mr(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=_a(i.classification,r.classification),i.owners.set(ur(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[ur(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(a=>{let s=t(a.item_id);return{id:a.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:a.link_kind}}).sort((a,s)=>{let o=a.id.localeCompare(s.id);return o!==0?o:a.field.localeCompare(s.field)})}))}function ha(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function fr(e){let t=[];for(let n of e)for(let r of n.items)t.push(`${n.path}:${n.classification} owner=${r.id} status=${r.status} field=${r.field} title="${ha(r.title)}"`);return t}import{execFile as ga}from"node:child_process";import{realpath as ya}from"node:fs/promises";import pr from"node:path";import{promisify as wa}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 ka=wa(ga),va=32*1024*1024,ba=1e4,Sa=["search/eval-queries.json"];function gt(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Ra(e){return`'${e.replaceAll("'","'\\''")}'`}async function Aa(e,t=ya){return t(e).catch(()=>pr.resolve(e))}async function _r(e){let t=await ke(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 Aa(e),r=gt(pr.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=tt.map(a=>`${r}/${gt(a)}`);try{let{stdout:a}=await ka("git",["ls-files","-z","--",...i.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:va,windowsHide:!0,timeout:ba}),s=new Set(Sa.map(l=>`${r}/${l}`)),o=[...new Set(a.split("\0").filter(l=>l.length>0&&!s.has(gt(l))))].sort((l,d)=>l.localeCompare(d)),c=i.filter(l=>o.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:o,tracked_path_count:o.length,remediation_command:o.length===0?null:`git rm --cached -r -- ${c.map(l=>Ra(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import Ea from"node:fs/promises";import U from"node:path";import xa 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 Ca=["path","scope","note"],Ia=["pattern","glob","path","scope","note"],Ta=["path"],Oa=["from","to"],Fa=new Set(["note","scope"]);function gr(e){let t=e??"project";if(!He.includes(t))throw new h(`Invalid scope "${e}". Valid scopes: ${He.join(", ")} (default: project).`,_.USAGE);return t}function yr(e){return e.startsWith("```")||e.includes(`
13
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:fn(e)}function Pa(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||yr(n)||!n.includes(",")?[t]:_n(n)})}function Da(e,t){return e?Pa(e).map(n=>{let r=n.trim(),i=yr(r)?he(n,"--add"):{path:r};if(ge(i,"--add",Ca),!i.path)throw new h(`--add requires path=<value> or a bare ${t} path`,_.USAGE);return{path:i.path,scope:gr(i.scope),note:i.note?.trim()||void 0}}):[]}function Na(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new h("--add-glob requires a glob pattern value",_.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=he(n,"--add-glob");ge(r,"--add-glob",Ia);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new h("--add-glob key/value form requires pattern=<glob>",_.USAGE);return{pattern:i,scope:gr(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Ma(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new h("--remove requires a path value",_.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=he(n,"--remove"),i=Object.keys(r).filter(a=>Fa.has(a.toLowerCase()));if(i.length>0)throw new h(`--remove identifies a linked artifact by path only and does not accept ${i.map(a=>`"${a}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,_.USAGE);if(ge(r,"--remove",Ta),!r.path)throw new h("--remove key/value form requires path=<value>",_.USAGE);return r.path}return n}):[]}function La(e){return e?e.map(t=>{let n=he(t,"--migrate");ge(n,"--migrate",Oa);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new h("--migrate requires from=<value> and to=<value>",_.USAGE);return{from:r,to:i}}):[]}function yt(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function Q(e){return e.split(U.sep).join("/")}function wt(e,t,n=process.cwd()){let r=e.trim();if(Re(r))return r;if(U.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return Q(r.replaceAll("\\",U.sep));let i=U.relative(t,n);return i.startsWith(`..${U.sep}`)||i===".."||U.isAbsolute(i)?Q(U.normalize(r)):Q(U.relative(t,U.resolve(n,r)))}async function $a(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){let a=U.isAbsolute(i.pattern),s=await xa(i.pattern,{cwd:n,absolute:a,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),o=[...new Set(s.map(c=>wt(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of o)r.push({path:c,scope:i.scope,note:i.note})}return r}function ja(e,t,n){if(t===void 0)return e;if(!n)throw new h("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",_.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function Ba(e){return`${e.path}::${e.scope}`}function kt(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function vt(e){return[...new Map(e.map(t=>[Ba(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function Ua(e,t=process.cwd()){let n=[...new Set(e)].sort((o,c)=>o.localeCompare(c)),r=[],i=[],a=[],s=[];for(let o of n){if(Re(o)){s.push(o.trim());continue}let c=U.isAbsolute(o)?o:U.resolve(t,o);try{(await Ea.stat(c)).isFile()?r.push(o):a.push(o)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&l.code==="ENOENT"){i.push(o);continue}a.push(o)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:a,remote_references:s}}function za(e,t,n,r){let i=0;for(let s=0;s<e.length;s+=1){let o=yt(e[s].path,r);o!==e[s].path&&(e[s]={...e[s],path:o},i+=1)}return{adds:t.map(s=>{let o=yt(s.path,r);return o!==s.path&&(i+=1),{...s,path:o}}),removes:n.map(s=>yt(s,r)),count:i}}function Ga(e,t,n,r){for(let a of t)e.some(s=>s.path===a.path&&s.scope===a.scope)||e.push(a);if(n.length>0)for(let a=e.length-1;a>=0;a-=1)n.includes(e[a].path)&&e.splice(a,1);let i=vt(e);return r?i:kt(i)}async function hr(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 Ua(t,e.workspaceRoot):void 0}}async function Le(e,t,n,r){let{metadataKey:i}=r,a=pn(),s=j(process.cwd(),n.path),o=_e(s),c=process.cwd();if(!await N(B(s)))throw new h(`Tracker is not initialized at ${s}. Run pm init first.`,_.NOT_FOUND);let l=await L(s),d=H(l,Y()),u=await a.resolveList(t.add,"--add"),m=await a.resolveList(t.addGlob,"--add-glob"),f=await a.resolveList(t.remove,"--remove"),k=await a.resolveList(t.migrate,"--migrate"),p=Da(u,r.bareNoun).map(D=>({...D,path:wt(D.path,o,c)})),g=Na(m),y=await $a(g,o,c),S=ja([...p,...y],t.note,p.length>0||g.length>0),A=Ma(f).map(D=>wt(D,o,c)),E=La(k);if(!(S.length>0||A.length>0||E.length>0)){let D=await Ce(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!D)throw new h(`Item ${e} not found`,_.NOT_FOUND);let I=(await Ie(D,{schema:l.schema})).document.metadata[i]??[];return hr({id:D.id,artifacts:I,changed:!1,options:t,workspaceRoot:o})}let K=le(t.author,l.author_default),W=await Te({pmRoot:s,settings:l,id:e,op:r.op,author:K,message:t.message,force:t.force,skipNoop:!0,mutate(D){let v=D.metadata,I=v[i]??[],ce=[...I],ae=za(ce,S,A,E),qe=Ga(ce,ae.adds,ae.removes,r.supportsAppendStable&&t.appendStable===!0);qe.length>0?v[i]=qe:delete v[i];let Dt=!Wt(I,qe);return{changedFields:Dt?[i]:[],warnings:Dt&&ae.count>0?[`path_migrations_applied:${ae.count}`]:[]}}}),R=W.item[i]??[],P=W.warnings.find(D=>D.startsWith("path_migrations_applied:")),q=P?Number(P.slice(24)):0;return hr({id:W.item.id,artifacts:R,changed:W.changedFields.includes(i),migrationsApplied:q,options:t,workspaceRoot:o})}function $e(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function wr(e,t,n){let r=await Le(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return $e(r,"docs")}import kr from"node:fs/promises";import z from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5e45d0f1-a1a7-50ea-a9a3-ec6283d3471d")}catch{}})();var Wa=32768;function bt(e){return Q(z.normalize(e))}async function je(e){try{return await kr.realpath(e)}catch{return z.resolve(e)}}function fe(e,t){let n=z.isAbsolute(e.path)?z.resolve(e.path):z.resolve(t,e.path);return`${bt(n)}::${e.scope}`}function Be(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>Be(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))Be(i,t?`${t}.${r}`:r,n)}function qa(e){let t=[];return Be(e.metadata,"metadata",t),Be(e.body,"body",t),t}function Ha(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 Va(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{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 i of e){let a=new Set,s=i.value.slice(0,Wa);for(let[o,c]of[[n,i.value],[r,s]]){o.lastIndex=0;for(let l of c.matchAll(o)){let d=Ha(l[0]);!d||a.has(d)||(a.add(d),t.push({field:i.field,value:d}))}}}return t}async function Ka(e,t,n=t){let r=z.isAbsolute(e)?z.resolve(e):z.resolve(n,e),i;try{i=await kr.stat(r)}catch{return}if(!i.isFile())return;let[a,s]=await Promise.all([je(t),je(r)]);if(Ve(a,s)){let o=z.relative(a,s);return!o||o.startsWith("..")||z.isAbsolute(o)?void 0:{path:bt(o),scope:"project"}}return{path:bt(r),scope:"global"}}async function Ya(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>fe(c,t))),i=new Map,a=Va(qa(e)),s=new Map;await Promise.all([...new Set(a.map(c=>c.value))].map(async c=>{s.set(c,await Ka(c,t,n))}));let o=a.map(c=>({reference:c,resolved:s.get(c.value)}));for(let{reference:c,resolved:l}of o){if(!l)continue;let d=fe(l,t),u=i.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,i.set(d,u)}return[...i.entries()].map(([c,l])=>({path:l.path,scope:l.scope,status:r.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 vr(e,t,n){let r=await Le(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return $e(r,"files")}async function Ja(e,t){let n=await je(t),r=await Promise.all(e.map(async a=>{let s=a.trim();if(!s)throw new h("Files lookup paths must not be empty.",_.USAGE);if(!z.isAbsolute(s))return Q(s);let o=await je(s);return Ve(n,o)?Q(z.relative(n,o)):Q(o)})),i=[...new Set(r)].sort((a,s)=>a.localeCompare(s));if(i.length===0)throw new h("Files lookup requires at least one path.",_.USAGE);return i}function Xa(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new h(`Files lookup ${r} must be a non-negative integer.`,_.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 br(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}async function Za(e){if([e.strictRead,e.noTruncate,Yt()].includes(!0))return null;let t=await dn(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?ln({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function Qa(e){let t=[],r=(await un(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema)).map(s=>({item:s,files:(s.files??[]).filter(o=>e.paths.includes(Q(o.path))&&(e.scope===void 0||o.scope===e.scope)).sort((o,c)=>{let l=o.path.localeCompare(c.path);return l===0?o.scope.localeCompare(c.scope):l})})).filter(s=>s.files.length>0).sort((s,o)=>{let c=s.item.priority-o.item.priority;if(c!==0)return c;let l=o.item.updated_at.localeCompare(s.item.updated_at);return l===0?s.item.id.localeCompare(o.item.id):l}),i=t.filter(s=>/^item_list_(?:item|directory)_read_failed:/u.test(s));if(e.strictRead&&i.length>0)throw new h(`Files lookup could not read every item: ${i.join("; ")}`,_.GENERIC_FAILURE);let a=r.slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<r.length,truncated:e.offset+a.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(s=>({item:br(s.item),files:s.files}))}}async function dd(e,t){let n=j(process.cwd(),t.path),r=_e(n);if(!await N(B(n)))throw new h(`Tracker is not initialized at ${n}. Run pm init first.`,_.NOT_FOUND);let i=await Ja(e.paths,r),a=await L(n),s=H(a,Y()),{offset:o,limit:c}=Xa(e),l=await Za({pmRoot:n,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0});return l?{paths:i,total:l.total,count:l.matches.length,offset:o,limit:c,has_more:o+l.matches.length<l.total,truncated:o+l.matches.length<l.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:l.matches.map(d=>({item:br(d.item),files:d.files}))}:Qa({pmRoot:n,settings:a,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0})}async function ud(e,t,n){let r=j(process.cwd(),n.path),i=_e(r);if(!await N(B(r)))throw new h(`Tracker is not initialized at ${r}. Run pm init first.`,_.NOT_FOUND);let a=await L(r),s=H(a,Y()),o=await Ce(r,e,a.id_prefix,a.item_format,s.type_to_folder);if(!o)throw new h(`Item ${e} not found`,_.NOT_FOUND);let c=await Ie(o,{schema:a.schema}),l=await Ya(c.document,i,process.cwd()),d=l.filter(R=>R.status==="addable"),u=l.filter(R=>R.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let R=c.document.metadata.files??[];return{id:o.id,files:R,changed:!1,apply:m,count:R.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let k=le(t.author,a.author_default),p=d.map(R=>({path:R.path,scope:R.scope,note:f})),g=[],y=new Set,S=await Te({pmRoot:r,settings:a,id:e,op:"files_discover",author:k,message:t.message??"Discover referenced file links",force:t.force,mutate(R){let P=[...R.metadata.files??[]],q=new Set(P.map(I=>fe(I,i)));g=[],y.clear();for(let[I,ce]of p.entries()){let ae=fe(ce,i);q.has(ae)||(P.push(ce),q.add(ae),g.push(ce),y.add(I))}let D=vt(P),v=t.appendStable?D:kt(D);return v.length>0?R.metadata.files=v:delete R.metadata.files,{changedFields:g.length>0?["files"]:[],warnings:g.length!==p.length?[`files_discover_skipped_existing:${p.length-g.length}`]:[]}}}),A=S.item.files??[],E=new Set(g.map(R=>fe(R,i))),x=A.filter(R=>E.has(fe(R,i))),K=d.filter((R,P)=>!y.has(P)),W=[...u,...K];return{id:S.item.id,files:A,changed:x.length>0,apply:!0,count:A.length,candidate_count:l.length,addable_count:d.length,added_count:x.length,skipped_existing_count:W.length,candidates:l,added:x,skipped_existing:W}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c4d45cf-6b97-5151-a325-db09d31962a7")}catch{}})();var es=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),St=new Set(["--pm-path","--path","--author"]),ts={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"])},ns=new Set(["-p","--package"]),rs=new Set(["-c","--call"]),is=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),as=new Set(["-C","--prefix","--userconfig","--cache"]),fd=new Set(["--cwd"]),pd=new Set(["--cwd"]),ss=new Set(["exec","x"]),_d=new Set(["run","run-script"]),hd=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function os(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function cs(e){let t=ls(e.split(" ").filter(a=>a.length>0));if(t.length===0)return null;let[n,...r]=t;if(Sr(n)||Rr(n))return r;if(n==="node"&&r[0]&&Rr(r[0]))return r.slice(1);let i=n==="npx"||n==="bunx"?Rt(r):n==="pnpm"?ms(r):n==="npm"?fs(r):null;return i&&(Sr(i.command)||us(i.command))?i.args:null}var Ar=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let a=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let o of os(a)){let c=cs(o),l=c?ps(c):null,d=l&&es.has(l.subcommand)?_s(l.remaining,ts[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&s.add(d)}return[...s].sort((o,c)=>o.localeCompare(c))};function ls(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 gd(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(St.has(n)){t+=2;continue}t+=1;continue}return n}}function Sr(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function ds(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function us(e){let t=ds(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Rr(e){return e==="dist/cli.js"||e==="./dist/cli.js"||e.endsWith("/dist/cli.js")}function Rt(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let a=i[1];return a?{command:a,args:e.slice(t+1)}:null}if(rs.has(r)){t+=1;break}t+=ns.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Er(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function ms(e){let t=Er(e,is);return t?.subcommand!=="dlx"?null:Rt(t.args)}function fs(e){let t=Er(e,as);return!t||!ss.has(t.subcommand)?null:Rt(t.args)}function ps(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(St.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function _s(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(St.has(r)||t.has(r))&&(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 ws=["src","tests","docs"],ks=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],vs=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),bs=["resolution","expected_result","actual_result"],Ss=["default","tracked-all","tracked-all-strict"],xr=["core","strict","custom"],ze=["off","warn","error"];var Et=["author","acceptance_criteria","estimated_minutes","close_reason"],Fr=[...Et,"reviewer","risk","confidence","sprint","release"],Tt=Array.from(new Set(Fr)),Rs={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"},As={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"},Es={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"},xs={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"},Cs={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"},Is=32*1024*1024,Ts=1e4,Pr=40,te=5,Os=4096,Fs=255,Ps=ys(gs);function Dr(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?Dr(r):r);return t}function Ds(e){return{...e,checks:e.checks.map(t=>({...t,details:Dr(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 oe(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Cr(e){return oe(e).replace(/\/+$/,"")}function G(e){let t=M(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function We(e,t){return en(e,t)??e}function Ae(e,t){return t.terminal_statuses.has(We(e,t))}function re(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ue(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Ns(e){let t=re(Mt),n={blocked_reason:re(Ee.blocked_reason),resolution:re(Ee.resolution),actual_result:re(Ee.actual_result)},r=re(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:re(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:re(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:re(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Ue(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Ue(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Ue(i.resolution,n.resolution)?"default":"settings",actual_result:Ue(i.actual_result,n.actual_result)?"default":"settings"}}}function Nr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(xr.includes(t))return t;throw new h(`Unknown --metadata-profile value "${e}". Supported values: ${xr.join(", ")}.`,_.USAGE)}function Mr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ze.includes(t))return t;throw new h(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ze.join(", ")}.`,_.USAGE)}function Lr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ze.includes(t))return t;throw new h(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ze.join(", ")}.`,_.USAGE)}function Ms(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>Rs[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function Ls(e,t,n){let r=Ms(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Et],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Fr],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Et],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var $s=new Set(["acceptance_criteria","estimated_minutes"]);function $r(e,t,n,r){return!r&&$s.has(t)&&Ae(e.status,n)?!1:t==="author"?!M(e.author):t==="acceptance_criteria"?!M(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?We(e.status,n)===n.close_status&&!M(e.close_reason):t==="reviewer"?!M(e.reviewer):t==="risk"?!M(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!M(e.confidence):t==="sprint"?!M(e.sprint):!M(e.release)}function jr(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 h(`Unknown --scan-mode value "${e}". Supported values: ${Ss.join(", ")}.`,_.USAGE)}function Br(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return $.resolve(t);let n=$.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return $.dirname($.dirname(n));let i=$.resolve(process.cwd()),a=Ir(n),s=Ir(i),o=$.relative(a,s);return o.length===0||!o.startsWith("..")&&!$.isAbsolute(o)?n:i}function Ir(e){try{return hs.native(e)}catch{return $.resolve(e)}}function Ur(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Ot(e,t,n){let r=t.length>0?$.join(e,t):e,i;try{i=await It.readdir(r,{withFileTypes:!0})}catch(a){if(Ur(a,["ENOENT"]))return;throw a}for(let a of i){if(a.name.startsWith("."))continue;let s=t.length>0?$.join(t,a.name):a.name;if(a.isDirectory()){if(vs.has(a.name))continue;await Ot(e,s,n);continue}a.isFile()&&n.push(oe(s))}}async function xt(e){let t=[];for(let n of ws)await Ot(e,n,t);for(let n of ks){let r=$.join(e,n);try{(await It.stat(r)).isFile()&&t.push(oe(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function zr(e){try{let{stdout:t}=await Ps("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:Is,windowsHide:!0,timeout:Ts}),n=t.split("\0").map(r=>oe(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function js(e,t){let n=new Set,r=Cr(Nt);r.length>0&&n.add(r);let i=Cr($.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((a,s)=>a.localeCompare(s))}function Tr(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function Bs(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await zr(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await xt(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await xt(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function F(e,t=te){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function ie(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=F(e,Pr);return{values:n.values,truncated:n.truncated,total:e.length}}var Us={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},zs={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function Gs(e){let t=e.missing_fields.map(n=>`${Us[n]} "${zs[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Gr(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(s=>typeof s=="string"):Un(t);if(i.length===0)return;let a=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...a?{fix_hints_truncated:!0}:{}}}function Wr(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 Ws="validate_metadata_duplicate_issue_codes";function qr(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:te,r=e.slice(0,n);return{rows:r.map(a=>({code:a.code,count:a.count,ids:a.ids,titles:a.titles,remediation_hint:`Items ${a.ids.join(", ")} share issue code "${a.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${Ws}:${e.length}`]}}function qs(){return Object.fromEntries(Tt.map(e=>[e,[]]))}function Hs(e,t,n){let r=qs();for(let i of e)for(let a of Tt)$r(i,a,t,n)&&r[a].push(i.id);return r}function Vs(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let a=t[i];a.length>0&&r.push(`${As[i]}:${a.length}`)}return r.push(...n),r}function Hr(e,t){let n={};for(let r of e.required_fields){let i=t[r],a=i?i.length:0,s=Es[r];a>0&&s&&(n[s]=a)}return n}function Vr(e,t,n){let r=[];for(let i of e.required_fields){let a=t[i];if(a)for(let s of a){let o=n.get(s)?.type,c=typeof o=="string"&&o.length>0?o:"Unknown";r.push({item_type:c,field:i})}}return r}function Ks(e,t,n,r){for(let i of t.required_fields){let a=n[i];if(!a||a.length===0)continue;let s=xs[i],o=Cs[i];if(!s||!o)continue;let c=F(a,r?a.length:te);e[s]=c.values,e[o]=c.truncated}}function Kr(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:M(n.get(i)?.resolution)})):[]}function Yr(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:M(n.get(i)?.type)})):[]}function Ys(e,t,n,r){let i=new Map(e.map(g=>[g.id,g])),a=t.profile==="strict",s=Hs(e,n,a),o=ar(e),c=qr(o,r),l=Vs(t,s,c.warnings),d=Hr(t,s),u=Vr(t,s,i),m=sr(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:[...Tt],counts:d,missing_by_type:m,duplicate_issue_codes_count:o.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]),Ks(f,t,s,r);let k=Kr(t,s,i),p=Yr(t,s,i);return{check:{name:"metadata",status:l.length===0?"ok":"warn",details:f},warnings:l,closeReasonBackfillRows:k,estimateBackfillRows:p}}function Js(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(We(m.status,t))),a=[],s=[];for(let m of i){let f=bs.filter(k=>!M(m[k]));f.length!==0&&(a.push({id:m.id,missing_fields:f}),s.push({id:m.id,missing_fields:f,close_reason:M(m.close_reason)}))}let o=a.length>0?[`validate_resolution_missing_fields:${a.length}`]:[],c=n?Number.POSITIVE_INFINITY:te,l=F(a.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=a.map(m=>Gs(m)),u=F(d,c);return{check:{name:"resolution",status:o.length===0?"ok":"warn",details:{checked_closed_items:i.length,missing_resolution_items:a.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:o,resolutionBackfillRows:s}}function Jr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xr(e,t="pm",n=Ke()){let r=new Set(e.map(a=>a.id)),i=[...e].sort((a,s)=>a.id.localeCompare(s.id));return new Map(i.map(a=>{let s=new Set,o=G(a.blocked_by);o&&r.has(o)&&s.add(o),(a.dependencies??[]).filter(l=>{let d=G(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>G(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=G(a.definition_of_ready);return Qr(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[a.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function Zr(e,t,n){let r=hn(e,n?d=>Ae(d,n):void 0),i=r.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),a=r.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),s=t?Number.POSITIVE_INFINITY:te,o=F(i,s),c=F(a,s),l=F(r.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>'`),s);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",details:{checked_items:e.length,dangling_reference_count:i.length+a.length,active_dangling_reference_count:i.length,dangling_reference_rows:o.values,dangling_reference_rows_truncated:o.truncated,legacy_terminal_dangling_reference_count:a.length,legacy_closed_dangling_reference_count:r.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:r.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function Qr(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${Jr(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,a)=>i.localeCompare(a))}function Ft(e){let t=0,n=new Map,r=new Map,i=[],a=new Set,s=[],o=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),a.add(d);for(let m of e.get(d)??[])n.has(m)?a.has(m)&&r.set(d,Math.min(r.get(d),n.get(m))):(o(m),r.set(d,Math.min(r.get(d),r.get(m))));if(r.get(d)!==n.get(d))return;let u=[];for(;i.length>0;){let m=i.pop();if(a.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),s.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||o(d);return s.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 Pt(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],a=new Set([n]),s=o=>{let c=(t.get(o)??[]).filter(l=>r.has(l));for(let l of c){if(l===n&&i.length>1)return i.push(n),!0;if(!a.has(l)){if(a.add(l),i.push(l),s(l))return!0;i.pop(),a.delete(l)}}return!1};return s(n)?[...i]:[...e,n]}function ei(e,t="pm"){let n=Xr(e,t),r=Ft(n),i=[...new Set(r.flat())].sort((s,o)=>s.localeCompare(o)),a=r.map(s=>Pt(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:a}}function ti(e,t=Ke()){let n=new Map(e.map(a=>[a.id.toLowerCase(),a.id])),r=new Map(e.map(a=>[a.id,[]]));return[...e].sort((a,s)=>a.id.localeCompare(s.id)).forEach(a=>{let s=r.get(a.id),o=G(a.parent),c=o?n.get(o.toLowerCase()):void 0;c&&s.push(c),(a.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"?r.get(u).push(a.id):s.push(u))})}),r.forEach((a,s)=>{r.set(s,[...new Set(a)].sort((o,c)=>o.localeCompare(c)))}),r}function ni(e){let t=ti(e),n=Ft(t),r=[...new Set(n.flat())].sort((a,s)=>a.localeCompare(s)),i=n.map(a=>Pt(a,t).join("->"));return{cycle_count:n.length,cycle_item_ids:r,cycle_sample_paths:i}}function ri(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 Ge(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function ii(e,t){let n=Ge(e).split("/").filter(Boolean),r=Ge(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function Xs(e,t){let n=Ge(t),r=Ge(e),i=t.endsWith("/")?t:`${t}/`,a=e.startsWith(i),s=n.length>0&&n===r,o=ii(e,t);return!a&&!s&&o===0?null:a?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:o+500,confidence:"same_directory"}:{score:o,confidence:"shared_directory"}}function Zs(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function Qs(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(a=>(r==="docs"?a.docs??[]:a.files??[]).map(s=>({item:a,link:s}))).forEach(({item:a,link:s})=>{if(s.scope!=="project")return;let o=oe(s.path);if(o.length===0||o===e)return;let c=Xs(e,o);c!==null&&Zs(i,a,c.score)&&(i={item:a,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function ai(e,t){return e.map(n=>{let r=ri(n),i=r==="docs_unowned"?"docs":"files",a=Qs(n,r,t),s=a?.id??"<id>";return{path:n,classification:r,owner_candidate:a,remediation_hint:`pm ${i} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function si(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function eo(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=G(e[n]);return i?r.some(a=>i.toLowerCase().includes(a)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function to(e,t,n,r,i){let a=G(t.parent),s=a?n.get(r.get(a.toLowerCase())??a):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!Ae(s.status,i)}}function no(e,t,n,r){let i=G(e.blocked_by),a=G(e.blocked_reason),s=a?.toLowerCase(),o=We(e.status,n),c=[];return t.has(o)?(!i&&!a&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(l=>s.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),a&&c.push("non_blocked_status_has_blocked_reason"),c)}function ro(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),a=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),o={activeItems:e.filter(c=>!Ae(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of o.activeItems){let l=eo(c,r);l.length>0&&o.closureLikeRows.push({id:c.id,fields:l});let d=G(c.parent),u=d?i.get(a.get(d.toLowerCase())??d):void 0;if(u&&Ae(u.status,n)&&(o.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),o.terminalParentFixRows.push(to(c,u,i,a,n))),t){let m=no(c,s,n,r);m.length>0&&o.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,k)=>f.localeCompare(k))})}}return o}function io(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 Or(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function ao(e,t,n,r,i,a){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=Or("validate_lifecycle_dependency_cycles",n,i),c=Or("validate_hierarchy_parent_cycle",r,a);return[...s,...o?[o]:[],...c?[c]:[]]}function oi(e){let t=oe(e);return t.length>Os||t.split(/[\\/]/).some(n=>n.length>Fs)}async function so(e,t){let n=$.isAbsolute(t)?t:$.resolve(e,t);if(oi(n))return!1;try{let r=await It.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return Ur(r,["ENOENT","ENOTDIR"])}}async function oo(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(a=>({item:i,artifact:a,link_kind:"files"})),...(i.docs??[]).map(a=>({item:i,artifact:a,link_kind:"docs"}))]);for(let{item:i,artifact:a,link_kind:s}of r){if(a.scope!=="project")continue;if(Re(a.path)){n.remoteLinkedPaths.add(a.path.trim());continue}let o=oe(a.path);o.length!==0&&(n.linkedProjectPaths.add(o),await so(t,a.path)&&(n.missingLinkedPaths.push(o),n.staleLinkRows.push({item_id:i.id,path:o,link_kind:s})))}return n}function co(e,t,n,r,i,a){let s=r==="tracked-all-strict",o=s&&!i,c=i||s,l=c?[]:js(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>Tr(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Tr(f,l)),m={};if(d.length>0){let f=ie(d,a);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:o,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function ci(e,t,n,r,i,a,s,o="pm"){let c=ro(e,t,i,a);io(c);let l=ei(c.activeItems,o),d=ni(e),u=ao(c,t,n,r,l.cycle_count,d.cycle_count),m=s?Number.POSITIVE_INFINITY:te,f=F(c.closureLikeRows.map(x=>`${x.id}:${x.fields.join(",")}`),m),k=F(c.terminalParentRows.map(x=>`${x.id}:${x.parent_id}:${x.parent_status}`),m),p=F(c.staleBlockerRows.map(x=>`${x.id}:${x.status}:${x.reasons.join(",")}`),m),g=F(l.cycle_item_ids,m),y=F(l.cycle_sample_paths,m),S=F(d.cycle_item_ids,m),A=F(d.cycle_sample_paths,m);return{check:{name:"lifecycle",status:l.cycle_count>0&&n==="error"||d.cycle_count>0&&r==="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:k.values,active_terminal_parent_rows_truncated:k.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:g.values,dependency_cycle_item_ids_truncated:g.truncated,dependency_cycle_sample_paths:y.values,dependency_cycle_sample_paths_truncated:y.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:S.values,parent_cycle_item_ids_truncated:S.truncated,parent_cycle_sample_paths:A.values,parent_cycle_sample_paths_truncated:A.truncated,stale_blocker_reason_patterns:[...a.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:a.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...a.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:a.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...a.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:a.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...a.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:a.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function li(e,t,n,r,i,a){let s=await oo(e,t),o=new Map(e.map(v=>[v.id,v])),c=[...new Set(s.missingLinkedPaths)].sort((v,I)=>v.localeCompare(I)),l=await Bs(t,r),d=co(l,n,t,r,i,a),u=d.candidateFiles.filter(v=>!s.linkedProjectPaths.has(v)),m=ai(u,e),f=lr(c,d.candidateFiles),k=new Map(f.map(v=>[v.path,v.classification])),p=f.filter(v=>v.classification==="moved").length,g=s.staleLinkRows.map(v=>({...v,classification:k.get(v.path)??"deleted"})).sort((v,I)=>v.item_id.localeCompare(I.item_id)||v.path.localeCompare(I.path)||v.link_kind.localeCompare(I.link_kind)),y=[];d.strictModeForcesPmInternals&&y.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&y.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&y.push(`validate_files_orphaned_paths:${u.length}`);let S=[...s.remoteLinkedPaths].sort((v,I)=>v.localeCompare(I)),A=ie(S,a),E=ie(c,a),x=ie(u,a),K=ie(m.map(v=>`${v.path}:${v.classification}:owner_candidate=${v.owner_candidate?.id??"unowned"}`),a),W=a?m:ie(si(m),!1).values,R=ie(dr(f),a),P=g.map(v=>({item_id:v.item_id,path:v.path,link_kind:v.link_kind,classification:v.classification})),q=mr(P,v=>{let I=o.get(v);return I?{type:I.type,title:I.title,status:I.status}:void 0}),D=a?q:ie(fr(q),!1).values;return{check:{name:"files",status:y.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:a?"full":"summary",file_list_summary_limit:Pr,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:i,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:s.linkedProjectPaths.size,remote_linked_paths_count:S.length,remote_linked_paths_total:A.total,remote_linked_paths:A.values,remote_linked_paths_truncated:A.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:E.total,missing_linked_paths:E.values,missing_linked_paths_truncated:E.truncated,missing_linked_paths_moved_count:p,missing_linked_paths_deleted_count:c.length-p,missing_linked_path_classifications:R.values,missing_linked_path_classifications_truncated:R.truncated,missing_linked_path_rows_count:q.length,missing_linked_path_rows:D,orphaned_paths_count:u.length,orphaned_paths_total:x.total,orphaned_paths:x.values,orphaned_paths_truncated:x.truncated,orphaned_path_classifications:K.values,orphaned_path_classifications_truncated:K.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:W}},warnings:y,staleLinkPruneRows:g}}async function lo(e,t,n){let{missingStreams:r,unreadableStreams:i,hashMismatches:a,chainMismatches:s,driftedItems:o}=await Yn(e,t),c=[];r.length>0&&c.push(`validate_history_drift_missing_streams:${r.length}`),i.length>0&&c.push(`validate_history_drift_unreadable_streams:${i.length}`),a.length>0&&c.push(`validate_history_drift_hash_mismatches:${a.length}`),s.length>0&&c.push(`validate_history_drift_chain_mismatches:${s.length}`);let l=n?Number.POSITIVE_INFINITY:te,d=F(o,l);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,drifted_items_count:o.length,drifted_items:d.values,drifted_items_truncated:d.truncated,counts:{missing_streams:r.length,unreadable_streams:i.length,hash_mismatches:a.length,chain_mismatches:s.length}}},warnings:c}}function uo(e,t,n){let r=n.trim().replaceAll(/\s+/g," "),i=r.length>120?`${r.slice(0,117)}...`:r;return`${e}:${t}:${i}`}function di(e,t,n){let r=new Set(e.map(g=>g.id.toLowerCase())),i=0,a=0,s=new Set,o=[],c=e.flatMap(g=>(g.tests??[]).map(y=>({item:g,linkedTest:y})));for(let{item:g,linkedTest:y}of c){if(typeof y.command!="string"||y.command.trim().length===0)continue;i+=1;let S=Ar(y.command,t);if(S.length!==0){a+=S.length;for(let A of S)s.add(A),r.has(A.toLowerCase())||o.push(uo(g.id,A,y.command))}}let l=[...new Set(o)].sort((g,y)=>g.localeCompare(y)),d=[...new Set(l.map(g=>g.split(":")[1]??""))].filter(g=>g.length>0).sort((g,y)=>g.localeCompare(y)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],m=n?Number.POSITIVE_INFINITY:te,f=F(l,m),k=F(d,m),p=F([...s].sort((g,y)=>g.localeCompare(y)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",details:{checked_items:e.length,linked_commands_scanned:i,referenced_pm_ids_count:a,unique_referenced_pm_ids_count:s.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:k.values,stale_pm_ids_truncated:k.truncated,stale_pm_id_reference_rows:f.values,stale_pm_id_reference_rows_truncated:f.truncated}},warnings:u}}function mo(e,t){let n=Qt(e.map(c=>({ref:c.id,version:Zt(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:te,a=F(n.outdated,i),s=F(n.ahead,i);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:Xt,outdated_items_count:n.outdated.length,outdated_items:a.values,outdated_items_truncated:a.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var Ct="pm validate auto-fix";async function ui(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Ct};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new h("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",_.USAGE);await n.runUpdate(e.item_id,r,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 At(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function mi(e,t,n){let r=[],i=[],a=new Map;for(let s of e.filter(o=>At(o)===null))try{await ui(s,t,n),r.push(s)}catch(o){i.push({fix:s,error:o})}for(let s of e.filter(o=>At(o)!==null)){let o=At(s),c=a.get(o);c?c.push(s):a.set(o,[s])}for(let s of a.values()){let o=s[0];if(!o)continue;let c=s.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{o.kind==="prune_file_link"?await vr(o.item_id,{remove:c,message:Ct},t):await wr(o.item_id,{remove:c,message:Ct},t),r.push(...s)}catch(l){i.push(...s.map(d=>({fix:d,error:l})))}}return{applied:r,failed:i}}var ru={applyValidateFix:ui,applyValidateFixes:mi,attachValidateFixHints:Gr,buildCommandReferencesCheck:di,buildDependencyReferencesCheck:Zr,buildCloseReasonBackfillRows:Kr,buildFilesCheck:li,buildLifecycleCheck:ci,buildLifecycleDependencyGraph:Xr,buildLifecycleParentGraph:ti,buildEstimateBackfillRows:Yr,buildMetadataCounts:Hr,buildMissingFieldOccurrences:Vr,buildOrphanedPathRows:ai,classifyOrphanedPath:ri,collectDefaultProjectFileCandidates:xt,collectTrackedGitFileCandidates:zr,detectLifecycleDependencyCycles:ei,detectLifecycleParentCycles:ni,escapeRegExp:Jr,extractItemIds:Qr,findLifecycleDependencyCycleComponents:Ft,isMetadataFieldMissing:$r,linkedArtifactPathExceedsFilesystemLimits:oi,listFilesRecursive:Ot,resolveDependencyCycleSeverity:Mr,resolveParentCycleSeverity:Lr,resolveFileScanMode:jr,resolveLifecycleDependencyCycleSamplePath:Pt,resolveRequestedChecks:Wr,resolveValidateMetadataProfile:Nr,resolveWorkspaceRoot:Br,sharedDirectoryPrefixLength:ii,summarizeOrphanedPathRows:si,summarizeDuplicateIssueCodes:qr,toMeaningfulString:G};async function fo(e,t,n,r){let i=await Bn(e,new Set(t.map(m=>m.id)),n,{schema:r.schema,extensionFieldNames:Lt(Y())}),a=[];i.unreadable_item_files.length>0&&a.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&a.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&a.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&a.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&a.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&a.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let s=a.length,o=await _r(e);o.tracked_path_count>0&&a.push(`validate_storage_tracked_runtime_cache_files:${o.tracked_path_count}`);let c=await Cn(e,Fe(r));c.status==="drift"&&a.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await ke(e),d=l===null?null:await In(l);d!==null&&d.status!=="ok"&&a.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await ft(l);return u.length>0&&a.push(`validate_merge_decisions_unreviewed:${u.length}`),{check:{name:"storage_integrity",status:s>0?"error":a.length>0?"warn":"ok",details:{...i,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:o.tracker_relative_root,tracked_paths:o.tracked_paths,tracked_path_count:o.tracked_path_count,remediation_command:o.remediation_command}}},warnings:a}}function ee(e,t,n){n&&Gr(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function po(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let i=Ys(e.items,e.metadataPolicy,e.statusRegistry,r);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,ee(t,i,n)}if(e.requestedChecks.has("resolution")){let i=Js(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,ee(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=ci(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,ee(t,i,n),ee(t,Zr(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await li(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=i.staleLinkPruneRows,ee(t,i,n)}return e.requestedChecks.has("command_references")&&ee(t,di(e.items,e.settings.id_prefix,r),n),e.requestedChecks.has("history_drift")&&ee(t,await lo(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&ee(t,mo(e.items,r),n),e.requestedChecks.has("storage_integrity")&&ee(t,await fo(e.pmRoot,e.items,H(e.settings,Y()).type_to_folder,e.settings),n),t}function _o(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...Zn(t.closeReasonBackfillRows)),r.push(...Xn(t.resolutionBackfillRows)),r.push(...Qn(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...er(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...tr(t.staleLinkPruneRows)),r}async function ho(e,t,n,r,i,a){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=_o(e,t,n),{applicable:o,gated:c}=rr(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await mi(o,i,a);d.push(...m.applied.map(Se)),u.push(...m.failed.map(({fix:f,error:k})=>({...Se(f),error:k instanceof Error?k.message:String(k)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,f)=>m.localeCompare(f)),planned_count:s.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(Se),applied_fixes:d,gated_fixes:c.map(m=>({...Se(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function iu(e,t,n={}){Kt(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new h("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",_.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new h("--fix-scope requires --auto-fix.",_.USAGE);let i=nr(e.fixScope),a=j(process.cwd(),t.path);if(!await N(B(a)))throw new h(`Tracker is not initialized at ${a}. Run pm init first.`,_.NOT_FOUND);let s=await L(a),o=Vt(s.schema),c=H(s,Y()),l=[],d=await mn(a,s.item_format,c.type_to_folder,l,s.schema),u=Wr(e);if(u.has("history_drift")){let P=await ut(a);P.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${P.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",f=Nr(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),k=Ls(f,m,s.validation.metadata_required_fields),p=Ns(s),g=Mr(e.dependencyCycleSeverity),y=Lr(e.parentCycleSeverity),S=jr(e.scanMode),A=Br(a),E=await po({requestedChecks:u,options:e,global:t,pmRoot:a,workspaceRoot:A,settings:s,items:d,statusRegistry:o,metadataPolicy:k,lifecyclePatternPolicy:p,dependencyCycleSeverity:g,parentCycleSeverity:y,fileScanMode:S,initialWarnings:[...new Set(l)]}),x=r?await ho(e,E,s,i,t,n):void 0,K=[...new Set(E.warnings)].sort((P,q)=>P.localeCompare(q)),R={ok:!E.checks.some(P=>P.status==="error"),has_warnings:K.length>0,checks:E.checks,warnings:K,...x!==void 0?{fixes:x}:{},generated_at:ne(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?R:{...Ds(R),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{vo as a,gi as b,yi as c,se as d,we as e,Si as f,ke as g,st as h,Fe as i,Cn as j,In as k,Bo as l,Uo as m,Ai as n,Yn as o,na as p,b as q,O as r,Ii as s,fc as t,pc as u,_c as v,Pn as w,hc as x,gc as y,yc as z,wc as A,kc as B,dt as C,vc as D,bc as E,lt as F,Sc as G,Rc as H,Dn as I,Ac as J,Li as K,Mn as L,Dc as M,ut as N,Ui as O,zi as P,Nc as Q,Gi as R,_r as S,qc as T,Hc as U,ft as V,Vc as W,Kc as X,Bn as Y,wr as Z,vr as _,dd as $,ud as aa,is as ba,as as ca,fd as da,pd as ea,_d as fa,hd as ga,os as ha,cs as ia,ls as ja,gd as ka,Sr as la,us as ma,Rr as na,Rt as oa,Er as pa,ms as qa,fs as ra,ps as sa,Ds as ta,ru as ua,iu as va};
14
+ //# sourceMappingURL=chunk-CMDS3KYT.js.map
@@ -1,6 +1,6 @@
1
- import{c as v}from"./chunk-QHRTT7WT.js";import{Ea as C,Pa as j,p as y,u as I}from"./chunk-RW5IYD4J.js";import{S as x,Y as c,Z as f,o as E,p as S,q as A}from"./chunk-ZJIMJHDB.js";import O from"node:fs/promises";import u 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]="6fc24a7c-a359-51fd-a432-4c8037d10e9e")}catch{}})();var G=["extensions","docs","examples","assets","prompts"],J=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});function K(e){return G.includes(e)}function V(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],r=[];for(let i of n){if(typeof i!="string"||i.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,c.USAGE);r.push(i.trim())}return[...new Set(r)].sort((i,o)=>i.localeCompare(o))}function Y(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new f("Package manifest field pm must be an object.",c.USAGE);let t={},n=e;for(let[r,i]of Object.entries(n)){if(!K(r))continue;let o=V(r,i);o.length>0&&(t[r]=o)}return t}function l(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function k(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,r)=>n.localeCompare(r)):void 0}function D(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=e.url;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}}function B(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:l(t,"docs"),npm:l(t,"npm"),repository:l(t,"repository"),report:l(t,"report")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function W(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:l(t,"image"),video:l(t,"video")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function H(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:l(t,"display_name")??l(t,"displayName"),category:l(t,"category"),summary:l(t,"summary"),links:B(t.links),media:W(t.media),tags:k(t.tags)};return Object.values(n).some(r=>r!==void 0)?n:void 0}async function X(e){let t=u.join(e,"package.json");if(!await y(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await O.readFile(t,"utf8"))}catch(a){throw new f(`Failed to parse package manifest at "${t}": ${String(a)}`,c.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new f(`Package manifest at "${t}" must be a JSON object.`,c.USAGE);let r=n,i=r.pm,o=i!=null,s=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};return{source:o?"pm":"convention",package_json_path:t,package_name:typeof r.name=="string"?r.name:void 0,package_version:typeof r.version=="string"?r.version:void 0,package_private:r.private===!0,package_description:typeof r.description=="string"?r.description:void 0,package_keywords:k(r.keywords),package_homepage:typeof r.homepage=="string"?r.homepage:void 0,package_repository_url:D(r.repository),package_bugs_url:D(r.bugs),aliases:k(s.aliases),resources:Y(i),catalog:H(s.catalog)}}async function $(e){if(!await y(e))return[];let t=await O.readdir(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let i=u.join(e,r.name);await y(u.join(i,"manifest.json"))&&n.push(i)}return n.sort((r,i)=>r.localeCompare(i))}async function Ae(e){if(await y(u.join(e,"manifest.json")))return[e];let n=(await X(e)).resources.extensions??[],r=new Set;for(let i of n){if(i.includes("*")||i.startsWith("!"))throw new f(`Package extension entry "${i}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,c.USAGE);let o=u.resolve(e,i);if(!I(e,o))throw new f(`Package extension entry "${i}" resolves outside package root.`,c.USAGE);if(await y(u.join(o,"manifest.json"))){r.add(o);continue}for(let s of await $(o))r.add(s)}if(n.length===0)for(let i of J.extensions)for(let o of await $(u.join(e,i)))r.add(o);return[...r].sort((i,o)=>i.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60cccce0-d933-5180-ac30-0cea1679c656")}catch{}})();var N=1,T=6,F=[["commands","Commands"],["command_overrides","Command overrides"],["flag_commands","Flag commands"],["item_types","Item types"],["item_fields","Item fields"],["migrations","Migrations"],["profiles","Profiles"],["importers","Importers"],["exporters","Exporters"],["search_providers","Search providers"],["vector_store_adapters","Vector store adapters"],["hooks","Lifecycle hooks"],["parser_overrides","Parser overrides"],["service_overrides","Service overrides"],["renderer_overrides","Renderer overrides"]];function w(e){return"#".repeat(e)}function M(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let o of e)n=o==="`"?n+1:0,t=Math.max(t,n);let r="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${r}${i}${e}${i}${r}`}function Q(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(M).join(", ")}`}function Z(e,t,n){let r=[`${w(t)} ${e}`,""];return n.length===0?(r.push("_None._",""),r):(r.push(...n.map(i=>`- ${M(i)}`),""),r)}function ee(e,t,n){return e===0&&!n?[]:[`${w(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function Te(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<N||n>T)throw new RangeError(`headingLevel must be an integer in [${N}, ${T}], received ${String(t.headingLevel)}`);let r=Math.min(n+1,T),i=t.includeEmpty===!0,o=t.title??"Extension surfaces",s=[`${w(n)} ${o}`,""];(i||e.capabilities.length>0)&&s.push(Q(e.capabilities),"");for(let[d,g]of F){let h=e[d];h.length===0&&!i||s.push(...Z(g,r,h))}return s.push(...ee(e.preflight_overrides,r,i)),!(e.preflight_overrides>0||F.some(([d])=>e[d].length>0))&&!i&&s.push("_This extension registers no surfaces._",""),`${s.join(`
1
+ import{c as v}from"./chunk-GWI6YIKJ.js";import{Ea as C,Pa as j,p as y,u as I}from"./chunk-FPDYXZBK.js";import{S as x,Y as c,Z as f,o as E,p as S,q as A}from"./chunk-54EU2UVO.js";import O from"node:fs/promises";import u 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]="6fc24a7c-a359-51fd-a432-4c8037d10e9e")}catch{}})();var G=["extensions","docs","examples","assets","prompts"],J=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});function K(e){return G.includes(e)}function V(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],r=[];for(let i of n){if(typeof i!="string"||i.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,c.USAGE);r.push(i.trim())}return[...new Set(r)].sort((i,o)=>i.localeCompare(o))}function Y(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new f("Package manifest field pm must be an object.",c.USAGE);let t={},n=e;for(let[r,i]of Object.entries(n)){if(!K(r))continue;let o=V(r,i);o.length>0&&(t[r]=o)}return t}function l(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function k(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,r)=>n.localeCompare(r)):void 0}function D(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=e.url;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}}function B(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:l(t,"docs"),npm:l(t,"npm"),repository:l(t,"repository"),report:l(t,"report")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function W(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:l(t,"image"),video:l(t,"video")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function H(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:l(t,"display_name")??l(t,"displayName"),category:l(t,"category"),summary:l(t,"summary"),links:B(t.links),media:W(t.media),tags:k(t.tags)};return Object.values(n).some(r=>r!==void 0)?n:void 0}async function X(e){let t=u.join(e,"package.json");if(!await y(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await O.readFile(t,"utf8"))}catch(a){throw new f(`Failed to parse package manifest at "${t}": ${String(a)}`,c.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new f(`Package manifest at "${t}" must be a JSON object.`,c.USAGE);let r=n,i=r.pm,o=i!=null,s=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};return{source:o?"pm":"convention",package_json_path:t,package_name:typeof r.name=="string"?r.name:void 0,package_version:typeof r.version=="string"?r.version:void 0,package_private:r.private===!0,package_description:typeof r.description=="string"?r.description:void 0,package_keywords:k(r.keywords),package_homepage:typeof r.homepage=="string"?r.homepage:void 0,package_repository_url:D(r.repository),package_bugs_url:D(r.bugs),aliases:k(s.aliases),resources:Y(i),catalog:H(s.catalog)}}async function $(e){if(!await y(e))return[];let t=await O.readdir(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let i=u.join(e,r.name);await y(u.join(i,"manifest.json"))&&n.push(i)}return n.sort((r,i)=>r.localeCompare(i))}async function Ae(e){if(await y(u.join(e,"manifest.json")))return[e];let n=(await X(e)).resources.extensions??[],r=new Set;for(let i of n){if(i.includes("*")||i.startsWith("!"))throw new f(`Package extension entry "${i}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,c.USAGE);let o=u.resolve(e,i);if(!I(e,o))throw new f(`Package extension entry "${i}" resolves outside package root.`,c.USAGE);if(await y(u.join(o,"manifest.json"))){r.add(o);continue}for(let s of await $(o))r.add(s)}if(n.length===0)for(let i of J.extensions)for(let o of await $(u.join(e,i)))r.add(o);return[...r].sort((i,o)=>i.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60cccce0-d933-5180-ac30-0cea1679c656")}catch{}})();var N=1,T=6,F=[["commands","Commands"],["command_overrides","Command overrides"],["flag_commands","Flag commands"],["item_types","Item types"],["item_fields","Item fields"],["migrations","Migrations"],["profiles","Profiles"],["importers","Importers"],["exporters","Exporters"],["search_providers","Search providers"],["vector_store_adapters","Vector store adapters"],["hooks","Lifecycle hooks"],["parser_overrides","Parser overrides"],["service_overrides","Service overrides"],["renderer_overrides","Renderer overrides"]];function w(e){return"#".repeat(e)}function M(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let o of e)n=o==="`"?n+1:0,t=Math.max(t,n);let r="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${r}${i}${e}${i}${r}`}function Q(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(M).join(", ")}`}function Z(e,t,n){let r=[`${w(t)} ${e}`,""];return n.length===0?(r.push("_None._",""),r):(r.push(...n.map(i=>`- ${M(i)}`),""),r)}function ee(e,t,n){return e===0&&!n?[]:[`${w(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function Te(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<N||n>T)throw new RangeError(`headingLevel must be an integer in [${N}, ${T}], received ${String(t.headingLevel)}`);let r=Math.min(n+1,T),i=t.includeEmpty===!0,o=t.title??"Extension surfaces",s=[`${w(n)} ${o}`,""];(i||e.capabilities.length>0)&&s.push(Q(e.capabilities),"");for(let[d,g]of F){let h=e[d];h.length===0&&!i||s.push(...Z(g,r,h))}return s.push(...ee(e.preflight_overrides,r,i)),!(e.preflight_overrides>0||F.some(([d])=>e[d].length>0))&&!i&&s.push("_This extension registers no surfaces._",""),`${s.join(`
2
2
  `).trimEnd()}
3
3
  `}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e3f016bb-8add-5765-bb1a-a7b22423f8d1")}catch{}})();var te=["agile","ops","research"],ne={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function Ie(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${te.join(", ")}.`)}function ve(e){return ne[e].map(t=>v(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="79b35844-ab8e-5b6f-9975-4dd85b210bcb")}catch{}})();var re=new Set(S),ie=new Set(A),L=new Set([...x.filter(e=>e!=="severity"),"id","title","type","status","priority","tags","assignee","parent","description","body","created_at","updated_at","closed_at","completed_at","author","deadline","estimate","sprint","release","risk","confidence","reviewer","resolution","expected","actual"]),oe=["create","update"];function p(e){return typeof e=="string"?e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_"):""}function R(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function P(e){return e.replaceAll("_","-")}function se(e,t){let n=new Set;for(let r of e){let i=R(r);i.length>0&&i!==t&&n.add(i)}return[...n].sort((r,i)=>r.localeCompare(i))}function ae(e){let t=new Set;for(let n of e??[]){let r=n.trim();r.length>0&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function de(e){let t=new Set,n=[];for(let r of e??[]){let i=r.trim().toLowerCase();if(i.length!==0){if(!ie.has(i))throw new Error(`Invalid field command "${r}". Allowed: ${A.join(", ")}.`);t.has(i)||(t.add(i),n.push(i))}}return e===void 0||n.length===0?[...oe]:n}function $e(e){let t=p(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(L.has(t))throw new Error(`Cannot define custom field "${t}": custom schema field "${t}" collides with built-in item metadata "${t}". Rename the custom field with a project-specific prefix. Reserved fields: ${[...L].sort((h,q)=>h.localeCompare(q)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!re.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${S.join(", ")}.`);let r=n,i=de(e.commands),o=R(e.cliFlag),s=o.length>0&&o!==P(t)?o:void 0,a=s??P(t),d=se(e.aliases??[],a),g=e.description?.trim();return{key:t,type:r,commands:i,description:g&&g.length>0?g:void 0,cliFlag:s,cliAliases:d,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:ae(e.requiredTypes)}}function le(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function ce(e){let t=le(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let i=r;typeof i.key!="string"||i.key.trim().length===0||n.push(i)}return n}function Oe(e){if(e==null||e.trim().length===0)return{fields:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/fields.json contains invalid JSON.")}return{fields:ce(t)}}function Ne(e){return`${JSON.stringify({fields:e.fields},null,2)}
4
4
  `}function Fe(e,t){let n=e.fields.find(s=>p(s.key)===t.key),r=n!==void 0,i=e.fields.filter(s=>p(s.key)!==t.key),o={...n,key:t.key,type:t.type,commands:[...t.commands]};return U(o,"description",t.description),U(o,"cli_flag",t.cliFlag),t.cliAliases.length>0?o.cli_aliases=[...t.cliAliases]:delete o.cli_aliases,z(o,"required",t.required),z(o,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?o.allow_unset=!1:delete o.allow_unset,t.requiredTypes.length>0?o.required_types=[...t.requiredTypes]:delete o.required_types,i.push(o),i.sort((s,a)=>p(s.key).localeCompare(p(a.key))),{file:{fields:i},definition:o,replaced:r}}function Me(e,t){let n=p(t);if(n.length===0)throw new Error("Field key must not be empty.");let r=[],i=e.fields.filter(o=>p(o.key)===n?(r.push(o),!1):!0);return r.length===0?{file:{fields:i},removed:!1}:{file:{fields:i},removed:!0,definition:r[0]}}function U(e,t,n){let r=e;n!==void 0&&n.length>0?r[t]=n:delete r[t]}function z(e,t,n){let r=e;n?r[t]=!0:delete r[t]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f81297bd-06ac-5aa4-9e1b-802fb50c9cd0")}catch{}})();var fe=new Set(E),ue=2e3,_=new Map,b=new Set(C.map(e=>m(e.id)).filter(e=>e.length>0));function m(e){if(typeof e!="string")return"";let t=_.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return _.size>=ue&&j(_),_.set(e,n),n}function pe(e){let t=new Set;for(let n of e){let r=m(n);r.length>0&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function Re(e){let t=m(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(b.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...b].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let s=new Set;for(let a of e.roles){let d=typeof a=="string"?a.trim().toLowerCase():"";if(d.length!==0){if(!fe.has(d))throw new Error(`Invalid status role "${a}". Allowed roles: ${E.join(", ")}.`);s.has(d)||(s.add(d),n.push(d))}}}let r=e.aliases===void 0?void 0:pe(e.aliases).filter(s=>s!==t),i=e.description?.trim(),o=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:r,description:i&&i.length>0?i:void 0,order:o}}function me(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function ye(e){let t=me(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let i=r;typeof i.id!="string"||i.id.trim().length===0||n.push(i)}return n}function qe(e){if(e==null||e.trim().length===0)return{statuses:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/statuses.json contains invalid JSON.")}return{statuses:ye(t)}}function Ge(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
5
5
  `}function Je(e,t,n){let r=e.statuses.slice(),i=r.findIndex(a=>m(a.id)===t.id),o=i>=0?r[i]:n,s={...o,id:t.id};return t.roles!==void 0&&(t.roles.length>0?s.roles=[...t.roles]:s.roles!==void 0&&delete s.roles),t.aliases!==void 0&&(t.aliases.length>0?s.aliases=[...t.aliases]:s.aliases!==void 0&&delete s.aliases),t.description!==void 0&&(s.description=t.description),t.order!==void 0&&(s.order=t.order),i>=0?r[i]=s:r.push(s),{file:{statuses:r},definition:s,replaced:o!==void 0}}function Ke(e,t){let n=m(t);if(n.length===0)throw new Error("Status id must not be empty.");if(b.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...b].join(", ")}.`);let r=e.statuses.slice(),i=r.findIndex(s=>m(s.id)===n);if(i<0)return{file:{statuses:r},removed:!1};let[o]=r.splice(i,1);return{file:{statuses:r},removed:!0,definition:o}}function Ve(e,t){let n=[e.id,...e.aliases??[]];for(let r of n){let i=m(r);if(i.length===0)continue;let o=t.get(i);if(o!==void 0&&o!==e.id)throw new Error(`Status token "${i}" already belongs to status "${o}". Choose a different id/alias to avoid shadowing it.`)}}export{G as a,J as b,X as c,Ae as d,te as e,ne as f,Ie as g,ve as h,p as i,$e as j,Oe as k,Ne as l,Fe as m,Me as n,b as o,m as p,Re as q,qe as r,Ge as s,Je as t,Ke as u,Ve as v,Te as w};
6
- //# sourceMappingURL=chunk-NBJKQP4S.js.map
6
+ //# sourceMappingURL=chunk-DMKOMTTY.js.map
@@ -1,5 +1,5 @@
1
- import{X as we,l as pe,t as T,u as ye,v as ge,w as _e}from"./chunk-DQ6FKGL3.js";import{e as fe,f as me,g as he}from"./chunk-YZEZAPJK.js";import{a as M}from"./chunk-4EX25PXM.js";import{Aa as j,Ba as I,K as re,L as S,La as x,M as P,ba as D,bb as ue,da as ne,ea as ie,eb as le,fa as oe,ga as se,k as F,la as ae,n as te,ta as O,wa as ce,xa as de,za as B}from"./chunk-MOTJFQ3F.js";import{D as L,J as C,M as k,h as Z,p as E,q as ee}from"./chunk-RW5IYD4J.js";import{Y as y,Z as g,aa as w}from"./chunk-ZJIMJHDB.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="582576df-8dbe-5f93-890b-5d872669dfe8")}catch{}})();function U(e,t){let n=D(e);if(n)throw new g(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,y.GENERIC_FAILURE);let r=[];for(let[o,a]of e.split(/\r?\n/).entries()){let i=a.trim();if(i)try{let d=JSON.parse(i);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");r.push(d)}catch{throw new g(`History merge input (${t}) contains invalid JSON at line ${o+1}.`,y.GENERIC_FAILURE)}}return r}function v(e){return w({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function Ne(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&v(e[r])===v(t[r]);)r+=1;return r}function Re(e,t,n){U(e,"base");let r=U(t,"ours"),o=U(n,"theirs"),a=Ne(r,o);if(a===r.length&&a===o.length)return{merged:I(r),strategy:"identical",common_entries:a,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(a===o.length)return{merged:I(r),strategy:"fast_forward_ours",common_entries:a,entries_from_ours:r.length-a,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(a===r.length)return{merged:I(o),strategy:"fast_forward_theirs",common_entries:a,entries_from_ours:0,entries_from_theirs:o.length-a,entries_total:o.length,reanchored:!1};let i=r.slice(a),d=new Set(i.map(v)),c=o.slice(a).filter(u=>!d.has(v(u))),m=[...i,...c].sort((u,f)=>{let l=P(u.ts,f.ts);if(l!==0)return l;let h=d.has(v(u)),p=d.has(v(f));return h!==p?Number(p)-Number(h):v(u).localeCompare(v(f))}),s=j([...r.slice(0,a),...m]);return{merged:I(s.entries),strategy:"union_reanchor",common_entries:a,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:s.entries.length,reanchored:!0}}function J(e,t){let n=D(e);if(n)throw new g(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,y.GENERIC_FAILURE);let r=[];for(let[o,a]of e.split(/\r?\n/).entries()){let i=a.trim();if(!i)continue;let d;try{d=JSON.parse(i)}catch{throw new g(`Relationship merge input (${t}) contains invalid JSON at line ${o+1}.`,y.GENERIC_FAILURE)}if(typeof d!="object"||d===null||Array.isArray(d)||typeof d.eventId!="string"||typeof d.sequence!="number")throw new g(`Relationship merge input (${t}) line ${o+1} is not a relationship event (eventId + sequence required).`,y.GENERIC_FAILURE);r.push(d)}return r}function H(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
1
+ import{T,U as ye,V as ge,W as _e,o as pe,va as we}from"./chunk-CMDS3KYT.js";import{e as fe,f as me,g as he}from"./chunk-YSAHYUXX.js";import{g as M}from"./chunk-U646T7Z6.js";import{Aa as j,Ba as I,K as re,L as S,La as x,M as P,ba as D,bb as ue,da as ne,ea as ie,eb as le,fa as oe,ga as se,k as F,la as ae,n as te,ta as O,wa as ce,xa as de,za as B}from"./chunk-HGNKPSCB.js";import{D as L,J as C,M as k,h as Z,p as E,q as ee}from"./chunk-FPDYXZBK.js";import{Y as y,Z as g,aa as w}from"./chunk-54EU2UVO.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="582576df-8dbe-5f93-890b-5d872669dfe8")}catch{}})();function U(e,t){let n=D(e);if(n)throw new g(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,y.GENERIC_FAILURE);let r=[];for(let[o,a]of e.split(/\r?\n/).entries()){let i=a.trim();if(i)try{let d=JSON.parse(i);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");r.push(d)}catch{throw new g(`History merge input (${t}) contains invalid JSON at line ${o+1}.`,y.GENERIC_FAILURE)}}return r}function v(e){return w({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function Ne(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&v(e[r])===v(t[r]);)r+=1;return r}function Re(e,t,n){U(e,"base");let r=U(t,"ours"),o=U(n,"theirs"),a=Ne(r,o);if(a===r.length&&a===o.length)return{merged:I(r),strategy:"identical",common_entries:a,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(a===o.length)return{merged:I(r),strategy:"fast_forward_ours",common_entries:a,entries_from_ours:r.length-a,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(a===r.length)return{merged:I(o),strategy:"fast_forward_theirs",common_entries:a,entries_from_ours:0,entries_from_theirs:o.length-a,entries_total:o.length,reanchored:!1};let i=r.slice(a),d=new Set(i.map(v)),c=o.slice(a).filter(u=>!d.has(v(u))),m=[...i,...c].sort((u,f)=>{let l=P(u.ts,f.ts);if(l!==0)return l;let h=d.has(v(u)),p=d.has(v(f));return h!==p?Number(p)-Number(h):v(u).localeCompare(v(f))}),s=j([...r.slice(0,a),...m]);return{merged:I(s.entries),strategy:"union_reanchor",common_entries:a,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:s.entries.length,reanchored:!0}}function J(e,t){let n=D(e);if(n)throw new g(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,y.GENERIC_FAILURE);let r=[];for(let[o,a]of e.split(/\r?\n/).entries()){let i=a.trim();if(!i)continue;let d;try{d=JSON.parse(i)}catch{throw new g(`Relationship merge input (${t}) contains invalid JSON at line ${o+1}.`,y.GENERIC_FAILURE)}if(typeof d!="object"||d===null||Array.isArray(d)||typeof d.eventId!="string"||typeof d.sequence!="number")throw new g(`Relationship merge input (${t}) line ${o+1} is not a relationship event (eventId + sequence required).`,y.GENERIC_FAILURE);r.push(d)}return r}function H(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
2
2
  `)}
3
3
  `}function $e(e){return e.map((t,n)=>({...t,sequence:n+1}))}function ve(e,t,n){J(e,"base");let r=J(t,"ours"),o=J(n,"theirs"),a=Math.min(r.length,o.length),i=0;for(;i<a&&r[i].eventId===o[i].eventId;)i+=1;if(i===r.length&&i===o.length)return{merged:H(r),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===o.length)return{merged:H(r),strategy:"fast_forward_ours",common_entries:i,entries_from_ours:r.length-i,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===r.length)return{merged:H(o),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:o.length-i,entries_total:o.length,reanchored:!1};let d=r.slice(i),c=new Set(d.map(f=>f.eventId)),m=o.slice(i).filter(f=>!c.has(f.eventId)),s=[...d,...m].sort((f,l)=>{if(f.timestamp!==void 0&&l.timestamp!==void 0){let _=P(f.timestamp,l.timestamp);if(_!==0)return _}else{if(f.timestamp===void 0&&l.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let h=c.has(f.eventId),p=c.has(l.eventId);return h!==p?Number(p)-Number(h):0}),u=$e([...r.slice(0,i),...s]);return{merged:H(u),strategy:"union_reanchor",common_entries:i,entries_from_ours:d.length,entries_from_theirs:m.length,entries_total:u.length,reanchored:!0}}var Pe=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],De=["updated_at"];function b(e,t){return w(e??null)===w(t??null)}function je(e,t,n){let r=s=>Array.isArray(s)?s:[],o=new Set(r(e).map(s=>w(s))),a=r(t),i=new Set(a.map(s=>w(s))),d=r(n),c=new Set(d.map(s=>w(s))),m=a.filter(s=>{let u=w(s);return!o.has(u)||c.has(u)});for(let s of d){let u=w(s);!i.has(u)&&!o.has(u)&&m.push(s)}return m}function Me(e,t){return P(String(e),String(t))>=0?e:t}function q(e,t,n,r){return b(t,n)?{value:t,from_theirs:!1,conflict:!1}:b(e,t)?{value:n,from_theirs:!0,conflict:!1}:b(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function G(e){return{...e.metadata}}function z(e,t,n){try{return oe(ne(e,n),n)}catch(r){throw new g(`Item merge input (${t}) is not a readable item document: ${String(r)}`,y.GENERIC_FAILURE)}}function He(e,t,n,r){let o=new Set(Pe),a=new Set(De),i=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((c,m)=>c.localeCompare(m)),d={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let c of i){let m=e[c],s=t[c],u=n[c];if(o.has(c)){let l=je(m,s,u);d.merged[c]=l,b(l,s)||d.unionFields.push(c);continue}if(a.has(c)){d.merged[c]=Me(s,u);continue}let f=q(m,s,u,r);f.value!==void 0&&(d.merged[c]=f.value),f.conflict?(d.conflictFields.push(c),d.conflictDecisions.push({field:c,base:m,ours:s,theirs:u,retained:f.value,discarded:r==="theirs"?s:u})):f.from_theirs&&d.fieldsFromTheirs.push(c)}return d}function Ie(e,t,n,r={}){let o=r.preferred??"ours",a=e.trim().length>0,i=z(t,"ours",r),d=z(n,"theirs",r),c=a?z(e,"base",r):i,m=a?G(c):{},s=G(i),u=G(d),{merged:f,conflictFields:l,fieldsFromTheirs:h,unionFields:p,conflictDecisions:_}=He(m,s,u,o),R=q(a?c.body:"",i.body,d.body,o);return R.conflict?(l.push("body"),_.push({field:"body",base:a?c.body:"",ours:i.body,theirs:d.body,retained:R.value,discarded:o==="theirs"?i.body:d.body})):R.from_theirs&&h.push("body"),{merged:ie({metadata:f,body:R.value},r),conflict_fields:l,fields_from_theirs:h,union_fields:p,conflict_decisions:_,preferred:o}}function V(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function W(e,t){let n=D(e);if(n)throw new g(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,y.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new g(`JSON merge input (${t}) is not valid JSON.`,y.GENERIC_FAILURE)}}function Le(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=m=>{let s=new Map;for(let u of m){let f=w(u);s.set(f,(s.get(f)??0)+1)}return s},o=r(e),a=r(t),i=r(n);for(let[m,s]of o)if((a.get(m)??0)<s||(i.get(m)??0)<s)return null;let d=new Map(a),c=[];for(let m of n){let s=w(m),u=d.get(s)??0;u>0?d.set(s,u-1):c.push(m)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function Be(e,t,n,r,o,a,i){if(!V(t)||!V(n))return null;let d=V(e)?e:{},c={},m=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((s,u)=>s.localeCompare(u));for(let s of m){let u=o.length>0?`${o}.${s}`:s,f=Ue(d,t,n,s,r,u,a,i);f!==void 0&&(c[s]=f)}return c}function be(e,t,n,r,o,a,i){if(b(t,n))return t;let d=Le(e,t,n);if(d!==null)return d.acceptedTheirs&&i.push(o),d.merged;let c=Be(e,t,n,r,o,a,i);if(c!==null)return c;let m=q(e,t,n,r);return m.conflict?a.push(o):m.from_theirs&&i.push(o),m.value}function Ue(e,t,n,r,o,a,i,d){let c=Object.prototype.hasOwnProperty.call(t,r),m=Object.prototype.hasOwnProperty.call(n,r),s=Object.prototype.hasOwnProperty.call(e,r);if(c&&m)return be(e[r],t[r],n[r],o,a,i,d);if(c){if(s&&b(e[r],t[r])){d.push(a);return}return s?(i.push(a),o==="theirs"?void 0:t[r]):t[r]}if(!(s&&b(e[r],n[r])))return s?(i.push(a),o==="theirs"?n[r]:void 0):(d.push(a),n[r])}function Ee(e,t,n,r={}){let o=r.preferred??"ours",a=W(e,"base"),i=W(t,"ours"),d=W(n,"theirs"),c=[],m=[],s=be(a,i,d,o,"",c,m);return{merged:`${JSON.stringify(s??null,null,2)}
4
4
  `,conflict_paths:c,paths_from_theirs:m,preferred:o}}import{readFile as Je,writeFile as Ge}from"node:fs/promises";import ze 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]="182fee45-4de8-502d-8aec-84b5b8e4aecb")}catch{}})();var Se=["item","history","relationship","json"];function Ve(e){let t=e.trim().toLowerCase();if(Se.includes(t))return t;throw new g(`Unknown merge artifact "${e}". Supported values: ${Se.join(", ")}.`,y.USAGE)}function We(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new g(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,y.USAGE)}async function X(e,t){try{return await Je(e,"utf8")}catch{throw new g(`Cannot read merge ${t} file at ${e}.`,y.NOT_FOUND)}}async function qe(e){let t=C(process.cwd(),e.path);return await E(k(t))?x(t):null}function Xe(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function It(e,t){let n=Ve(e.artifact),r=We(e.prefer),o=ze.resolve(e.outputPath??e.oursPath),[a,i,d]=await Promise.all([X(e.basePath,"base"),X(e.oursPath,"ours"),X(e.theirsPath,"theirs")]),c,m,s=[],u={};if(n==="history"){let l=Re(a,i,d);c=l.merged,u.history={strategy:l.strategy,common_entries:l.common_entries,entries_from_ours:l.entries_from_ours,entries_from_theirs:l.entries_from_theirs,entries_total:l.entries_total,reanchored:l.reanchored}}else if(n==="relationship"){let l=ve(a,i,d);c=l.merged,u.relationship={strategy:l.strategy,common_entries:l.common_entries,entries_from_ours:l.entries_from_ours,entries_from_theirs:l.entries_from_theirs,entries_total:l.entries_total,reanchored:l.reanchored}}else if(n==="item"){let l=await qe(t),h=Ie(a,i,d,{format:Xe(e.itemPath??o,l),schema:l?.schema,extensionFieldNames:Z(F()),preferred:r});c=h.merged,s.push(...h.conflict_fields),u.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields},e.itemPath!==void 0&&(m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,decisions:h.conflict_decisions})}else{let l=Ee(a,i,d,{preferred:r});c=l.merged,s.push(...l.conflict_paths),u.json={paths_from_theirs:l.paths_from_theirs}}if(await Ge(o,c,"utf8"),m!==void 0){let l=await ye(m);l!==null&&(u.receipt=T(l))}let f=[];if(s.length>0){let l=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${s.join(", ")}; the ${r} value was kept. ${l} Review the merged file, re-apply the losing change if needed, then "git add" it.`)}return n==="history"&&u.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm validate --check-history-drift" and "pm history-repair --all" after the merge to reconcile item state with merged history.'),{ok:s.length===0,artifact:n,output_path:o,preferred:r,conflicts:s,...u,guidance:f,generated_at:S()}}import Ce from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dd5ab9c3-bc6f-59f1-be89-ad0ab2abe7b5")}catch{}})();function Oe(e,t){return t==="body"?e.body:e.metadata[t]}function K(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(o=>{let a=t.findIndex((i,d)=>!r.has(d)&&K(o,i));return a<0?!1:(r.add(a),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,o])=>Object.hasOwn(n,r)&&K(o,n[r]))}function Ae(e,t){let n=new Set(t),r=[];for(let o=e.length-1;o>=0&&n.size>0;o-=1){let a=e[o],i=new Set;for(let c of de(a.patch))i.add(M(c.path)),c.from&&i.add(M(c.from));let d=[...n].filter(c=>i.has(c));if(d.length!==0){for(let c of d)n.delete(c);r.push({index:o+1,ts:a.ts,author:a.author,op:a.op,fields:d.sort((c,m)=>c.localeCompare(m))})}}return r.reverse()}function Ke(e,t,n){let r=Ce.compare(t,n);if(r.length===0)return;let o=new Set;for(let h of r)o.add(M(h.path));let a=new Set([...o].filter(h=>K(Oe(t,h),Oe(n,h)))),i=new Set([...o].filter(h=>!a.has(h))),d=Ae(e,i),c=Ae(e,a),m=[...o].sort((h,p)=>h.localeCompare(p)),s=[...i].sort((h,p)=>h.localeCompare(p)),u=[...a].sort((h,p)=>h.localeCompare(p)),f=[...new Set(d.map(h=>h.author))].sort((h,p)=>h.localeCompare(p)),l=[...new Set(c.map(h=>h.author))].sort((h,p)=>h.localeCompare(p));return{reconciled_field_count:o.size,reconciled_fields:m,reverted_field_count:i.size,reverted_fields:s,discarded_events:d,discarded_authors:f,preserved_field_count:a.size,preserved_fields:u,preserved_events:c,preserved_authors:l,recovery_hint:d.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function Qe(e,t,n){let r=e.located?.itemPath??null,o=e.located?await ue(e.located,{schema:t.schema}):null;if(!o)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let a=ce(o.document),i=n[n.length-1]?.after_hash;return{currentItemReplay:a,currentItemPath:r,matchedChainBefore:O(a)===i,currentItemRawBeforeLock:o.raw,loadedItem:o}}function Ye(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function Ze(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:S(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Ce.compare(e.finalReplay,e.currentItemReplay):[],before_hash:O(e.finalReplay),after_hash:O(n),message:e.message,...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function et(e,t){let n=[];return e||n.push("history_repair_no_changes"),t>0&&n.push(`history_repair_skipped_unresolvable_ops:${t}`),n}async function tt(e){return me({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>fe({historyPath:e.historyPath,nextHistoryRaw:I(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>te({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function Q(e,t,n){let r=C(process.cwd(),n.path);if(!await E(k(r)))throw new g(`Tracker is not initialized at ${r}. Run pm init first.`,y.NOT_FOUND);let o=await x(r),a=L(o,F()),i=await he(r,e,o,a.type_to_folder);if(!await E(i.historyPath))throw new g(`No history stream exists for ${i.id}.`,y.NOT_FOUND);let d=await ee(i.historyPath),c=await se(i.historyPath,i.id);if(c.length===0)throw new g(`No history entries exist for ${i.id}; nothing to repair.`,y.USAGE);let m=B(c),s=j(c),u=await Qe(i,o,c),f=s.finalDocument,l=u.currentItemReplay!==null&&O(f)!==O(u.currentItemReplay),h=l&&u.currentItemReplay?Ke(s.entries,f,u.currentItemReplay):void 0,p=[s.entriesRehashed>0,s.entriesPatchRepaired>0,l,t.forceAuditEntry===!0].some(Boolean),_=re(t.author,o.author_default),R=!!t.dryRun,A=Ye({message:t.message,entriesRehashed:s.entriesRehashed,entriesPatchRepaired:s.entriesPatchRepaired,reconcileNeeded:l}),{rewrittenEntries:Y,auditEntryAdded:Fe}=Ze({reanchorEntries:s.entries,changed:p,reconcileNeeded:l,currentItemReplay:u.currentItemReplay,finalReplay:f,author:_,message:A,auditOperation:t.auditOperation??"history_repair",auditContext:t.auditContext}),N=B(Y);if(!N.ok)throw new g(`history-repair produced an invalid rewritten chain (${N.errors.join(", ")}).`,y.GENERIC_FAILURE);let $=et(p,s.skippedOps);return h&&h.discarded_events.length>0&&($.push(`history_repair_reconcile_discards_events:${h.discarded_events.length}`),$.push(`history_repair_discarded_authors:${h.discarded_authors.join(",")}`)),p&&!R&&$.push(...await tt({pmRoot:r,subject:i,settings:o,typeRegistry:a,historyRawBeforeLock:d,currentItemRawBeforeLock:u.currentItemRawBeforeLock,author:_,force:t.force,loadedItem:u.loadedItem,historyPath:i.historyPath,rewrittenEntries:Y})),{id:i.id,dry_run:R,changed:p,history:{path:i.historyPath,entries_scanned:c.length,chain_drift_before:!m.ok,entries_rehashed:s.entriesRehashed,entries_patch_repaired:s.entriesPatchRepaired,converted_replace_to_add:s.convertedReplaceToAdd,skipped_ops:s.skippedOps,reconciled_with_item:l,audit_entry_added:Fe,verify_ok:N.ok,verify_errors:N.errors},item:{exists:u.currentItemPath!==null,path:u.currentItemPath,matched_chain_before:u.matchedChainBefore},...h?{reconciliation:h}:{},warnings:[...new Set($)].sort((xe,Te)=>xe.localeCompare(Te)),generated_at:S()}}function Ut(e,t){if(t&&e!==void 0)throw new g("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",y.USAGE);if(!t&&e===void 0)throw new g("history-repair: provide an item <id> or pass --all to repair every drifted stream.",y.USAGE)}async function ke(e,t){let n=C(process.cwd(),t.path);if(!await E(k(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,y.NOT_FOUND);let r=await x(n),o=L(r,F()),a=[],i=await le(n,r.item_format,o.type_to_folder,a,r.schema,{forceSourceScan:!0}),d=await pe(n,i),c=[],m=[],s={repaired:0,skipped_clean:0,failed:0};for(let u of d.driftedItems)try{let f=await Q(u,{...e,auditContext:e.auditContextById?.[u],auditContextById:void 0},t),l=f.changed?"repaired":"skipped_clean";s[l]+=1,m.push(...f.warnings.map(h=>`${u}:${h}`)),c.push({id:u,outcome:l,entries_rehashed:f.history.entries_rehashed,entries_patch_repaired:f.history.entries_patch_repaired,reconciled_with_item:f.history.reconciled_with_item,...f.reconciliation?{reconciliation:f.reconciliation}:{},warnings:f.warnings})}catch(f){s.failed+=1,c.push({id:u,outcome:"failed",error:f instanceof Error?f.message:String(f)})}return e.dryRun||await ae(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:i.length,drifted_streams:d.driftedItems.length,streams:c,totals:s,warnings:[...new Set([...a,...m])].sort((u,f)=>u.localeCompare(f)),generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2f34565-7664-5612-815d-949b8b1d4f90")}catch{}})();async function Wt(e,t){let n=e.dryRun===!0,r=await ge(process.cwd()),o=r.reduce((p,_)=>((p[_.item_id]??=[]).push(_),p),{}),a=Object.fromEntries(Object.entries(o).map(([p,_])=>[p,{merge:{receipts:_.map(T)}}])),i=await ke({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:a},t),d=new Set(i.streams.map(p=>p.id)),c=Object.keys(o).filter(p=>!d.has(p));(await Promise.allSettled(c.map(p=>Q(p,{dryRun:n,author:e.author??t.author,message:e.message??"record field-aware branch merge provenance",force:e.force,auditOperation:"merge_reconcile",auditContext:a[p],forceAuditEntry:!0},t)))).forEach((p,_)=>{let R=c[_];if(p.status==="fulfilled"){let A=p.value.changed?"repaired":"skipped_clean";i.streams.push({id:R,outcome:A,entries_rehashed:p.value.history.entries_rehashed,entries_patch_repaired:p.value.history.entries_patch_repaired,reconciled_with_item:p.value.history.reconciled_with_item,warnings:p.value.warnings}),i.totals[A]+=1}else i.streams.push({id:R,outcome:"failed",error:p.reason instanceof Error?p.reason.message:String(p.reason)}),i.totals.failed+=1});let s=0;!n&&i.totals.failed===0&&(await Promise.all(r.map(p=>_e(process.cwd(),p))),s=r.length);let u=await we({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),f=u.checks.every(p=>p.status==="ok"),l=i.totals.failed===0&&f,h=n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.","No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:l?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:l,dry_run:n,repair:i,receipts:{pending_before:r.length,reconciled:s,summaries:r.map(T)},validation:u,guidance:h,generated_at:u.generated_at}}export{Re as a,ve as b,Pe as c,De as d,Ie as e,Ee as f,Se as g,It as h,Q as i,Ut as j,ke as k,Wt as l};
5
- //# sourceMappingURL=chunk-CIXVQPB7.js.map
5
+ //# sourceMappingURL=chunk-F5B3HBEZ.js.map