@unbrained/pm-cli 2026.11.20 → 2026.11.22

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 (265) hide show
  1. package/.agents/skills/pm-developer/SKILL.md +1 -1
  2. package/.agents/skills/pm-sdk/SKILL.md +1 -1
  3. package/.agents/skills/pm-test-audit/SKILL.md +1 -1
  4. package/.claude-plugin/marketplace.json +1 -1
  5. package/CONTRIBUTING.md +2 -1
  6. package/dist/cli/error-guidance.js +2 -2
  7. package/dist/cli/register-history-maintenance.js +2 -2
  8. package/dist/cli/register-list-query.js +2 -2
  9. package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
  10. package/dist/cli-bundle/bundle-manifest.json +1 -1
  11. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +9 -0
  12. package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +125 -0
  13. package/dist/cli-bundle/chunks/{chunk-4TZW4NLM.js → chunk-5ZMVLWE3.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +33 -0
  15. package/dist/cli-bundle/chunks/{chunk-GXGW6KHB.js → chunk-AR4NP5HI.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-6X2AGUOT.js → chunk-B4PPFOPY.js} +3 -3
  17. package/dist/cli-bundle/chunks/{chunk-XK25TAJZ.js → chunk-B76TFRO2.js} +47 -45
  18. package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +8 -0
  19. package/dist/cli-bundle/chunks/{chunk-KDDIHGAO.js → chunk-EIGUKEV6.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-ZAO7VGX3.js → chunk-GTPCAJMZ.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +2 -0
  22. package/dist/cli-bundle/chunks/{chunk-KQSPKWFH.js → chunk-HC2OPETM.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-5LF5QZT3.js → chunk-HKUV74K3.js} +2 -2
  24. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +115 -0
  25. package/dist/cli-bundle/chunks/{chunk-FF4TXJDH.js → chunk-J2LABXBL.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-3BOR22MC.js → chunk-J52BEBSS.js} +2 -2
  27. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +3 -0
  28. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +3 -0
  29. package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +31 -0
  30. package/dist/cli-bundle/chunks/{chunk-DG2EOOFX.js → chunk-TC6XLIYO.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-MGYAJONE.js → chunk-U7EL3AYA.js} +2 -2
  32. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +6 -0
  33. package/dist/cli-bundle/chunks/{chunk-ZVEHACE6.js → chunk-X6MIWTTT.js} +2 -2
  34. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +2 -0
  35. package/dist/cli-bundle/chunks/{chunk-KEBLUTC3.js → chunk-XFHPKXAE.js} +2 -2
  36. package/dist/cli-bundle/chunks/{chunk-OXG5XPC7.js → chunk-YHVLVSEZ.js} +2 -2
  37. package/dist/cli-bundle/chunks/{chunk-Y4LXVPA5.js → chunk-YMUSRWV4.js} +2 -2
  38. package/dist/cli-bundle/chunks/{chunk-HQYIKAC6.js → chunk-YR2KEBHP.js} +2 -2
  39. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-ELEMA7IW.js → indexed-receipt-blobs-ITTXIN4K.js} +2 -2
  40. package/dist/cli-bundle/chunks/{item-revision-GE2CQECR.js → item-revision-4QBMZXKX.js} +2 -2
  41. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +2 -0
  42. package/dist/cli-bundle/chunks/{mutation-actor-5GYX7LP3.js → mutation-actor-FWLYWJ37.js} +2 -2
  43. package/dist/cli-bundle/chunks/{mutation-admission-72TYKPGU.js → mutation-admission-7ZDCK3G2.js} +2 -2
  44. package/dist/cli-bundle/chunks/{register-list-query-OQZZEWEB.js → register-list-query-RR5KACJ3.js} +10 -10
  45. package/dist/cli-bundle/chunks/{register-mutation-YZEUZ6XT.js → register-mutation-57AJQWFV.js} +2 -2
  46. package/dist/cli-bundle/chunks/{register-operations-JNVCF7EW.js → register-operations-RKWST7CU.js} +2 -2
  47. package/dist/cli-bundle/chunks/{register-setup-LDKULZSD.js → register-setup-CMI23PC5.js} +2 -2
  48. package/dist/cli-bundle/chunks/{settlement-hook-E5LHZ4RD.js → settlement-hook-BXN5LEQD.js} +2 -2
  49. package/dist/cli-bundle/chunks/{stage-Q2QZ2IBG.js → stage-4KDVXC5Z.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-JUYJ7NXL.js → chunk-2ZD7275J.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-7SB6VKEI.js → chunk-324AHXJO.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-IXYBN6D2.js → chunk-3IRCYJI5.js} +3 -3
  53. package/dist/cli-bundle/focused-chunks/{chunk-DH4DHL6V.js → chunk-3V53UBHN.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +91 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-V55XZFOP.js → chunk-4JZITIJB.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +2 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +78 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +2 -0
  59. package/dist/cli-bundle/focused-chunks/{chunk-BZCLW5V7.js → chunk-BRZV7BFV.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +3 -0
  61. package/dist/cli-bundle/focused-chunks/{chunk-PKMDWIP3.js → chunk-HDEKFSOK.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{chunk-O25KFLLA.js → chunk-IWOXAUDU.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{chunk-UATP3RK3.js → chunk-ML3JHCC6.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{chunk-ZKGGGU2K.js → chunk-OPGOOP25.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-PRFEOCNZ.js → chunk-RE7ZWT7D.js} +3 -3
  66. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +3 -0
  67. package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +8 -0
  68. package/dist/cli-bundle/focused-chunks/{chunk-KQJNJZKP.js → chunk-URGHTTT3.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +13 -0
  70. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +102 -0
  71. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +44 -0
  72. package/dist/cli-bundle/focused-chunks/{chunk-PQXTZLK3.js → chunk-WZWXGDYY.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/{chunk-5VSXKA35.js → chunk-YKSLZPLT.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-ZTRFCPH7.js → indexed-receipt-blobs-AF4U3F3D.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/{item-revision-OXDZHMJ7.js → item-revision-2O6MLPEX.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +2 -0
  78. package/dist/cli-bundle/focused-chunks/{mutation-actor-6DYIF6NH.js → mutation-actor-TCYDPUGG.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/{mutation-admission-2BYXANVJ.js → mutation-admission-LY73EJWM.js} +2 -2
  80. package/dist/cli-bundle/focused-chunks/{settlement-hook-OUBUN45C.js → settlement-hook-ARYCZQY4.js} +2 -2
  81. package/dist/cli-bundle/focused-chunks/{stage-FGHSB3QX.js → stage-DQ7RQQ52.js} +2 -2
  82. package/dist/cli-bundle/main.js +25 -25
  83. package/dist/cli-bundle/sdk-authoring.js +1 -1
  84. package/dist/cli-bundle/sdk-contracts.js +2 -2
  85. package/dist/cli-bundle/sdk-core.js +1 -1
  86. package/dist/cli-bundle/sdk-governance.js +1 -1
  87. package/dist/cli-bundle/sdk-graph.js +1 -1
  88. package/dist/cli-bundle/sdk-merge.js +70 -57
  89. package/dist/cli-bundle/sdk-query.js +1 -1
  90. package/dist/cli-bundle/sdk-runtime.js +1 -1
  91. package/dist/cli-bundle/sdk-testing.js +1 -1
  92. package/dist/cli-bundle/sdk.js +11 -11
  93. package/dist/core/diagnostics/remediation.js +1 -1
  94. package/dist/core/extensions/index.d.ts +2 -0
  95. package/dist/core/extensions/index.js +1 -1
  96. package/dist/core/fs/atomic-create.js +1 -1
  97. package/dist/core/fs/file-glob.js +1 -1
  98. package/dist/core/fs/fs-utils.d.ts +3 -1
  99. package/dist/core/fs/fs-utils.js +1 -1
  100. package/dist/core/history/bridge.js +2 -0
  101. package/dist/core/history/drift-scan.js +1 -1
  102. package/dist/core/history/history-rewrite.js +1 -1
  103. package/dist/core/history/history-stream-policy.js +1 -1
  104. package/dist/core/history/history.d.ts +12 -0
  105. package/dist/core/history/history.js +2 -2
  106. package/dist/core/history/projection.js +1 -1
  107. package/dist/core/history/read.d.ts +20 -1
  108. package/dist/core/history/read.js +1 -1
  109. package/dist/core/history/replay.d.ts +46 -5
  110. package/dist/core/history/replay.js +2 -2
  111. package/dist/core/history/stream-summary.d.ts +129 -0
  112. package/dist/core/history/stream-summary.js +3 -0
  113. package/dist/core/shared/errors.d.ts +8 -0
  114. package/dist/core/shared/errors.js +1 -1
  115. package/dist/core/shared/url-credentials.js +1 -1
  116. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  117. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  118. package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
  119. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  120. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  121. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
  122. package/dist/sdk/completion/fish.js +3 -2
  123. package/dist/sdk/completion/zsh.js +3 -2
  124. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  125. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  126. package/dist/sdk/governance/gc.js +1 -1
  127. package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
  128. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  129. package/dist/sdk/governance/health.js +2 -2
  130. package/dist/sdk/governance/validate.js +1 -1
  131. package/dist/sdk/governance/workspace-position.js +1 -1
  132. package/dist/sdk/history/append-only-repair.d.ts +30 -0
  133. package/dist/sdk/history/append-only-repair.js +6 -0
  134. package/dist/sdk/history/maintenance.d.ts +8 -2
  135. package/dist/sdk/history/maintenance.js +1 -1
  136. package/dist/sdk/history/reanchor-refusal.js +2 -0
  137. package/dist/sdk/history/reseed.d.ts +15 -0
  138. package/dist/sdk/history/reseed.js +2 -0
  139. package/dist/sdk/history/salvage.d.ts +19 -8
  140. package/dist/sdk/history/salvage.js +5 -3
  141. package/dist/sdk/history-compact.js +1 -1
  142. package/dist/sdk/history-provenance.js +1 -1
  143. package/dist/sdk/history-redact.js +1 -1
  144. package/dist/sdk/history-repair.d.ts +8 -2
  145. package/dist/sdk/history-repair.js +1 -1
  146. package/dist/sdk/index.d.ts +1 -1
  147. package/dist/sdk/item-transaction.d.ts +33 -1
  148. package/dist/sdk/item-transaction.js +1 -1
  149. package/dist/sdk/lifecycle/restore.js +1 -1
  150. package/dist/sdk/merge/index.d.ts +1 -1
  151. package/dist/sdk/merge/index.js +1 -1
  152. package/dist/sdk/merge/install.d.ts +20 -6
  153. package/dist/sdk/merge/install.js +3 -3
  154. package/dist/sdk/merge/three-way.d.ts +22 -3
  155. package/dist/sdk/merge/three-way.js +8 -2
  156. package/dist/sdk/merge/worktree-config.js +2 -1
  157. package/dist/sdk/public-surface.json +1 -1
  158. package/dist/sdk/query/activity.d.ts +67 -5
  159. package/dist/sdk/query/activity.js +1 -1
  160. package/dist/sdk/query/context.d.ts +13 -3
  161. package/dist/sdk/query/context.js +2 -2
  162. package/dist/sdk/query.d.ts +1 -1
  163. package/dist/sdk/runtime/actions.js +1 -1
  164. package/dist/sdk/runtime-input.d.ts +6 -2
  165. package/dist/sdk/runtime-input.js +1 -1
  166. package/dist/sdk/runtime-primitives.d.ts +1 -1
  167. package/dist/sdk/runtime-primitives.js +1 -1
  168. package/dist/sdk/runtime.d.ts +7 -0
  169. package/dist/sdk/runtime.js +1 -1
  170. package/dist/sdk/structured-mutations.d.ts +5 -5
  171. package/dist/sdk/structured-mutations.js +1 -1
  172. package/dist/sdk/transactions/item-finalization.js +2 -0
  173. package/dist/types.d.ts +20 -0
  174. package/dist/types.js +1 -1
  175. package/docs/AGENT_GUIDE.md +1 -1
  176. package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
  177. package/docs/COMMANDS.md +62 -4
  178. package/docs/HISTORY_RECOVERY.md +229 -5
  179. package/docs/MERGE_SAFETY.md +8 -0
  180. package/docs/MUTATION_INTEGRITY.md +3 -1
  181. package/docs/README.md +8 -6
  182. package/docs/SDK.md +128 -5
  183. package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
  184. package/docs/TESTING.md +8 -697
  185. package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +1 -1
  186. package/marketplace.json +1 -1
  187. package/node_modules/tar/package.json +2 -3
  188. package/package.json +35 -3
  189. package/packages/pm-beads/package.json +1 -1
  190. package/packages/pm-calendar/package.json +1 -1
  191. package/packages/pm-command-kit/package.json +1 -1
  192. package/packages/pm-digital-twin/package.json +1 -1
  193. package/packages/pm-governance-audit/package.json +1 -1
  194. package/packages/pm-guide-shell/package.json +1 -1
  195. package/packages/pm-kanban/package.json +1 -1
  196. package/packages/pm-lifecycle-hooks/package.json +1 -1
  197. package/packages/pm-linked-test-adapters/package.json +1 -1
  198. package/packages/pm-search-advanced/package.json +1 -1
  199. package/packages/pm-templates/package.json +1 -1
  200. package/packages/pm-todos/package.json +1 -1
  201. package/packages/pm-vcs/package.json +1 -1
  202. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  203. package/plugins/pm-claude/package.json +1 -1
  204. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  205. package/plugins/pm-codex/package.json +1 -1
  206. package/plugins/pm-codex/plugin.json +1 -1
  207. package/runtime-dependencies.json +1 -1
  208. package/dist/cli-bundle/chunks/chunk-2IZGNOGT.js +0 -6
  209. package/dist/cli-bundle/chunks/chunk-4QQPM3IY.js +0 -2
  210. package/dist/cli-bundle/chunks/chunk-5OFMWP3Q.js +0 -3
  211. package/dist/cli-bundle/chunks/chunk-6HRPGEBF.js +0 -2
  212. package/dist/cli-bundle/chunks/chunk-7ESF676D.js +0 -125
  213. package/dist/cli-bundle/chunks/chunk-7EZZ4W7O.js +0 -20
  214. package/dist/cli-bundle/chunks/chunk-FOYRE23V.js +0 -115
  215. package/dist/cli-bundle/chunks/chunk-HJQ3XPS3.js +0 -31
  216. package/dist/cli-bundle/chunks/chunk-M5D3CEMY.js +0 -9
  217. package/dist/cli-bundle/chunks/chunk-VS565KBX.js +0 -2
  218. package/dist/cli-bundle/chunks/chunk-W4TLA5H3.js +0 -8
  219. package/dist/cli-bundle/chunks/item-transaction-YSAWJRA2.js +0 -2
  220. package/dist/cli-bundle/focused-chunks/chunk-3LRSQXCN.js +0 -2
  221. package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +0 -2
  222. package/dist/cli-bundle/focused-chunks/chunk-FPKVHC3Q.js +0 -2
  223. package/dist/cli-bundle/focused-chunks/chunk-I7XBR2RM.js +0 -91
  224. package/dist/cli-bundle/focused-chunks/chunk-MJP3TFVW.js +0 -2
  225. package/dist/cli-bundle/focused-chunks/chunk-PZSTRYTA.js +0 -102
  226. package/dist/cli-bundle/focused-chunks/chunk-QNJQPJWO.js +0 -44
  227. package/dist/cli-bundle/focused-chunks/chunk-SIPDQBJI.js +0 -8
  228. package/dist/cli-bundle/focused-chunks/chunk-SJE3PYPI.js +0 -3
  229. package/dist/cli-bundle/focused-chunks/chunk-TNKI6WKG.js +0 -66
  230. package/dist/cli-bundle/focused-chunks/chunk-TRCXANRR.js +0 -12
  231. package/dist/cli-bundle/focused-chunks/item-transaction-54VSTT6L.js +0 -2
  232. package/dist/sdk/agent/refusal-closure.js +0 -2
  233. package/dist/sdk/agent/refusal-reachability.js +0 -4
  234. package/dist/sdk/agent/task-transcript-contracts.js +0 -2
  235. package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
  236. package/dist/sdk/authoring.js +0 -2
  237. package/dist/sdk/compose.js +0 -2
  238. package/dist/sdk/contracts.js +0 -2
  239. package/dist/sdk/core-governance.js +0 -2
  240. package/dist/sdk/core.js +0 -2
  241. package/dist/sdk/corpus-shape.js +0 -2
  242. package/dist/sdk/define.js +0 -2
  243. package/dist/sdk/environment/agent-environment.js +0 -2
  244. package/dist/sdk/governance/artifact-ledgers.js +0 -2
  245. package/dist/sdk/governance/coverage-assurance.js +0 -2
  246. package/dist/sdk/governance/reliability.js +0 -2
  247. package/dist/sdk/governance.js +0 -2
  248. package/dist/sdk/graph/adapter.js +0 -2
  249. package/dist/sdk/graph/conformance.js +0 -2
  250. package/dist/sdk/graph/index.js +0 -2
  251. package/dist/sdk/graph.js +0 -2
  252. package/dist/sdk/index.js +0 -2
  253. package/dist/sdk/query.js +0 -2
  254. package/dist/sdk/relationship-migration.js +0 -2
  255. package/dist/sdk/testing.js +0 -8
  256. package/dist/sdk/workspace-recipe.js +0 -2
  257. package/docs/AGENT_PROVENANCE_ADR.md +0 -206
  258. package/docs/DEFECT_RECURRENCE.md +0 -257
  259. package/docs/MCP_2026_07_28_CONFORMANCE.md +0 -41
  260. package/docs/PERFORMANCE.md +0 -189
  261. package/docs/QUALITY_EVIDENCE.md +0 -130
  262. package/docs/generated/FLAG_LEXICON_BUDGETS.md +0 -117
  263. package/docs/performance/cli-transport-overhead.md +0 -51
  264. package/docs/performance/runner-qualification.md +0 -36
  265. package/docs/performance/sdk-entrypoint-import-costs.md +0 -32
@@ -0,0 +1,78 @@
1
+ import{h as om,j as am}from"./chunk-IWOXAUDU.js";import{c as Nt,d as Cn,e as Tn,f as $n,g as nm,j as im}from"./chunk-RQ252B6V.js";import{a as tm}from"./chunk-3V53UBHN.js";import{K as Ku,v as ee,z as ja}from"./chunk-324AHXJO.js";import{a as ga,c as li,d as ui,e as cl,g as dl,h as wa,i as ll,j as fn,k as hn,l as ul,m as ml,n as va,o as gl,p as _n,q as gn,r as yl,s as wl,t as ba}from"./chunk-ML3JHCC6.js";import{a as Ma}from"./chunk-SVOOGGAK.js";import{H as tu,I as Ci,J as nu,K as Aa,M as ru,N as iu,P as ou,Q as au,R as Ti,_ as $i}from"./chunk-RKQNVYGF.js";import{K as rm}from"./chunk-2ZD7275J.js";import{G as Ha,w as Zu,y as em}from"./chunk-4KTFKSS3.js";import{a as Fa,b as Qu}from"./chunk-OPGOOP25.js";import{$a as Pa,A as mr,Aa as fr,B as cu,C as du,Ca as $a,D as pr,Ga as Ou,Ha as Du,Hb as Gu,Ia as Pu,Ja as Lu,Jb as Bu,Ka as Fi,M as lu,Ma as Nu,Na as Mu,Oa as ju,Pa as Kt,Pb as Ju,Qa as Fu,Qb as Vu,R as uu,Ra as In,Sa as Hu,Ta as Oa,Ua as Rn,Va as Uu,Wa as zu,Xa as Wu,Ya as Da,Za as qu,_a as An,a as il,ab as La,b as pn,ba as mu,c as ya,ca as pu,d as ol,da as fu,e as al,f as mt,g as mi,ga as Pi,h as sl,i as $t,rb as Na,v as Oi,xa as Ni,ya as vu,z as su,za as Ta}from"./chunk-RE7ZWT7D.js";import{d as hr,f as Hi,m as Yu,p as Xu}from"./chunk-HDEKFSOK.js";import{E as Mi,G as Cu,H as ge,I as ye,J as Tu,K as ji,L as ft,M as ht,Q as $u,R as _t,b as ln,e as Di,g as hu,n as bu,o as ku,q as Eu,r as Su,s as Lt,t as xu,u as Iu,y as Ru,z as Au}from"./chunk-3XSWH6QC.js";import{a as ne,b as kn,c as _u,d as Ca,e as En,f as Sn,g as xn,j as gu,k as yu,n as qe,r as wu,s as T,t as Li,y as re}from"./chunk-BRZV7BFV.js";import{$ as Ze,$f as We,Aa as un,Ae as Pt,Af as xi,Bd as Dt,Ca as Bd,Cc as we,Cd as Al,Ce as Ue,Da as ut,Db as el,Dc as ka,Dd as Cl,De as xa,Eb as tl,Fa as Jd,Fc as C,Fe as wn,Ff as Kl,Ga as A,Gc as bl,Ge as wi,Ha as ma,Hc as yn,He as pt,Hf as Ii,Ia as Ae,Ic as Ot,Id as Tl,Ie as ve,If as Yl,Jc as Jt,Jd as $l,Je as dr,Jf as Xl,Ka as di,Ke as Hl,La as Vd,Ld as Ol,Le as Ul,Lf as Zl,Ma as pa,Mb as nl,Mc as fi,Md as Dl,Me as zl,Na as fa,Nb as Bt,Nc as K,Nd as oe,Ne as Wl,Oa as ha,Oe as ql,Pe as vi,Q as Hd,Qa as Kd,Qe as Vt,Ra as Yd,Re as bi,T as Ud,Tf as F,Ua as Xd,V as ua,Vc as kl,Wb as _a,Xb as rl,Xe as Gl,Xf as Y,Yb as mn,Ye as lr,Ze as vn,_ as he,_b as et,_e as ze,a as Od,aa as zd,ac as tt,bf as bn,bg as Ql,ca as X,cb as Zd,cc as de,cf as ki,cg as Ri,d as Dd,dc as pl,df as Bl,e as Pd,ec as fl,ef as Ei,fa as Wd,fc as De,fd as hi,gd as cr,gf as Jl,hc as Ce,hd as El,hg as eu,ic as nt,id as _i,if as Si,jd as Sl,lb as Qd,ld as gi,mc as _e,md as yi,nc as hl,ng as Ai,o as la,oc as pi,od as xl,oe as W,pa as qd,pe as Pl,pf as Ia,qa as Gd,qc as _l,qf as Ra,ra as z,re as Ll,rf as Vl,sd as Il,se as Nl,td as Rl,te as He,ue as Ml,ve as jl,wa as sr,wd as Pe,we as Ea,xa as M,xe as Fl,ya as Qe,ye as Sa,za as ci,zc as vl,zf as ur}from"./chunk-UWS3FC4D.js";import{a as Ui,b as _r}from"./chunk-EGN2HFRU.js";import{A as _,B as ar,C as O,D as Xe,E as j,F as B,I as Q,a as oi,d as ai,p as Ld,r as Nd,t as Md,v as jd,w as si,x as Fd,y as Tt,z as g}from"./chunk-3IRCYJI5.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]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var P=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Se=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},rt=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function On(e){try{return await e()}catch(t){throw t instanceof P?new _(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Ua(e){try{return await e()}catch(t){throw t instanceof Se?new _(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as tv}from"node:crypto";import nv 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]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var Dn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eaede7d4-43ae-5551-915e-19befefc29d0")}catch{}})();var cm=1,Yt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],za=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],rv=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],iv=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,zi=30,Wi=5e3,dm=4,ov=50;function gt(e,t){if(!iv.test(e))throw new P(`${t} must be a stable lowercase id`)}function av(e,t){if(!Number.isFinite(e)||e<0)throw new P(`${t} must be a finite non-negative number`)}function gr(e){let t=rv.filter(i=>e[i]!==void 0);if(t.length!==1)throw new P(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function qa(e,t){return A(e)===A(t)}function lm(e,t){if(t.polarity==="equals")return qa(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function um(e){let t=gr(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>lm(r.observed,t)===(r.expected==="pass"))}function sv(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!qa(e.value,t.value)}function cv(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||A(e.scope)!==A(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return sv(gr(e),gr(t))||n[t.enforcement]<n[e.enforcement]||r}function dv(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new P("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new P("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new P("items source equals/state requires field")}function lv(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new P("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new P("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new P("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new P("dependency_kind source source_kind_state must be present or missing")}function uv(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new P("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new P("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new P("prose_edge_gap exemption selectors must not be empty")}}function Ga(e){gt(e.id,"measurement.id"),e.max_cost!==void 0&&av(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new P(`measurement.source.kind must be one of ${za.join(", ")}`);let n=Reflect.get(t,"kind");if(!za.includes(n))throw new P(`measurement.source.kind must be one of ${za.join(", ")}`);let r=t;if(r.kind==="items"&&dv(r),r.kind==="dependency_kind"&&lv(r),r.kind==="prose_edge_gap"&&uv(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new P(`${r.kind} source requires field`);return r.kind==="provider"&&(gt(r.provider,"provider source provider"),gt(r.key,"provider source key")),e}function Ba(e){if(gt(e.id,"assertion.id"),gt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new P("assertion.owner_item_id is required");let t=gr(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new P(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new P("retired assertion requires retire_reason");e.scope.kind==="filter"&&gt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new P("assertion negative control requires pass and fail cases");if(!um(e))throw new P(`assertion ${e.id} negative control does not prove its bound`);return e}function mv(e){if(!Array.isArray(e.allowed_providers))throw new P("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)gt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new P("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Yt.includes(t))throw new P(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new P(`gate provider policy trigger ${t} is invalid`)}}function mm(e){if(gt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new P("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new P("gate requires at least one assertion");for(let t of e.assertion_ids)gt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new P(`gate.triggers is required and must be an array of ${Yt.join(", ")}`);if(e.triggers.length===0)throw new P("gate requires at least one trigger");for(let t of e.triggers)if(!Yt.includes(t))throw new P(`gate trigger must be one of ${Yt.join(", ")}`);return e.provider_policy&&mv(e.provider_policy),e}function Pn(e){if(e.version!==cm)throw new P(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Ga(r),t.has(`measurement:${r.id}`))throw new P(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(Ba(r),t.has(`assertion:${r.id}`))throw new P(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){mm(r);let i=r.assertion_ids.filter(o=>!e.assertions.some(a=>a.id===o));if(i.length>0)throw new P(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new P(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of pm(e))if(!n.has(r))throw new P(`${i.join(", ")} references missing measurement ${r}`);return e}function Ja(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)Ja(n,t)}function pm(e){let t=new Map,n=(r,i)=>{let o=t.get(r)??[];o.push(i),t.set(r,o)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];Ja(r.source.expression,i);for(let o of i)n(o,`derived measurement ${r.id}`)}return t}function pv(e,t){let n=e.assertion_ids.flatMap(o=>{let a=t.assertions.find(s=>s.id===o);return[a.measurement_id,...a.scope.kind==="filter"?[a.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let o=n.pop();if(r.has(o))continue;r.add(o);let a=t.measurements.find(s=>s.id===o);a.source.kind==="provider"?i.add(a.source.provider):a.source.kind==="derived"&&Ja(a.source.expression,n)}return i}function yr(){return{version:cm,measurements:[],assertions:[],gates:[]}}function fv(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let o=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?o:!o}return qa(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function hv(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function _v(e,t){let n=[],r=ua(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let o of i.dependencies??[]){let a=ua(o.kind)??o.kind.trim().toLowerCase(),s=o.source_kind?.trim();a===r&&hv(e,s)&&n.push(`${i.id}->${o.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function gv(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let o=Reflect.get(i,"text");typeof o=="string"&&t.push(o)}}}return t}function yv(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function Wa(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function wv(e){let t=new Map,n=new Set,r=[],i=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,o=0;for(let a of e){t.set(a.id.toLowerCase(),a.id);for(let s of a.dependencies??[])n.add(Wa(a.id,s.id));for(let s of[a.parent,a.blocked_by])typeof s=="string"&&n.add(Wa(a.id,s));for(let s of gv(a)){let c=[...s.matchAll(i)].map(d=>d[0]);o+=c.length,r.push({holder_id:a.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:o}}function vv(e,t){let n=wv(t.items),r=new Map;for(let a of n.prose_mentions){let s=a.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==a.holder_id),c=[...new Set(s)];for(let d of c){let l=Wa(a.holder_id,d);if(n.linked_pairs.has(l)||yv(e.exemptions??[],a.holder_id,d,a.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${a.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],o=i.map(a=>a.contributor).sort();return{value:o.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:o.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(a=>a.explicit).length,implicit_subject:i.filter(a=>!a.explicit).length}}}function bv(e,t){return{value:t.history.filter(n=>(e.op===void 0||n.op===e.op)&&(e.author===void 0||n.author===e.author)&&(e.harness===void 0||n.agent_harness===e.harness)&&(e.model===void 0||n.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function kv(e,t){let n=t.items.filter(r=>{let i=r[e.link],o=Array.isArray(i)&&i.length>0;return e.state==="present"?o:!o});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Ev(e,t){let n=e.source;return n.kind==="items"?fv(n,t):n.kind==="dependency_kind"?_v(n,t):n.kind==="prose_edge_gap"?vv(n,t):n.kind==="history"?bv(n,t):n.kind==="links"?kv(n,t):null}function fm(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function Sv(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function hm(e,t,n){let r=new Array(e.length),i=0,o=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let a=i;i+=1,r[a]=await n(e[a],a)}});return await Promise.all(o),r}async function _m(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let a=n.find(d=>d.id===e.measurement);if(!a)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await gm(a,t,n,r,i);if(typeof s.value!="number")throw new TypeError(`derived measurement ${a.id} is not numeric`);let c=i.charged.has(a.id)?[]:[s.cost];return i.charged.add(a.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let o=await hm(e.operands,dm,a=>_m(a,t,n,r,i));return{value:Sv(e.operator,o.map(a=>a.value)),costs:o.flatMap(a=>a.costs),population_size:Math.max(0,...o.map(a=>a.population_size)),contributors:[...new Set(o.flatMap(a=>a.contributors))]}}async function xv(e,t,n,r,i){Ga(e);let o=Date.now(),a,s=[],c=0;if(e.source.kind==="derived"){let u=await _m(e.source.expression,t,n,[...r,e.id],i);a={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Ev(e,t);u!==null?a=u:(a=await t.external(e.source),c=1)}let d={units:a.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-o},l=fm([...s,d],Date.now()-o);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Se(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${tv("sha256").update(A(e)).digest("hex")}`,value:a.value,population_size:a.population_size,cost:l,contributors:a.contributors??[],...a.partitions?{partitions:a.partitions}:{}}}function gm(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let o=i.cache.get(e.id);if(o)return o;let a=xv(e,t,n,r,i).catch(s=>{if(s instanceof rt&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new rt(s.message,c);throw d.cause=s,d}throw s});return i.cache.set(e.id,a),a}async function Va(e,t,n=[e]){return gm(e,t,n,[],{cache:new Map,charged:new Set})}function Iv(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity,e-t.value)}function Rv(e,t,n={}){Ba(e);let r=gr(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:Iv(t.value,r),verdict:i?"retired":lm(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:um(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Av(e,t,n,r){let i=pv(e,t);if(i.size===0)return;let o=e.provider_policy,a=o?.triggers[r];if(!o||!a)throw new Se(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let s=new Set(o.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!s.has(d))throw new Se(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Se(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[a.max_cost_class])throw new Se(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!a.allow_network)throw new Se(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function sm(e,t,n,r,i){try{return await Va(n,r,i)}catch(o){if(o instanceof rt){let a=o.check?` check ${o.check}`:"",s=o.measurement_id??n.id,c=new Se(`assurance gate ${e} assertion ${t} measurement ${s} source ${o.source_kind}${a} field ${o.field} could not resolve: ${o.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}});throw c.cause=o,c}throw o}}async function ym(e,t,n,r){Pn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new Se(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new Se(`assurance gate ${e} does not declare trigger ${r.trigger}`);Av(i,t,n,r.trigger);let o=await hm(i.assertion_ids,dm,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(v=>v.id===p),y=await sm(i.id,d.id,h,n,t.measurements),w=new Set(y.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return Rv(d,await sm(i.id,d.id,l,u,t.measurements),{owner_terminal:f})}),a=o.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=o.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:a?"block":s?"warn":"pass",exit_code:a?1:0,assertions:o,assertions_total:o.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:fm(o.map(c=>c.cost),Math.max(0,...o.map(c=>c.cost.duration_ms)))}}function qi(e){return nv.join(e,"assurance.json")}async function wm(e){let t=await B(qi(e));return t===null?yr():Gi(t)}function Gi(e){try{return Pn(JSON.parse(e))}catch(t){throw new _("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function Bi(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Cv(e,t){e==="measurement"?Ga(t):e==="assertion"?Ba(t):mm(t)}async function wr(e,t){let n=structuredClone(Bi(await wm(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function vm(e,t,n){let r=Bi(await wm(e),t).find(i=>i.id===n);if(!r)throw new Se(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Ji(e,t,n,r={}){Cv(t,n);let i=await T(e),o=W(r.author,i.author_default),a=await Sn({pmRoot:e,filePath:qi(e),op:`assurance:${t}:put`,author:o,message:r.message,lockTtlSeconds:zi,lockWaitMs:Wi,mutate:s=>{let c=s===null?yr():Gi(s),d=Bi(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&cv(d[l],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new P(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),Pn(c),{raw:`${JSON.stringify(c,null,2)}
2
+ `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...a.result,changed:a.changed}}async function Ka(e,t,n={}){let r=yr();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),Pn(r);let i=await T(e),o=W(n.author,i.author_default),a=await Sn({pmRoot:e,filePath:qi(e),op:"assurance:bundle:apply",author:o,message:n.message,lockTtlSeconds:zi,lockWaitMs:Wi,mutate:s=>{let c=s===null?yr():Gi(s),d=[],l=[],u=(m,f,p)=>{for(let h of f){let y=m.find(w=>w.id===h.id);if(!y){m.push(structuredClone(h)),d.push(`${p}:${h.id}`);continue}if(A(y)!==A(h))throw new P(`assurance bundle refuses to replace divergent ${p} ${h.id}`);l.push(`${p}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),Pn(c),{raw:`${JSON.stringify(c,null,2)}
3
+ `,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...a.result,changed:a.changed}}async function bm(e,t,n,r={}){let i=await T(e),o=W(r.author,i.author_default),a=await Sn({pmRoot:e,filePath:qi(e),op:`assurance:${t}:remove`,author:o,message:r.message,lockTtlSeconds:zi,lockWaitMs:Wi,mutate:s=>{let c=s===null?yr():Gi(s);if(t==="measurement"){let u=pm(c).get(n);if(u&&u.length>0)throw new P(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new P(`assurance assertion ${n} is referenced by gate`);let d=Bi(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new P(`assurance ${t} ${n} not found`);return d.splice(l,1),Pn(c),{raw:`${JSON.stringify(c,null,2)}
4
+ `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...a.result,changed:a.changed}}async function km(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await T(e);await En({pmRoot:e,op:"assurance:gate:verdict",author:W(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:zi,lockWaitMs:Wi})}async function Em(e,t={}){let n=t.limit??ov;if(!Number.isInteger(n)||n<1||n>Dn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${Dn}`);return(await He(kn(e),ne)).reverse().filter(r=>r.op==="assurance:gate:verdict").map(r=>r.context?.assurance_verdict).filter(r=>typeof r=="object"&&r!==null&&"gate_id"in r).filter(r=>t.gate_id===void 0||r.gate_id===t.gate_id).slice(0,n)}import{AsyncLocalStorage as Tv}from"node:async_hooks";import Sm 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]="c8fb265a-c747-5387-8504-adfa325b14d5")}catch{}})();var xm=new Tv;function Im(e,t){return xm.run({...e,pmRoot:Sm.resolve(e.pmRoot)},t)}function TP(e,t){let n=xm.getStore();return n!==void 0&&n.pmRoot===Sm.resolve(e)&&n.transactionId===t?n.step:void 0}import{mkdir as $v,readFile as Ov}from"node:fs/promises";import Am from"node:path";import{createHash as Dv}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f100554a-d0e9-54c1-9dca-7ea5b79b0dc2")}catch{}})();var Ya=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Cm="sdk-workspace-transaction",Tm=/^[a-zA-Z0-9._-]+$/,$m=30,Om=3e3;function ts(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Tm.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Xa(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function ns(e){return{pmRoot:Xa(e.pmRoot,"Transaction pmRoot"),transactionId:ts(e.transactionId,"Transaction id"),author:Xa(e.author,"Transaction author")}}function Ki(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function Dm(e,t){return Am.join(e,"transactions","sdk",`${t}.json`)}async function it(e,t){t.updatedAt=C();let n=Dm(e,t.transactionId);await $v(Am.dirname(n),{recursive:!0}),await Q(n,`${JSON.stringify(t,null,2)}
5
+ `)}function Pv(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"&&Lv(e)}function Lv(e){let t=e.abandonment;return t===void 0?e.schemaVersion===1&&e.status!=="abandoned":e.schemaVersion!==2||t===null||typeof t!="object"||e.status==="committed"?!1:typeof t.reason=="string"&&t.reason.trim().length>0&&typeof t.author=="string"&&t.author.trim().length>0&&(t.supersededBy===void 0||typeof t.supersededBy=="string"&&Tm.test(t.supersededBy)&&t.supersededBy!==e.transactionId)}function Xt(e){return Object.assign(Object.create(null),e)}function Pm(e,t){try{let n=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function Za(e,t){return e===void 0?void 0:Pm(e,t)}function Qa(e,t,n,r){let i=Za(n,r);i===void 0?delete e[t]:e[t]=i}function Rm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function es(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Nv(e,t){if(!es(e.startedStepIds,t)||!es(e.completedStepIds,t)||!Rm(e.results)||!Rm(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,o=new Set(i);return Object.keys(e.compensationData).some(a=>!r.has(a))||Object.keys(e.results).some(a=>!o.has(a))?!1:e.status==="committed"?t.every(a=>o.has(a)):!["compensated","abandoned"].includes(e.status??"")||o.size===0&&r.size===0}function Vi(e,t){return new _(`Workspace transaction ${e} journal is invalid (${t})`,g.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function Lm(e){return new _(`Workspace transaction ${e} journal does not match the supplied plan`,g.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function Mv(e,t,n){return n===void 0||e.abandonment!==void 0||e.status==="compensated"||t.length===n.length&&t.every((r,i)=>r===n[i])}function jv(e,t,n){let r;try{r=JSON.parse(e)}catch{throw Vi(t,"invalid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw Vi(t,"expected an object");let i=r;if(!((i.schemaVersion===1||i.schemaVersion===2)&&i.transactionId===t))throw Vi(t,"schema version or transaction id does not match the journal file");let o=i.stepIds;if(!Array.isArray(o)||!es(o,o)||!Nv(i,o)||!Pv(i)||typeof i.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(i.status))throw Vi(t,"invalid lifecycle, metadata, status or step ids");if(!Mv(i,o,n))throw Lm(t);return{...i,results:Xt(i.results),compensationData:Xt(i.compensationData)}}async function Fv(e,t,n,r,i){let o=i,a=o!==void 0;if(o?.status==="compensating"&&await rs(e,o),o===void 0||o.status==="compensated"){let s=C();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:Xt(),compensationData:Xt(),...e.recoveryData===void 0?{}:{recoveryData:Pm(e.recoveryData,"Transaction recovery data")}},await it(e.pmRoot,o),await yt(e,o,"prepared")}return{journal:o,recovered:a}}async function Hv(e,t,n){try{await Uv(t,e.steps),await it(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let o of e.steps){if(r.has(o.id))continue;let a=await o.inspect(),s=Za(a.result,`Step ${o.id} result`);if(a.state!=="applied"){let c=await o.prepareCompensation?.();Qa(t.compensationData,o.id,c,`Step ${o.id} compensation data`),i.add(o.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await it(e.pmRoot,t);let d=await o.apply();s=Za(d,`Step ${o.id} result`)}await yt(e,t,"step_applied",o.id),r.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),Qa(t.results,o.id,s,`Step ${o.id} result`),await it(e.pmRoot,t),await yt(e,t,"step_recorded",o.id)}return await yt(e,t,"committing"),t.status="committed",await it(e.pmRoot,t),await yt(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Xt(t.results)}}catch(r){if(r instanceof Ya||t.status==="committed")throw r;try{await rs(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function Yi(e,t,n){try{return jv(await Ov(Dm(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&j(r))return;throw r}}async function yt(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function Uv(e,t){let n=new Set,r=Xt();for(let i of t){let o=await i.inspect();o.state==="applied"&&(n.add(i.id),Qa(r,i.id,o.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function rs(e,t){t.status="compensating",await it(e.pmRoot,t),await yt(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!r.has(i.id)&&!n.has(i.id))continue;let o;try{let a=(await i.inspect()).state;o=r.has(i.id)&&(a==="applied"||a==="pending"&&i.compensatePending===!0)}catch{o=r.has(i.id)}o&&(await yt(e,t,"step_compensating",i.id),await Im({pmRoot:e.pmRoot,transactionId:t.transactionId,step:i},()=>i.compensate(t.compensationData[i.id]))),n.delete(i.id),r.delete(i.id),t.completedStepIds=e.steps.map(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>r.has(a)),delete t.results[i.id],delete t.compensationData[i.id],await it(e.pmRoot,t),await yt(e,t,"step_compensated",i.id)}t.status="compensated",await it(e.pmRoot,t),await yt(e,t,"compensated")}async function Nm(e){let{pmRoot:t,transactionId:n,author:r}=ns(e),i=Ki(e.lockTtlSeconds,$m,"Transaction lock TTL"),o=Ki(e.lockWaitMs,Om,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(l=>{let u=ts(l.id,"Transaction step id");if(u!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return u});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:a,lockTtlSeconds:i,lockWaitMs:o},d=await oe(t,Cm,i,r,!1,!1,o);try{let l=await Yi(t,n,s);if(l?.status==="abandoned"||l?.abandonment!==void 0)throw Mm(l);let u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Xt(l.results)};let m=await Fv(c,n,r,s,l);return await Hv(c,m.journal,u||m.recovered)}finally{await d()}}function Mm(e){let t=e.status!=="abandoned",n=e.abandonment.supersededBy,r=n===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(e.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(n)} to finish retirement of ${JSON.stringify(e.transactionId)}.`;return new _(t?`Transaction ${e.transactionId} retirement is incomplete`:`Transaction ${e.transactionId} has been abandoned`,g.CONFLICT,{code:"transaction_abandoned",required:t?r:"Use a new transactionId for the replacement plan.",why:t?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...t?{retirement:{state:"pending",superseded_by:n??null},nextSteps:[r]}:{}})}async function WP(e,t){let n=ns({pmRoot:e,transactionId:t,author:"reader"});return Yi(n.pmRoot,n.transactionId)}function zv(e){return Dv("sha256").update(JSON.stringify(e.stepIds)).digest("hex")}async function qP(e){let t=ns(e),n=Xa(e.reason,"Abandonment reason"),r=e.supersededBy===void 0?void 0:ts(e.supersededBy,"Replacement transaction id");if(r===t.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");let i=Ki(e.lockTtlSeconds,$m,"Transaction lock TTL"),o=Ki(e.lockWaitMs,Om,"Transaction lock wait"),a=await oe(t.pmRoot,Cm,i,t.author,!1,!1,o);try{let s=await Yi(t.pmRoot,t.transactionId);if(s===void 0)throw new _(`Transaction ${t.transactionId} was not found`,g.NOT_FOUND);if(s.status==="committed")throw new _(`Transaction ${t.transactionId} is committed and cannot be abandoned`,g.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(s.abandonment!==void 0&&s.abandonment.supersededBy!==r)throw Mm(s);if(s.status==="abandoned")return s;let c=e.resolveSteps(structuredClone(s));if(JSON.stringify(c.map(d=>d.id))!==JSON.stringify(s.stepIds))throw Lm(t.transactionId);if(s.abandonment===void 0){if(r!==void 0&&await Yi(t.pmRoot,r)!==void 0)throw new _(`Replacement transaction ${r} already exists`,g.CONFLICT);s.schemaVersion=2,s.abandonment={reason:n,author:t.author,...r===void 0?{}:{supersededBy:r}},await it(t.pmRoot,s)}return s.status!=="compensated"&&await rs({...e,...t,steps:c},s),await Wv(s,t.pmRoot,i,o),s.status="abandoned",await it(t.pmRoot,s),s}finally{await a()}}async function Wv(e,t,n,r){let i=zv(e);if((await He(kn(t),ne)).some(a=>a.op==="transaction_abandon"&&a.context?.transaction_id===e.transactionId&&a.context?.attempt===e.attempt&&a.context?.plan_digest===i))return;let o=e.abandonment;await En({pmRoot:t,author:o.author,lockTtlSeconds:n,lockWaitMs:r,op:"transaction_abandon",message:o.reason,context:{transaction_id:e.transactionId,attempt:e.attempt,plan_digest:i,...o.supersededBy===void 0?{}:{superseded_by:o.supersededBy}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var vr={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Xi={type:"array",minItems:1,maxItems:pa,items:vr},jm={...Xi,items:{...vr,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},qv={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Xi])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:vr,id:vr}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:jm}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Xi}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:jm,authors:Xi}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:pa,items:{type:"array",minItems:2,maxItems:2,items:vr}}}}]}}},JP={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:Vd,items:qv}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function Fm(e,t,n,r){let i=await Lt(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Hm(i,t,n,r)}function Gv(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Hm(e,t,n=5,r=!1){let i=[],o=new Map,a=e.policies.filter(y=>y.rule.kind==="require_fields"),s=a.filter(y=>y.subject?.operations===void 0),c=new Set,d=0,l=0,u=0,m=0,f=0,p=Xd(e);for(let y of t){let w=p({operation:"",author:"",before:y,after:y,completeness_only:!0});d+=+(w.decisions.length>0),l+=w.decisions.length,w.decisions.forEach(E=>c.add(E.policy_id));let v=w.decisions.filter(E=>!E.satisfied);if(v.length===0)continue;m+=1;let k=o.get(y.type)??{items:0,violations:0,missing_fields:0};k.items+=1;for(let E of v)u+=1,k.violations+=1,k.missing_fields+=E.missing_fields.length,E.effect==="refuse"&&(f+=1),i.length<n&&i.push({id:y.id,type:y.type,status:y.status,decision:E});o.set(y.type,k)}let h=r||f>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:h,ok:h==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:a.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:l,governed_items:d,ungoverned_items:t.length-d,contract_status:Gv(a.length,t.length,d),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:u,refused_violations:f,missing_by_type:Object.fromEntries(o),violations:i,violations_truncated:i.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}import Bv 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]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function Jv(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function Wm(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new _("Policy definition must be valid JSON.",g.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new _("Policy definition must be an object.",g.USAGE);return t}async function Vv(e,t){let n=M(process.cwd(),e.path);await re(n);let r=await T(n);return{pmRoot:n,settings:r,author:W(t,r.author_default)}}function Um(e,t,n,r){if(e==="policy-mode")return ha({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let o=fa(r.definition),a=ha({...n,policies:[...i,o].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(a,null,2)}
6
+ `)>Eu)throw new _("Policy registry exceeds its byte ceiling.",g.USAGE);return a}async function zm(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:Um(e,t,await Lt(r.pmRoot),n)};let i=await Sn({pmRoot:r.pmRoot,filePath:Bv.join(r.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:r.author,message:n.message,lockTtlSeconds:r.settings.locks.ttl_seconds,lockWaitMs:r.settings.locks.wait_ms,mutate(o){let a=Um(e,t,Su(o),n);return{raw:`${JSON.stringify(a,null,2)}
7
+ `,result:a}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function Kv(e,t,n){let r,i=await $u({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(o){let a=(await Lt(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!a||a.rule.kind!=="approval")throw new _("--policy must name an approval rule.",g.USAGE);if(!a.rule.authors.includes(n.author))throw new _("This actor is not a declared approver.",g.CONFLICT);return await xu(n.pmRoot,o.metadata.id),r={policy_id:a.id,policy_fingerprint:Kd(a),content_fingerprint:Yd(a,{...o.metadata,body:o.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...r,warnings:i.warnings}}}function Yv(e,t){let n=Wm(t),r=fa({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==r.id)throw new _("Policy id operand does not match definition.id.",g.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return r}async function pL(e,t,n={},r={}){if(!di.includes(e))throw new _("Unknown workflow policy action.",g.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:Jv()};let i=await Vv(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Lt(i.pmRoot)};if(e==="policy-put"){let l=Yv(t,n.definition);return zm(e,l.id,{...n,definition:l},i)}if(!t?.trim())throw new _(`schema ${e} requires an operand.`,g.USAGE);if(["policy-remove","policy-mode"].includes(e))return zm(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new _("Use policy-check to preview; policy-approve records an approval.",g.USAGE);return Kv(t,n,i)}let o=z(i.settings,F()),a=await ge(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,o.type_to_folder);if(!a)throw new _(`Item ${t} not found.`,g.NOT_FOUND);let{document:s}=await ye(a,{schema:i.settings.schema}),c={...s.metadata,body:s.body},d=n.definition===void 0?c:{...c,...Wm(n.definition)};if(d.id!==c.id)throw new _("Policy preview cannot change the item id.",g.USAGE);return{policy_result:!0,action:e,changed:!1,result:await Iu(i.pmRoot,await Lt(i.pmRoot),{operation:"update",author:i.author,before:c,after:d,completeness_only:n.definition===void 0})}}import{createHash as Gm}from"node:crypto";import br from"node:fs/promises";import kr 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]="69bf315a-01aa-56d9-bd56-196d6792dea2")}catch{}})();function Le(e,t){throw new _(e,g.USAGE,t)}var Xv="2026-07-15T06:22:12.276Z",Zv=Date.parse(Xv),Qv=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],qm=e=>typeof e=="string"?e:"",Bm=e=>{let t=e??{},n=qm(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(qm(t.ts))>=Zv);return Qv[r][i]};function Jm(e,t,n=20,r=new Set,i=!1){let o=[],a=[],s={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}d+=1;let h=Bm(p);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}s[h]+=1,i&&h==="actionable_unknown"&&a.push({item_id:e,line:m+1}),o.length<c&&o.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:s.legacy_unknown,actionable_unknown_event_count:s.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:s.legacy_unknown+s.actionable_unknown>o.length,actionable_events:a}}var xL=(e,t,n=20,r=new Set)=>Jm(e,t,n,r);function Vm(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let o of i.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Er=async(e,t=20,n=!1)=>{let r=kr.join(e,"history"),i;try{i=(await br.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let o=new Set,a=[],s=[],c=0,d=0,l=0,u=0,m=0,f=0,p="_workspace.jsonl",h=new Set;if(i.includes(p))try{h=Vm(await br.readFile(kr.join(r,p),"utf8"))}catch{h=new Set}for(let w of i){let v;try{v=await br.readFile(kr.join(r,w),"utf8")}catch{continue}let k=w.slice(0,-6),E=Jm(k,v,t-a.length,h,n);c+=1,d+=E.checked_events,l+=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&&o.add(k),a.push(...E.samples),n&&s.push(...E.actionable_events)}let y=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...o].sort((w,v)=>w.localeCompare(v)),samples:a,samples_truncated:y>a.length,...n?{actionable_events:s}:{}}};function eb(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function tb(e){try{return Vm(await br.readFile(kr.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function nb(e){return(e.item_id===ne||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function rb(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Le(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Bm(i)!=="actionable_unknown"&&Le(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:Gm("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Km(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Le("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Le("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Le("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let o=eb(t.all_actionable===!0?(await Er(e,0,!0)).actionable_events:r),a=await tb(e),s=new Map;for(let m of o)if(nb(m)||Le(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!s.has(m.item_id))try{s.set(m.item_id,(await br.readFile(kr.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Le(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=o.map(m=>rb(m,a,s.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Gm("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function IL(e,t,n=50){return(await Km(e,t,n)).plan}function ib(e,t){let n=e.length>0;return n&&t&&Le("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&&Le("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:ob(e),all_actionable:t}}function ob(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),o=r===ne||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!o||!Number.isSafeInteger(i)||i<1)&&Le(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function RL(e,t){let n=ib(Ku(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return ab(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:ee(t,"planFingerprint")??ee(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:ee(t,"attributedAuthor")??ee(t,"attributed_author")??void 0,reviewer:ee(t,"reviewer"),reason:ee(t,"reason")})}async function ab(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",o=await Km(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:g.SUCCESS,plan:o.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Le("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Le("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==o.plan.plan_fingerprint)throw new _("Author acknowledgment selection changed after preview; no history was mutated.",g.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let a=o.completeCoordinates.filter(({disposition:l})=>o.plan.selection.kind==="events"||l==="actionable").map(({item_id:l,line:u})=>({item_id:l,line:u}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:g.NO_EFFECT,plan:o.plan};let s=await T(e),c=await En({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:r}},message:i,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms}),d=o.plan.actionable_count>0&&o.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:g.PARTIAL_EFFECT}:{outcome:"effect",exit_code:g.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...d,plan:o.plan,history_path:c.historyPath}}import{execFile as sb}from"node:child_process";import Ym 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]="15749905-177d-5ae0-b475-668733f41e8a")}catch{}})();function Xm(e,t){return new Promise((n,r)=>{sb("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,o)=>{i?r(i):n(o)})})}function Zm(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function OL(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Zm(n),!n)throw new RangeError("Source line range must use start:end.");return n}function cb(e){let t=new Map;for(let n of e.split(`
8
+ `)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function db(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let o=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((a,s)=>a.localeCompare(s));n.set(i,o)}return n}async function lb(e){let t=Ym.relative(e.workspaceRoot,Ym.resolve(e.workspaceRoot,e.sourcePath)),n=await Xm(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Xm(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:cb(n),commitItems:db(r),available:!0}}function ub(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let o=i.source===t,a=o?i.target:i.source;if((e.visitedDepth.get(a)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(a,n);let s=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,a],kinds:[...e.current.kinds,o?i.kind:s.inverse??i.kind]};e.details.get(a)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function mb(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let o=t.shift(),a=o.kinds.length;i!==void 0&&a>=i||a>=e.maxDepth||(i=ub({current:o,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((o,a)=>o.nodes.join("\0").localeCompare(a.nodes.join("\0"))),r}function pb(e,t,n){let r=Xu(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=mb({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(s=>[s.id,s]))}),o=i[0];if(!o)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let a=[...new Set(i.map(s=>s.nodes.at(-1)))];return{status:a.length===1?"found":"ambiguous",nodes:o.nodes,kinds:o.kinds,alternative_decision_ids:a.slice(1)}}async function fb(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await lb({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function hb(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function _b(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Qm(e){Zm(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await fb(e),r=_b(n),i=new Map;for(let o of e.candidates){let a=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(o.item.id)),s=a.reduce((l,[,u])=>l+u,0),c=pb(o.item.id,e.corpus,t),d=hb({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:s,decisionStatus:c.status});i.set(o.item.id,{score:s*100+o.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(o.item.updated_at))/(720*60*60*1e3))),contribution_lines:s,evidence:[...o.files.map(l=>({kind:"linked_file",reference:l.path})),...a.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:o.item.value?.trim()||null,why_now:o.item.why_now?.trim()||null,outcome:o.item.outcome?.trim()||null,objective:o.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth: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]="bee6d15d-ca4a-538c-bb70-fd3dc7e2a8ec")}catch{}})();var Sr=["software-delivery","research","agent-evaluation","operations"];function ep(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function Zi(e,t,n,r,i){let o=`preset-${e}`,a=i.map(c=>({id:`${o}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),s=a.map(c=>ep(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:a,assertions:s,gates:[{id:`${o}-readiness`,description:n,assertion_ids:s.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Qi(e,t){return e==="software-delivery"?Zi(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Zi(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Zi(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Zi(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function tp(e,t,n,r={}){return Ka(e,Qi(t,n).declarations,r)}async function np(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(i=>!n.has(i.status))};return await Promise.all(["files","tests","docs"].map(async i=>{let o={id:`derived-active-missing-${i}`,description:`Observed active items missing ${i} evidence.`,source:{kind:"links",link:i,state:"missing"}},a=(await Va(o,r)).value,s=ep(`${o.id}-ceiling`,o.id,t,a,"observe"),c=`active-missing-${i}`;return{id:c,population_size:r.items.length,scope:{kind:"active"},observed:a,declarations:{measurements:[o],assertions:[s],gates:[{id:`derived-${c}`,description:`Observe the accepted ${i} evidence baseline.`,assertion_ids:[s.id],triggers:["ci","scheduled"]}]}}}))}function rp(e,t,n={}){return Ka(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function ip(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return Ji(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import sp from"node:fs/promises";import{createRequire as gb}from"node:module";import Te 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]="32adaa7c-f0aa-5aff-8d88-d7c0ccfbd971")}catch{}})();function op(e,t){let n=Te.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Te.sep}`)&&!Te.isAbsolute(n))return n.split(Te.sep).join("/");let r=Te.resolve(e),i=0xcbf29ce484222325n;for(let o=0;o<r.length;o+=1)i^=BigInt(r.charCodeAt(o)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Te.basename(Te.dirname(e))}/package.json`}function yb(e){return e.includes(`${Te.sep}.pnpm${Te.sep}`)?"pnpm":e.includes(`${Te.sep}node_modules${Te.sep}`)?"npm":"other"}async function ap(e){try{let t=JSON.parse(await sp.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function is(e){try{return await sp.realpath(e)}catch{return Te.resolve(e)}}async function cp(e,t,n=Ze(import.meta.url,["../../.."])){let r=await is(t),i=await is(Te.join(n,"package.json")),o=await ap(i),a=new Map;o!==void 0&&a.set(i,{version:o,path:op(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=gb(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await is(l),m=await ap(u);if(m===void 0)continue;let f=u,p=a.get(f);if(p){p.consumers.includes(d.name)||(p.consumers.push(d.name),p.consumers.sort((h,y)=>h.localeCompare(y)));continue}a.set(f,{version:m,path:op(u,r),layout:yb(u),consumers:[d.name]})}catch{}let s=[...a.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=o===void 0?[]:s.filter(d=>d.version!==o);return{host_version:o??null,copies:s,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${o}:${d.version}:${d.consumers.join("+")}`)}}import os from"node:fs/promises";import as from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="069e2e60-11d9-5a37-a966-9073944d32a2")}catch{}})();var dp=8388608,wb=new Set(["resolved","failed"]),vb=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ss(e){return vb.find(t=>t.matches(e))?.kind}function cs(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let o=ot(i.agent_provenance)?i.agent_provenance:void 0;if(o===void 0||!Bl(i).ok)return i;let a={},s=!1;for(let[d,l]of Object.entries(o)){let u=ot(l)?ss(l.value):void 0;if(u===void 0){a[d]=l;continue}s=!0,r+=1;let m=i.agent_harness??"unknown",f=`${m}\0${d}\0${u}`,p=t.get(f)??{harness:m,dimension:d,kind:u,count:0};p.count+=1,t.set(f,p)}if(!s)return i;n+=1;let c={...i};return Object.keys(a).length===0?delete c.agent_provenance:c.agent_provenance=a,Ei(i,c,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((i,o)=>i.harness.localeCompare(o.harness)||i.dimension.localeCompare(o.dimension)||i.kind.localeCompare(o.kind))}}}async function lp(e){let t=[];for(let n of await up(e)??[])try{let r=await os.readFile(as.join(e,"history",n),"utf8");for(let i of r.split(`
9
+ `)){if(i.trim().length===0)continue;let o=mp(i);if(!(o===null||!ot(o.agent_provenance))&&Object.values(o.agent_provenance).some(a=>ot(a)&&ss(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function up(e){try{return(await os.readdir(as.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function bb(e,t,n){let r;try{r=await os.open(as.join(e,"history",t),"r");let i=(await r.stat()).size,o=Math.min(i,Math.max(0,n)),a=Buffer.alloc(o),{bytesRead:s}=await r.read(a,0,o,0),c=a.subarray(0,s).toString("utf8"),d=s>=i,l=c.lastIndexOf(`
10
+ `),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:s,complete:d}}catch{return null}finally{await r?.close()}}function mp(e){try{let t=JSON.parse(e);return ot(t)?t:null}catch{return null}}function kb(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=ot(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([a,s])=>{if(!ot(s))return;let c=ss(s.value);if(!c)return;let d=`${r}\0${a}\0${c}`,l=n.get(d)??{harness:r,dimension:a,kind:c,count:0};l.count+=1,n.set(d,l)}),!ot(e.context))return;let o=e.context.agent_provenance_outcomes;ot(o)&&Object.entries(o).forEach(([a,s])=>{if(!ot(s)||typeof s.resolver!="string"||!wb.has(String(s.status)))return;let c=`${r}\0${a}\0${s.resolver}`,d=t.get(c)??{harness:r,dimension:a,resolver:s.resolver,attempts:0,successes:0};d.attempts+=1,s.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function Eb(e,t,n,r,i,o){let a=i;for(let s of e.split(`
11
+ `)){if(s.trim().length===0)continue;if(a>=r)return{eventsRead:a,truncated:!0};a+=1;let c=mp(s);if(c===null){o.malformed_events+=1;continue}if(typeof c.ts=="string"&&Ot(c.ts)){let d=new Date(c.ts).toISOString();(o.earliest_event_at===null||d<o.earliest_event_at)&&(o.earliest_event_at=d),(o.latest_event_at===null||d>o.latest_event_at)&&(o.latest_event_at=d)}kb(c,t,n)}return{eventsRead:a,truncated:!1}}function Sb(e,t,n){return n?[...e.filter(r=>r.attempts>0&&r.successes===0).map(r=>`provenance_resolver_zero_success:${r.harness}:${r.dimension}:${r.resolver}:${String(r.attempts)}`),...t.map(r=>`provenance_value_domain_invalid:${r.harness}:${r.dimension}:${r.kind}:${String(r.count)}`)]:[]}async function pp(e,t=1e4){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("Provenance event limit must be a non-negative safe integer.");let n={scope:"history_prefix",event_limit:t,byte_limit:dp,bytes_read:0,events_read:0,truncated:!1,unreadable_sources:0,malformed_events:0,earliest_event_at:null,latest_event_at:null,complete:!1},r=new Map,i=new Map,o=0,a=0,s=!1,c=await up(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await bb(e,u,Math.max(0,dp-a));if(m===null){n.unreadable_sources+=1;continue}a+=m.bytesRead;let f=Eb(m.content,r,i,t,o,n);if(o=f.eventsRead,f.truncated){s=!0;break}if(!m.complete){s=!0;break}}let d=[...r.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.resolver.localeCompare(m.resolver)),l=[...i.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.kind.localeCompare(m.kind));return n.bytes_read=a,n.events_read=o,n.truncated=s,n.complete=!s&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:d,sample:n,invalid_values:l,warnings:Sb(d,l,n.complete),events_read:o,truncated: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]="c3200eea-d2c8-5813-87e8-df765f7b6c7a")}catch{}})();var fp=25;function xb(e,t,n=[]){let r=["list","--status",e,...n],i=["--assignee-filter","unassigned"],o=["--updated-before",`-${t}h`];return{unowned:K([...r,...i]),idle:K([...r,...o]),stale:K([...r,...i,...o])}}function hp(e,t){let n=e.items.length>fp;return{count:e.count,items:e.items.slice(0,fp),...n?{truncated:!0}:{},sweep:t}}function _p(e,t,n=[]){let r=xb(t.in_progress,e.threshold_hours,n),i=(a,...s)=>`pm ${a} <id>${[...s,...n].map(c=>` ${fi(c)}`).join("")}`,o=[...e.unowned.count>0?[`in_progress_unowned:${e.unowned.count}`]:[],...e.idle.count>0?[`in_progress_idle:${e.idle.count}`]:[]];return{warnings:o,details:o.length===0?void 0:{threshold_hours:e.threshold_hours,threshold_setting:"mutation_guard.stale_in_progress_hours",unowned:hp(e.unowned,r.unowned),idle:hp(e.idle,r.idle),item_remedies:{claim:i("claim"),take_over_idle:i("claim","--takeover-stale"),return_to_open:i("update","--status",t.open)}},remediation:{stale_in_progress_items:r.stale,in_progress_unowned:r.unowned,in_progress_idle:r.idle}}}import Ib from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="be6f35e2-0762-5188-b373-bdc7d7302d1c")}catch{}})();function ds(e){if(!e.itemDocument||e.force)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author)return[];let n=kl(t),r=qe(e.settings);if(r.ownership_enforcement==="strict")throw new _(`Item ${e.subjectId} is assigned to ${n}. Use --force to override.`,g.CONFLICT);return r.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${n}`]:[]}async function gp(e){if(!Ra(e.pmRoot))return;let t=await ge(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),n=t===null?Tt:(await ye(t,{schema:e.settings.schema}).catch(()=>null))?.document;n!==void 0&&ur(e.pmRoot,n,e.subject.id)}async function Rb(e){let t=await B(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw await gp(e),new _(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);let n=await ge(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?e.readItem?await e.readItem(n):await ye(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw await gp(e),new _(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function eo(e){let t=e.writeHistoryRaw??Q;try{await t(e.historyPath,e.nextHistoryRaw),await lr(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await Ib.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await lr(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function yp(e){let t=[...ds({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await oe(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let r=await Rb({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation}),i=Tt;if(ur(e.pmRoot,r.loadedItemUnderLock?.document??i,e.subject.id),await e.applyRewrite(r),Ra(e.pmRoot)){let o=await ge(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),a=o===null?i:(await ye(o,{schema:e.settings.schema})).document;xi(e.pmRoot,a,e.subject.id)}return e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await 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]="0676366f-63e6-502f-8505-b58bdb20377a")}catch{}})();function Ab(e,t,n){if(n.raw===null)throw new _(`No history stream exists for ${e}.`,g.NOT_FOUND);if(n.entries.length===0)throw new _(`No history entries exist for ${e}; nothing to ${t.slice(8)}.`,g.USAGE)}async function ls(e){let{subject:t,settings:n,operation:r,options:i}=e,o=await Pl(t.historyPath,t.id),a=o.entries.length===0&&t.located!==null?e.reseed:void 0;a===void 0&&Ab(t.id,r,o);let s=t.located?await ye(t.located,{schema:n.schema}):null,c=W(i.author,n.author_default),d={raw:o.raw??"",entries:o.entries,verification:dr(o.entries),loadedItem:s,author:c},l=await(a===void 0?e.transform(d):a(d,{absent:o.raw===null})),u=dr(l.rewrittenEntries);if(!u.ok)throw new _(`${r} produced an invalid rewritten chain (${u.errors.join(", ")}).`,g.GENERIC_FAILURE);let m=l.changed&&!i.dryRun?await yp({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:o.raw,currentItemRawBeforeLock:s?.raw??null,operation:r,author:c,force:i.force,itemDocument:s?.document??null,applyRewrite:async f=>{await l.beforeWrite?.(),l.applyRewrite?await l.applyRewrite(f):await eo({historyPath:t.historyPath,nextHistoryRaw:Vt(l.rewrittenEntries),historyRawUnderLock:f.historyRawUnderLock})},applyPostRewrite:l.afterWrite??(async()=>Y({path:t.historyPath,scope:"project",op:`${r.replace("-","_")}:history`}))}):[];return l.report({verification:u,warnings:m})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d8f1968e-a030-5a3c-b766-60a409163745")}catch{}})();function to(e,t,n=25){let r=e.definitions.filter(a=>a.roles.length===0).map(a=>a.id).sort((a,s)=>a.localeCompare(s)),i=new Set(r),o=t.filter(a=>{let s=hl(a.status,e);return s!==void 0&&i.has(s)}).map(a=>a.id).sort((a,s)=>a.localeCompare(s));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:o.length,affected_item_ids:o.slice(0,n),affected_item_ids_truncated:o.length>n}}function no(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b5c9f97-33fb-5318-8bec-3aa033ef7c25")}catch{}})();var vp=8,us=100;function bp(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Ge(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function Cb(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function xr(e,t){let n=Ge(e,t);return{...n,sample:n.sample.map(r=>Cb(r))}}function q(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function Tb(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var $b={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:q(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:q(e.missing_required,t),missing_optional:q(e.missing_optional,t),missing:q(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:q(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:xr(e.discovered,t),effective:xr(e.effective,t),loaded:xr(e.loaded,t),failed:Ge(e.failed,t),warnings:q(e.warnings,t),activation:{failed:Ge(n.failed,t),warnings:q(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:Tb(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Ge(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:q(n.affected_item_ids,t),samples:Ge(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:q(e.item_unreadable,t),item_conflict_markers:Ge(e.item_conflict_markers,t),item_parse_failures:q(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:q(n.tracked_paths,t)},history_unreadable:q(e.history_unreadable,t),history_conflict_markers:Ge(e.history_conflict_markers,t),history_invalid_json:Ge(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:q(n.candidate_items,t),confirmed_items:q(n.confirmed_items,t),resolved_false_positive_items:q(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:q(e.drifted_items,t),merge_receipt_attributed_items:q(e.merge_receipt_attributed_items,t),missing_streams:q(e.missing_streams,t),unreadable_streams:q(e.unreadable_streams,t),hash_mismatches:q(e.hash_mismatches,t),chain_mismatches:q(e.chain_mismatches,t),version_skews:q(e.version_skews,t),workspace_state_mismatches:q(e.workspace_state_mismatches,t),workspace_state_missing:q(e.workspace_state_missing,t),workspace_state_unreadable:q(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:q(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:q(e.stale_items_after,t),skipped:e.skipped})};function ms(e,t){let n=$b[e.name];return n?n(e.details,t):e.details}function kp(e){return{disabled_by_flag:e.details.disabled_by_flag,loaded_count:Array.isArray(e.details.loaded)?e.details.loaded.length:0,failed_count:0,warning_count:0,restore_with:"pm health --full"}}function Ob(e){if(e.name==="extensions"&&e.status==="ok")return kp(e);let t=ms(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function ps(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(r=>n.has(r.warning))}function Db(e){let t=q(e.warnings,8);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:Ob(n)})),warnings:t.sample,findings:ps(e,t.sample),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8},generated_at:e.generated_at}}function wp(e){return e.details.skipped===!0}function Pb(e){let t=q(e.warnings,8),n=e.checks.filter(wp).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!wp(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:ps(e,t.sample),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8,omitted_checks:n},generated_at:e.generated_at}}function Lb(e,t,n){return n?Pb(e):t.brief===!0?Db(e):t.full===!0?e:{...e,checks:e.checks.map(r=>r.name==="extensions"&&r.status==="ok"?{...r,details:kp(r)}:r),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function fs(e,t,n){let r=e.warning_count??e.warnings.length,i=e.warnings.slice(0,100),o={...e,warning_count:r,warning_limit:100,warnings_truncated:r>100,warnings:i,findings:ps(e,i)},a=Lb(o,t,n);return{...a,warning_count:r,warning_limit:100,warnings_truncated:r>a.warnings.length,...a.projection?{projection:{...a.projection,warning_count:r,warnings_truncated:r>a.warnings.length}}:{}}}import _s from"node:fs/promises";import le from"node:path";import Nb from"node:readline/promises";import{stdin as Mb,stdout as ro}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bb8a4985-8bc0-5290-a6f9-310d940cf4d7")}catch{}})();var E1=["ask","add","skip","status"],jb=["AGENTS.md","CLAUDE.md"],Fb=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Hb=8,gs=1,Ub="<!-- pm-cli:agent-guidance:start:",zb=`<!-- pm-cli:agent-guidance:start:v${gs} -->`,hs="<!-- pm-cli:agent-guidance:end -->",Rr="Add workflow guidance later: pm init --agent-guidance add";var Wb=()=>Nb.createInterface({input:Mb,output:ro});function Ln(e,t){let n=le.relative(e,t);return n.length===0?le.basename(t):n.split(le.sep).join("/")}function Ep(e){return e.endsWith(`
12
+ `)?e:`${e}
13
+ `}function qb(e){return e.includes(`\r
14
+ `)?`\r
15
+ `:`
16
+ `}function Sp(e){let t=e.indexOf(Ub);if(t===-1)return null;let n=e.indexOf(hs,t);return n===-1?null:{start_index:t,end_index:n+hs.length}}function Gb(e){return Sp(e)!==null}function Bb(e,t="<your project test command>"){return[zb,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and start: `pm claim <id> --start`, or `pm claim --next --start` to take the next available item in one write.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",hs,""].join(e)}function xp(e,t="<your project test command>"){let n=qb(e),r=Bb(n,t),i=Sp(e);if(i){let s=e.slice(i.end_index),c=s.startsWith(`\r
17
+ `)?s.slice(2):s.startsWith(`
18
+ `)?s.slice(1):s,d=Ep(`${e.slice(0,i.start_index)}${r}${c}`);return{next_content:d,changed:d!==e}}let o=e.length===0?"":e.endsWith(`
19
+ `)?`
20
+ `:`
21
+
22
+ `,a=Ep(`${e}${o}${r}`);return{next_content:a,changed:a!==e}}async function Ip(e){if(await O(le.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await _s.readFile(le.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=Jb(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await O(le.join(e,"pnpm-lock.yaml"))?"pnpm test":await O(le.join(e,"bun.lock"))||await O(le.join(e,"bun.lockb"))?"bun run test":await O(le.join(e,"yarn.lock"))?"yarn test":"npm test"}function Jb(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function Vb(e,t){let n=le.dirname(e);return le.basename(e)==="pm"&&le.basename(n)===".agents"?le.dirname(n):le.resolve(t,e)}function Kb(e,t){let n=e.find(i=>le.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let r=e.find(i=>i.exists);return r?r.file_path:le.join(t,"AGENTS.md")}function Yb(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function Xb(e){let t=Wb();try{ro.write(`
23
+ Agent guidance check
24
+ `),ro.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
25
+ `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return ro.write(`
26
+ `),Yb(n,!0)}finally{t.close()}}function Rp(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:gs,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function Ap(e){let t=[],n=await Ip(e);for(let r of jb){let i=le.join(e,r),o=await O(i);if(!o){t.push({file_path:i,exists:o,has_guidance:!1,has_marker:!1});continue}let a=await _s.readFile(i,"utf8"),s=a.toLowerCase(),c=Fb.filter(l=>s.includes(l)),d=Gb(a);t.push({file_path:i,exists:o,has_guidance:d||c.length>=Hb,has_marker:d,outdated:d&&xp(a,n).changed})}return t}function Zt(e,t){e.includes(t)||e.push(t)}function Zb(e,t){let n=Rp(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function Cp(e,t=le.dirname(e)){let n=await O(e)?await _s.readFile(e,"utf8"):"",r=xp(n,await Ip(t));return r.changed?(await Q(e,r.next_content),{changed:!0,warnings:await Y({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function Qb(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Ln(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Ln(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Ln(e.projectRoot,t.file_path))}}async function ek(e,t,n){return e?await Ap(n):t}function Ir(e,t,n){e.state={...e.state,...n,template_version:gs,last_checked_files:t}}async function Tp(e,t){if(t.presentBefore)return;let n=await Cp(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function tk(e,t){t||(e.warnings.push("agent_guidance:missing"),Zt(e.nextSteps,Rr))}function nk(e,t){e.skipped=!0,Ir(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Zt(e.nextSteps,Rr)}async function rk(e,t){await Tp(e,t),Ir(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function ik(e,t){e.state.declined&&Ir(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function ok(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Zt(e.nextSteps,Rr)}async function ak(e,t){if(e.prompted=!0,await Xb(t.targetRelativePath)){await Tp(e,t),Ir(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,Ir(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Zt(e.nextSteps,Rr)}function sk(e){e.warnings.push("agent_guidance:missing_non_interactive"),Zt(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Zt(e.nextSteps,Rr)}async function ck(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(tk(n,t.presentBefore),n):t.mode==="skip"?(nk(n,t.checkedFiles),n):t.mode==="add"?(await rk(n,t),n):t.presentBefore?(ik(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(ok(n),n):t.interactive?(await ak(n,t),n):(sk(n),n)}async function $p(e){let t=Vb(e.pm_root,e.cwd),n=await Ap(t),r=Kb(n,t),i=Ln(t,r),o=n.map(l=>Ln(t,l.file_path)),a=n.some(l=>l.has_guidance),s=await ck(Rp(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:i,checkedFiles:o,presentBefore:a,projectRoot:t});if(e.mode==="add")for(let l of n.filter(u=>u.outdated)){let u=await Cp(l.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=Zb(e.settings,s.state);n=await ek(s.applied,n,t);let d=n.filter(l=>l.outdated).map(l=>Ln(t,l.file_path));return d.length>0&&(s.warnings.push(`agent_guidance_outdated:${d.join(",")}`),Zt(s.nextSteps,"pm init --agent-guidance add")),{summary:Qb({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a8289336-e833-5617-9a32-0a21f28f294e")}catch{}})();function Ar(e){let t=/^extension_(disabled_)?pm_(min|max)_version_([a-z_]+):(project|global):([^:]+):(.+)$/u.exec(e);if(!t)return;let[,n,r,i,o,a,s]=t,c=s.split(":")[0].replace(r==="min"?"required=":"allowed=",""),d=i==="invalid"?`a valid pm_${r}_version instead of ${c}`:`pm ${r==="min"?">=":"<="} ${c}`;return n?`Package ${a} is disabled and requires ${d} before activation. After satisfying the bound, run ${K(["package","activate",a,`--${o}`])}.`:`Package ${a} requires ${d}. Use a compatible host or package version, or keep it disabled with ${K(["package","deactivate",a,`--${o}`])}.`}import It from"node:fs/promises";import me from"node:path";import Cr from"node:fs/promises";import{createHash as dk}from"node:crypto";import Dp 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]="a535e1be-f99b-5898-af76-0c9d5b8a681d")}catch{}})();var ys=new Set([void 0,...vl]),Pp=13,lk="history-drift-cache.json";function Lp(e){return Dp.join(e,"runtime",lk)}async function uk(e){try{let t=await Cr.readFile(Lp(e),"utf8"),n=JSON.parse(t);return n.version!==Pp||n.history_item_hash_version!==vn||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!ys.has(r.hash_algorithm)||!ze.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&ze.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}function Np(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function Mp(e){let t=[...new Set([...e.missingStreams,...e.unreadableStreams,...e.hashMismatches,...e.chainMismatches,...e.versionSkews,...e.workspaceStateMismatches.length>0||e.workspaceStateMissing.length>0||e.workspaceStateUnreadable.length>0?[ne]:[]])].sort((n,r)=>n.localeCompare(r));return{...e,driftedItems:t}}async function mk(e,t,n,r,i){let o=kn(e),a;try{a=await Cr.stat(o)}catch(d){return j(d)||i.unreadableStreams.push(ne),!1}let s=i.missingStreams.length,c=await jp({itemId:ne,historyPath:o,stat:a,cached:t[ne],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(ne),c.verification.chainOk||i.chainMismatches.push(ne),n[ne]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion,hash_algorithm:c.verification.hashAlgorithm},c.cacheDirty):(i.missingStreams.splice(s),c.cacheDirty)}function pk(e){return!ys.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!ze.includes(e.item_hash_version)||ki(e)}async function fk(e){let t=await Cr.readFile(e,"utf8"),n=dk("sha256").update(t).digest("hex");if(t.trim().length===0)return null;let r=[],i=null;for(let m of t.split(/\r?\n/)){let f=m.trim();if(f.length===0)continue;let p=JSON.parse(f);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(p),i=p.after_hash}if(!i)return null;let o=ve(r),a=r.some(pk),s=r[r.length-1],c=ys.has(s.hash_algorithm),d=s.item_hash_version,l=d!==void 0&&ze.includes(d),u=l?d:o.item_hash_version;return{latestAfterHash:i,hashAlgorithm:c?we(s.hash_algorithm):void 0,identityDiscontinuities:Ml(r),chainOk:o.ok,versionSkew:a,latestHashComparable:c&&u!==void 0&&(!a||l||d===void 0),contentHash:n,itemHashVersion:u??vn}}function hk(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Op(e,t,n){try{return await fk(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function _k(e,t){return e!==null&&e.contentHash===t.content_hash&&e.latestAfterHash===t.latest_after_hash&&e.chainOk===t.chain_ok&&e.versionSkew===(t.version_skew===!0)&&e.latestHashComparable===t.latest_hash_comparable&&e.itemHashVersion===t.item_hash_version&&e.hashAlgorithm===t.hash_algorithm}async function jp(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(hk(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await Op(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await Op(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!_k(n,e.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&ze.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function Fp(e,t,n,r){let i,o;try{i=ut(e,t.id),o=await Cr.stat(i)}catch(d){return(j(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let a=await jp({itemId:t.id,historyPath:i,stat:o,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!a.verification)return a.cacheDirty;a.verification.identityDiscontinuities.length>0&&(r.identityDiscontinuities??=[]).push(...a.verification.identityDiscontinuities.map(d=>({...d,item_id:t.id}))),a.verification.versionSkew&&r.versionSkews.push(t.id),a.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:a.verification.contentHash,latest_after_hash:a.verification.latestAfterHash,chain_ok:a.verification.chainOk,version_skew:a.verification.versionSkew,latest_hash_comparable:a.verification.latestHashComparable,item_hash_version:a.verification.itemHashVersion,hash_algorithm:a.verification.hashAlgorithm};let{body:s,...c}=t;return a.verification.latestHashComparable&&(Jl({metadata:c,body:s},a.verification.itemHashVersion,a.verification.hashAlgorithm).includes(a.verification.latestAfterHash)||r.hashMismatches.push(t.id)),a.cacheDirty}async function gk(e,t){if(!(t.unreadableStreams.includes(ne)||t.chainMismatches.includes(ne)||t.versionSkews.includes(ne)))try{let n=await _u(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(ne)}}async function Hp(e,t){let n=Np();return await Fp(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),Mp(n)}async function Qt(e,t,n={}){let r=Np(),i=(await uk(e))?.entries??{},o={},a=!1,s=n.cacheHitVerification!=="metadata",c={previousEntries:i,nextEntries:o,verifyCacheHitByContent:s};for(let l of t)await Fp(e,l,c,r)&&(a=!0);let d=await mk(e,i,o,s,r);if(a||=d,await gk(e,r),a||Object.keys(i).length!==Object.keys(o).length){let l=Lp(e);try{await Cr.mkdir(Dp.dirname(l),{recursive:!0}),await Q(l,JSON.stringify({version:Pp,history_item_hash_version:vn,entries:o}))}catch{}}return Mp(r)}import Nn from"node:fs/promises";import Tr 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]="b01042e0-77ae-5e2c-8118-6680f0002d60")}catch{}})();function Up(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:o,ttl_seconds:a}=n;return typeof r!="string"||typeof i!="string"||typeof o!="string"||typeof a!="number"||!Number.isFinite(a)?null:{id:r,owner:i,created_at:o,ttl_seconds:a,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function yk(e,t,n){let r=Up(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let o=n-i,a=Math.floor(o/1e3),s=o>r.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:a,stale:s,reason:s?"expired":"active"}}}async function zp(e,t,n){let r=yk(e,t,n);if(r.detail!=="active")return r;let i=Up(t),o=await $l(i);return o==="unknown"?r:{detail:o==="dead"?"owner_dead":"active",entry:{...r.entry,owner_state:o,pid:i.pid,...o==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}async function wk(e,t,n){let r=await Ol(e,"gc");if(r===null)return!1;try{let i;try{i=await Nn.readFile(e,"utf8")}catch(o){if(j(o))return!0;throw o}if(i!==t)return!1;n&&await Dl(e,t);try{await Nn.unlink(e)}catch(o){if(!j(o))throw o}return!0}finally{await r()}}function vk(e,t,n){t==="owner_dead"&&(e.owner_dead_lock_samples??=[],e.owner_dead_lock_samples.length<20&&e.owner_dead_lock_samples.push(n)),t==="active"?e.active_lock_count+=1:t==="expired"||t==="owner_dead"?e.stale_lock_count+=1:e.unparseable_lock_count+=1}async function Wp(e,t){let n=t??Date.now(),r=Tr.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await Nn.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(a){if(j(a))return i;throw a}for(let a of o){let s;try{s=await Nn.readFile(Tr.join(r,a),"utf8")}catch(l){if(j(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c,entry:d}=await zp(a,s,n);vk(i,c,d)}return i}async function bk(e,t,n,r,i,o,a){if(!t.dryRun){try{if(!await wk(n,o,a.reason==="owner_dead")){e.warnings.push(`lock_changed_or_busy:${i}`),e.retained.push(r),e.entries.push(a);return}}catch{e.warnings.push(`lock_remove_failed:${i}`),e.retained.push(r),e.entries.push(a);return}if(t.hooks?.onWrite){let s=await t.hooks.onWrite(n);e.warnings.push(...s)}}e.removed.push(r),e.entries.push(a)}async function qp(e,t){let{hooks:n}=t,r=t.now??Date.now(),i=Tr.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]};await Tl(e,Tr.join(i,"gc.lock"),"gc");let a;try{a=(await Nn.readdir(i)).filter(s=>s.endsWith(".lock")).sort()}catch(s){if(j(s))return o;throw s}for(let s of a){o.scanned+=1;let c=Tr.join(i,s),d=`locks/${s}`;if(n?.onRead){let m=await n.onRead(c);o.warnings.push(...m)}let l;try{l=await Nn.readFile(c,"utf8")}catch(m){if(j(m)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${s}`),o.retained.push(d),o.entries.push({file:s,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let u=await zp(s,l,r);if(u.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${s}`),o.retained.push(d),o.entries.push(u.entry);continue}if(u.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${s}`),o.retained.push(d),o.entries.push(u.entry);continue}if(u.detail==="active"){o.retained.push(d),o.entries.push(u.entry);continue}await bk(o,t,c,d,s,l,u.entry)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2000c9e7-7cba-5f6f-adea-d980569b4869")}catch{}})();var kk=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:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{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:"merge_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history record; the repair rebuilds the stream as one audited baseline from the on-disk item, and earlier versions stay unrecorded. When the stream was deleted by mistake, restore it from version control first (pm history-repair --all, with or without --append-only, rebuilds every missing stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"The item's history stream cannot be read; preview salvage, which removes lines that cannot hold a record and an invalid tail after a verified prefix, then apply it without --dry-run. Salvage refuses interior corruption, which needs recovery from version control, and a permission error needs the file's access fixed."},{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> --append-only",summary:"The item's history chain is broken; append one record that bridges every break in the stream and keeps every recorded line byte-identical (pm history-repair <id> re-anchors the recorded entries instead). pm health previews the bridge for every chain mismatch, so a break a bridge cannot repair is reported as history_drift_chain_unbridgeable, and a stream no repair can keep as history_drift_unrepairable_stream, instead."},{code:"history_drift_chain_unbridgeable",command:"pm history-repair <id>",summary:"The item's history chain is broken in a way an append-only bridge cannot repair, for example a recorded patch that applies only on top of the unrecorded change (details.repair_refusals names the refusal reason); re-anchor the recorded entries instead (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unrepairable_stream",command:"pm history <id> --verify --full",summary:"Neither history repair can keep this stream (details.repair_refusals names both refusal reasons). Inspect it: a record that no longer matches its seal, or a malformed chain, needs the item's own stream restored from version control or a backup; a stream entry that is a link (reason stream_not_regular_file) needs the item's own stream restored as a regular file. Then run pm history <id> --verify --strict-exit."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{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:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{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_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{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:"Rebuild the history streams of the items without a history record as one audited baseline from each on-disk item."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"Preview salvage of the unreadable history streams, then apply it without --dry-run; interior corruption needs recovery from version control."},{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_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{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 ws(e){if(typeof e!="string")return;let t=e.trim();for(let n of kk)if(t===n.code||t.startsWith(`${n.code}:`))return n}function vs(e){let t={};for(let n of e){let r=ws(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Gp(e){return Object.values(vs(e))}import Jn from"node:fs/promises";import Me from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var Ek=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Mn(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Ii(t.extensionName));for(let y of t.extensionNames??[])n.add(Ii(y));let r=y=>n.size===0||n.has(Ii(y)),i=(y,w)=>Bp(y.filter(v=>r(v.name)).map(w)),o=(y,w)=>Bp(y.filter(v=>r(v.name)).flatMap(w)),{registrations:a,commands:s,parsers:c,preflight:d,services:l,renderers:u,hooks:m}=e,f=o(a.relationship_kinds??[],y=>y.definitions.map(w=>w.kind)),p=u.overrides.filter(y=>r(y.name)&&((y.commands?.length??0)>0||y.resultDiscriminator!==void 0)).map(y=>({format:y.format,commands:[...y.commands??[]],result_discriminator:y.resultDiscriminator!==void 0})).sort((y,w)=>y.format.localeCompare(w.format)),h=i(a.assurance_providers??[],y=>y.definition.id);return{capabilities:Yl(e,t),commands:i(a.commands,y=>y.command),command_overrides:i(s.overrides,y=>y.command),command_handlers:i(s.handlers,y=>y.command),hooks:Ek.filter(([y])=>m[y].some(w=>r(w.name))).map(([,y])=>y),flag_commands:i(a.flags,y=>y.target_command),item_types:o(a.item_types,y=>y.types.map(w=>w.name)),item_fields:o(a.item_fields,y=>y.fields.map(w=>w.name)),...f.length>0?{relationship_kinds:f}:{},migrations:o(a.migrations,y=>typeof y.definition.id=="string"?[y.definition.id]:[]),profiles:i(a.profiles,y=>y.profile.name),importers:i(a.importers,y=>y.importer),exporters:i(a.exporters,y=>y.exporter),search_providers:i(a.search_providers,y=>y.definition.name),vector_store_adapters:i(a.vector_store_adapters,y=>y.definition.name),...h.length>0?{assurance_providers:h}:{},parser_overrides:i(c.overrides,y=>y.command),service_overrides:i(l.overrides,y=>y.service),renderer_overrides:i(u.overrides,y=>y.format),...p.length>0?{renderer_ownership:p}:{},preflight_overrides:d.overrides.filter(y=>r(y.name)).length,preflight_ownership:d.overrides.filter(y=>r(y.name)).map(y=>({commands:[...y.commands??[]]}))}}function Bp(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import Xk from"node:path";import{mkdir as Zk}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var Sk=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function xk(e){let t=Sk.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Ik(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Jp(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=xk(s);if(c===void 0)continue;let d=i.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(s),i.set(c,d)}let o=[];for(let[a,s]of i.entries()){if(s.count<n)continue;let c=Ik(a);o.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:il(c)!==void 0})}return o.sort((a,s)=>s.count-a.count||a.name.localeCompare(s.name)),o}import{createHash as Yp}from"node:crypto";import Fn from"node:fs/promises";import Hn 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]="09d88765-6283-5287-b293-43300251833f")}catch{}})();function wt(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Xp(e){let t=wt(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Zp(e,t){let n=ks(e),r=wt(t,"migrationScope");return`auto-${Yp("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function ks(e){let t=e.kind==="rename-type"?{kind:e.kind,from:wt(e.from,"source"),to:wt(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:de(wt(e.from,"source")),to:de(wt(e.to,"target")),...e.type===void 0?{}:{type:wt(e.type,"type")}}:{kind:e.kind,from:de(wt(e.from,"source")),to:de(wt(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Rk(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Ak(e,t,n){let r=Ce(t.schema),i=Rk(n);return nt(e,r.files[i],De[i])}function Qp(e,t){return Hn.join(e,"transactions","schema",`${t}-plan.json`)}function io(e){return e.length===0?null:JSON.parse(e)}async function jn(e){let t=await B(e);return{exists:t!==null,raw:t??""}}async function ef(e,t){t.exists?await Q(e,t.raw):await Fn.rm(e,{force:!0})}function Ck(e,t,n){let r=mt(e),i=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),o=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return $t(r);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[i],name:t.to})}else i>=0&&r.definitions.splice(i,1);return $t(r)}function Tk(e,t,n){let r=fn(e),i=r.fields.findIndex(a=>a.key===t.from),o=r.fields.findIndex(a=>a.key===t.to);if(n==="stage"){if(o>=0)return hn(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let a=r.fields[i];r.fields.push({...a,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&r.fields.splice(i,1);return hn(r)}function $k(e,t,n){let r=_n(e),i=r.statuses.findIndex(a=>a.id===t.from),o=r.statuses.findIndex(a=>a.id===t.to);if(n==="stage"){if(o>=0)return gn(r);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[i],id:t.to})}else i>=0&&r.statuses.splice(i,1);return gn(r)}function Ok(e,t,n){return t.kind==="rename-type"?Ck(e,t,n):t.kind==="rename-field"?Tk(e,t,n):$k(e,t,n)}function Mt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Es(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Un(e){return Array.isArray(e)?e.map(t=>Es(t)).filter(t=>t!==void 0):[]}function Dk(e,t){for(let n of Un(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>Mt(r,t)));for(let n of Un(e.type_workflows))n.type=Mt(n.type,t)}function Pk(e,t){for(let r of Un(e.definitions))r.default_status=Mt(r.default_status,t);let n=Es(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=Mt(i,t);for(let r of Un(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(o=>Mt(o,t)):i))}function Lk(e,t){for(let n of Un(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>Mt(i,t)));for(let r of["options","command_option_policies"])for(let i of Un(n[r])){let o=r==="options"?"key":"option";i[o]=Mt(i[o],t)}}}function Nk(e,t){let n=Es(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=Mt(n[r],t)}function bs(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?Dk(r,t):t.kind==="rename-field"?Lk(r,t):Pk(r,t),Nk(r,t),`${JSON.stringify(r,null,2)}
27
+ `}function tf(e,t){if(t.kind==="rename-type"){let r=mt(e).definitions;return{source:r.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=fn(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=_n(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function Mk(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function jk(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function nf(e,t){let n=ks(t.request),r=t.migrationId===void 0?Zp(n,t.migrationScope??"plan"):Xp(t.migrationId),i=e.map(c=>jk(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),o=Yp("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),a=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!a.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:o,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function Fk(e){let t=z(e.settings,F()),n=[...new Set(Object.values(t.type_to_folder))],r=await Mi(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},o=r?await Ru({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:i}):null;return o?{items:o.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await ft(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Hk(e,t){let n=await B(Qp(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new _(`Stored schema migration plan "${t}" is invalid: ${Wd(r)}`,g.GENERIC_FAILURE)}}async function Uk(e,t){let n=Qp(e,t.migration_id);await Fn.mkdir(Hn.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await Q(n,`${JSON.stringify(r,null,2)}
28
+ `)}function zk(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Wk(e){let t=await ge(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new _(`Schema migration item "${e.id}" no longer exists.`,g.NOT_FOUND);return(await ye(t,{schema:e.settings.schema})).document.metadata}function Vp(e,t,n){let r=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let o=e.metadata;if(Object.prototype.hasOwnProperty.call(o,i)&&!Object.prototype.hasOwnProperty.call(o,r))return[];if(!Object.prototype.hasOwnProperty.call(o,r)||Object.prototype.hasOwnProperty.call(o,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return o[i]=o[r],delete o[r],[r,i]}function Kp(e){return{id:e.id,inspect:async()=>{let t=await jn(e.filePath),n=tf(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await jn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await jn(e.filePath);return await Q(e.filePath,Ok(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await ef(e.filePath,{exists:t.exists,raw:t.raw})}}}function qk(e){return{id:e.stepId,inspect:async()=>{let t=await jn(e.filePath);return{state:bs(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await jn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await jn(e.filePath);return await Q(e.filePath,bs(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await ef(e.filePath,{exists:t.exists,raw:t.raw})}}}function Gk(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await T(e.pmRoot),n=z(t,F()).type_to_folder,r=await Wk({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=Mk(r,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await T(e.pmRoot),n=z(t,F()).type_to_folder,r=await _t({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:Vp(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await T(e.pmRoot),n=z(t,F()).type_to_folder;await _t({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:Vp(r,e.request,"reverse")}}})}}}async function Bk(e){let t=await Hk(e.pmRoot,e.migrationId);if(t){if(!zk(t.request,e.request))throw new _(`Schema migration id "${e.migrationId}" already belongs to a different request.`,g.CONFLICT);return{plan:t,stored:!0}}let n=await Fk({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...nf(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Jk(e){let t=tf(await B(e.schemaPath)??"",e.request);if(!t.source)throw new _(`Schema migration source "${e.request.from}" is not a custom definition.`,g.NOT_FOUND);if(t.target)throw new _(`Schema migration target "${e.request.to}" already exists.`,g.CONFLICT);await Uk(e.pmRoot,e.plan)}async function Vk(e){let t=Ce(e.settings.schema),n=[...new Set([["types",De.types],["fields",De.fields],["workflows",De.workflows]].map(([i,o])=>nt(e.pmRoot,t.files[i],o)).filter(i=>i!==e.schemaPath))];try{let i=Hn.join(e.pmRoot,"templates"),o=await Fn.readdir(i,{withFileTypes:!0});n.push(...o.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>Hn.join(i,a.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!j(i))throw i}n.sort((i,o)=>i.localeCompare(o));let r=[];for(let i of n){let o=await B(i);o!==null&&bs(o,e.request)!==o&&r.push({filePath:i,beforeRaw:o})}return{paths:n,snapshots:r}}async function Kk(e){for(let t of e.snapshots){let n=await Fn.readFile(t.filePath,"utf8"),r=Hn.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await Ca({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:io(t.beforeRaw),after:io(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function Yk(e,t,n){let r=ks(e),i=M(process.cwd(),n.path);await re(i);let o=t.migrationId===void 0?Zp(r,await Fn.realpath(i)):Xp(t.migrationId),a=await T(i),s=W(t.author,a.author_default),c=await Bk({pmRoot:i,settings:a,migrationId:o,request:r}),d=c.plan;if(t.dryRun===!0)return{...d,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Ak(i,a,r),u=await B(l)??"";c.stored||await Jk({pmRoot:i,schemaPath:l,request:r,plan:d});let m=await Vk({pmRoot:i,schemaPath:l,settings:a,request:r}),f=[Kp({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...m.paths.map((w,v)=>qk({filePath:w,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>Gk({pmRoot:i,id:w.id,request:r,author:s,force:t.force===!0})),Kp({id:"retire-source",filePath:l,request:r,phase:"retire"})],p=await Nm({pmRoot:i,transactionId:`schema-${o}`,author:s,steps:f,lockTtlSeconds:Math.max(a.locks.ttl_seconds,300),lockWaitMs:a.locks.wait_ms}),h=await Fn.readFile(l,"utf8"),{historyPath:y}=await Ca({pmRoot:i,author:s,documentPath:Hn.relative(i,l).replaceAll("\\","/"),before:io(u),after:io(h),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await Kk({pmRoot:i,author:s,settings:a,request:r,plan:d,snapshots:m.snapshots}),{...d,action:r.kind,applied:!0,recovered:p.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:y}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var qN=[...di,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],oo="schema-types",rf="schema-statuses",of="schema-fields";function jt(e){return xn({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function JN(e,t,n){let r=M(process.cwd(),n.path);await vt(r);let i;try{i=ya({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(f){throw new _(f instanceof Error?f.message:String(f),g.USAGE)}let o=await T(r),a=Ce(o.schema),s=nt(r,a.files.types,De.types),c=[],d=W(t.author,o.author_default),l=qe(o),u=await oe(r,oo,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms),m;try{let f=await B(s),p;try{p=mt(f)}catch(h){throw new _(h instanceof Error?h.message:String(h),g.GENERIC_FAILURE)}try{ol(i,p);let h=new Map,y=z(o,F());for(let[w,v]of Object.entries(y.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!h.has(k)&&h.set(k,w)}al(i,p,h)}catch(h){throw new _(h instanceof Error?h.message:String(h),g.USAGE)}m=mi(p,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await jt({pmRoot:r,filePath:s,raw:$t(m.file),op:"schema:add-type",author:d,settings:o}),await $r(r,[m.definition],c,"schema:add-type-folder"),c.push(...await Y({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await af(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Ft(c),generated_at:C()}}async function vt(e){await re(e)}async function af(e,t){try{let n=await nm(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Ft(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Qk(e,t,n,r){let i=z(t,F()),o=r.trim().toLowerCase();return(await ft(e,t.item_format,i.type_to_folder,[],n)).filter(a=>typeof a.type=="string"&&a.type.toLowerCase()===o).length}async function e0(e,t,n,r){let i=z(t,F()),o=_e(n),a=de(r);return(await ft(e,t.item_format,i.type_to_folder,[],n)).filter(s=>{let c=typeof s.status=="string"?s.status:"";return(o.alias_to_id.get(de(c))??de(c))===a}).length}async function t0(e,t,n,r,i){if(i.length===0||va.has(i))return;let o=await e0(t,n,r,i);o>0&&e.push(`items_using_status:${o}`);let a=n0(r.workflow,i);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function n0(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&de(n)===t).map(([n])=>n)}async function VN(e,t,n){let r=M(process.cwd(),n.path);await vt(r);let i=await T(r),o=Ce(i.schema),a=nt(r,o.files.types,De.types),s=[],c=W(t.author,i.author_default),d=qe(i),l=await oe(r,oo,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await B(a),f;try{f=mt(m)}catch(p){throw new _(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=sl(f,e)}catch(p){throw new _(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=(u.definition?.name??e??"").trim();if(p.length>0){let h=await Qk(r,i,o,p);h>0&&s.push(`items_using_type:${h}`)}await jt({pmRoot:r,filePath:a,raw:$t(u.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await Y({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await af(r,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:a,definitions:u.file.definitions.length},warnings:Ft(s),generated_at:C()}}function Ss(e,t){return nt(e,t.files.statuses,De.statuses)}function ao(e,t){return nt(e,t.files.fields,De.fields)}function sf(e,t){return nt(e,t.files.types,De.types)}async function $r(e,t,n,r){for(let i of t){let o=Gd(i.folder??qd(i.name)),a=Xk.join(e,o);await O(a)||(await Zk(a,{recursive:!0}),n.push(...await Y({path:a,scope:"project",op:r})))}}function xs(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function r0(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function i0(e){let t=new Map;for(let n of e){let r=de(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let o=de(i);o.length>0&&!t.has(o)&&t.set(o,r)}}}return t}async function KN(e,t,n){let r=M(process.cwd(),n.path);await vt(r);let i;try{i=gl({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(h){throw new _(h instanceof Error?h.message:String(h),g.USAGE)}let o=await T(r),a=Ce(o.schema),s=Ss(r,a),c=_e(a);try{ba(i,c.alias_to_id)}catch(h){throw new _(h instanceof Error?h.message:String(h),g.USAGE)}let d=r0(c.by_id.get(i.id));if((i.roles??d?.roles??[]).length===0)throw new _(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,g.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${pn(i.id)}" --role active`,`pm schema add-status "${pn(i.id)}" --role blocked`]});let l=[],u=W(t.author,o.author_default),m=qe(o),f=await oe(r,rf,o.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,o.locks.wait_ms),p;try{let h=await B(s),y;try{y=_n(h)}catch(v){throw new _(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=i0(y.statuses);try{ba(i,w)}catch(v){throw new _(v instanceof Error?v.message:String(v),g.USAGE)}p=yl(y,i,d),await jt({pmRoot:r,filePath:s,raw:gn(p.file),op:"schema:add-status",author:u,settings:o}),l.push(...await Y({path:s,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:p.replaced,status:p.definition,file:{path:s,statuses:p.file.statuses.length},warnings:Ft(l),generated_at:C()}}async function YN(e,t,n){let r=M(process.cwd(),n.path);await vt(r);let i=await T(r),o=Ce(i.schema),a=Ss(r,o),s=[],c=W(t.author,i.author_default),d=qe(i),l=await oe(r,rf,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await B(a),f;try{f=_n(m)}catch(p){throw new _(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=wl(f,e)}catch(p){throw new _(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=de(u.definition?.id??e);await t0(s,r,i,o,p),await jt({pmRoot:r,filePath:a,raw:gn(u.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await Y({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:a,statuses:u.file.statuses.length},warnings:Ft(s),generated_at:C()}}function cf(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function o0(e,t,n){return{...cf(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function df(e){return{id:e.id,source:va.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function lf(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function a0(){let e=new Map,t=F();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let i of r){if(typeof i!="object"||i===null||Array.isArray(i))continue;let o=i.name;typeof o=="string"&&o.trim().length>0&&e.set(o.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function s0(e){let t=_e(e),n=[],r=[];for(let i of t.definitions){let o=df(i);o.source==="builtin"?n.push(o):r.push(o)}return{builtin:n,custom:r}}async function Or(e){let t=M(process.cwd(),e.path);await vt(t);let n=await T(t),r=Ce(n.schema),i=nt(t,r.files.types,De.types),o=Ss(t,r),a=z(n,F()),s=a0(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:i,statusesPath:o,byType:a.by_type,customNames:c,extensionProvenance:s,schema:r}}async function XN(e){let t=await Or(e),n=[],r=[],i=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=lf(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=cf(s);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let o=s0(t.schema),a=pi(t.schema).definitions.map(xs);return{action:"list",builtin:n,custom:r,extension:i,counts:{builtin:n.length,custom:r.length,extension:i.length,total:n.length+r.length+i.length},statuses:{builtin:o.builtin,custom:o.custom,counts:{builtin:o.builtin.length,custom:o.custom.length,total:o.builtin.length+o.custom.length}},fields:{custom:a,counts:{total:a.length}},file:{path:t.typesPath},generated_at:C()}}async function ZN(e,t){let n=(e??"").trim();if(n.length===0)throw new _("Type name must not be empty.",g.USAGE);let r=await Or(t),i=Object.values(r.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!i)throw new _(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${pn(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:o0(i,lf(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:C()}}async function QN(e,t){let n=de(e);if(n.length===0)throw new _("Status id must not be empty.",g.USAGE);let r=await Or(t),i=_e(r.schema),o=i.alias_to_id.get(n)??n,a=i.by_id.get(o);if(!a)throw new _(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${pn(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:df(a),file:{path:r.statusesPath},generated_at:C()}}async function eM(e,t,n){let r=M(process.cwd(),n.path);await vt(r);let i;try{i=ll({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(p){throw new _(p instanceof Error?p.message:String(p),g.USAGE)}let o=await T(r),a=Ce(o.schema),s=ao(r,a),c=[],d=$i(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=W(t.author,o.author_default),u=qe(o),m=await oe(r,of,o.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,o.locks.wait_ms),f;try{let p=await B(s),h;try{h=fn(p)}catch(y){throw new _(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}f=ul(h,i),await jt({pmRoot:r,filePath:s,raw:hn(f.file),op:"schema:add-field",author:l,settings:o}),c.push(...await Y({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:s,fields:f.file.fields.length},warnings:Ft(c),generated_at:C()}}async function c0(e,t,n,r){let i=z(t,F());return(await ft(e,t.item_format,i.type_to_folder,[],n)).filter(o=>{let a=o[r];return a==null?!1:Array.isArray(a)?a.length>0:typeof a=="string"?a.trim().length>0:!0}).length}async function tM(e,t,n){let r=M(process.cwd(),n.path);await vt(r);let i=await T(r),o=Ce(i.schema),a=ao(r,o),s=[],c=W(t.author,i.author_default),d=qe(i),l=await oe(r,of,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await B(a),f;try{f=fn(m)}catch(p){throw new _(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=ml(f,e)}catch(p){throw new _(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=de(u.definition?.key??e),h=de(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(h.length>0){let y=await c0(r,i,o,h);y>0&&s.push(`items_using_field:${y}`)}await jt({pmRoot:r,filePath:a,raw:hn(u.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await Y({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:a,fields:u.file.fields.length},warnings:Ft(s),generated_at:C()}}async function nM(e){let t=await Or(e),n=pi(t.schema).definitions.map(xs);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:ao(t.pmRoot,t.schema)},generated_at:C()}}async function rM(e,t){let n=de(e);if(n.length===0)throw new _("Field key must not be empty.",g.USAGE);let r=await Or(t),i=pi(r.schema).by_key.get(n);if(!i)throw new _(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${pn(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:xs(i),file:{path:ao(r.pmRoot,r.schema)},generated_at:C()}}async function iM(e,t,n){let r=M(process.cwd(),n.path);await vt(r);let i;try{let h=dl(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${cl.join(", ")}.`);i=h}catch(h){throw new _(h instanceof Error?h.message:String(h),g.USAGE)}let o=await T(r),a=Ce(o.schema),s=sf(r,a),c=[],d=W(t.author,o.author_default),l=qe(o),u=[],m=[],f,p=await oe(r,oo,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms);try{let h=await B(s),y;try{y=mt(h)}catch(v){throw new _(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=y;for(let v of wa(i)){let k=mi(w,v);w=k.file,(k.replaced?m:u).push(k.definition.name)}f=w.definitions.length,await jt({pmRoot:r,filePath:s,raw:$t(w),op:"schema:apply-preset",author:d,settings:o}),await $r(r,wa(i),c,"schema:apply-preset-folder"),c.push(...await Y({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await p()}return{action:"apply-preset",preset:i,registered:u,replaced:m,file:{path:s,definitions:f},warnings:Ft(c),generated_at:C()}}function d0(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new _("--min-count must be a positive integer (>= 1).",g.USAGE);return e}async function oM(e,t){let n=M(process.cwd(),t.path);await vt(n);let r=await T(n),i=Ce(r.schema),o=sf(n,i),a=d0(e.minCount),s=z(r,F()),c=(await ft(n,r.item_format,s.type_to_folder,[],i)).map(v=>typeof v.title=="string"?v.title:""),d=Jp(c,{minCount:a}),l=[],u=[],m=[],f=[],p;if(!e.apply){let v;try{v=mt(await B(o))}catch(k){throw new _(k instanceof Error?k.message:String(k),g.GENERIC_FAILURE)}return p=v.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:d,registered:u,replaced:m,skipped:f,file:{path:o,definitions:p},warnings:l,generated_at:C()}}let h=W(e.author,r.author_default),y=qe(r),w=await oe(n,oo,r.locks.ttl_seconds,h,!!e.force,y.force_required_for_stale_lock,r.locks.wait_ms);try{let v=await B(o),k;try{k=mt(v)}catch(x){throw new _(x instanceof Error?x.message:String(x),g.GENERIC_FAILURE)}let E=k;for(let x of d){if(x.shadows_builtin){f.push({name:x.name,reason:"shadows_builtin"});continue}let $;try{$=ya({name:x.name})}catch{f.push({name:x.name,reason:"invalid_type_token"});continue}let S=mi(E,$);E=S.file,(S.replaced?m:u).push(S.definition.name)}p=E.definitions.length,await jt({pmRoot:n,filePath:o,raw:$t(E),op:"schema:infer-types",author:h,settings:r}),await $r(n,E.definitions.filter(x=>u.includes(x.name)||m.includes(x.name)),l,"schema:infer-types-folder"),l.push(...await Y({path:o,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:a,candidates:d,registered:u,replaced:m,skipped:f,file:{path:o,definitions:p},warnings:Ft(l),generated_at:C()}}import uf from"node:fs/promises";import Is 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]="9cf5a9e7-4a66-5e72-80a2-f8a9b5b6e412")}catch{}})();function $e(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function R(e){return e.trim().toLowerCase()}function so(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let i=t.slice(n,r);if(i.length===0)throw new _("Extension manifest name must resolve to a non-empty directory name.",g.USAGE);if(i==="."||i==="..")throw new _('Extension manifest name must not resolve to "." or "..".',g.USAGE);return i}function Rs(e){return nl(e)}async function l0(e){try{let t=JSON.parse(await uf.readFile(Is.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(r=>typeof t.scripts?.[r]=="string")}}catch{return{has_build_script:!1}}}async function u0(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new _(`Extension entry file is missing at "${t}".`,g.USAGE);let r=await l0(n.source_root),i=r.package_name?`pm package install npm:${r.package_name}`:void 0,o=n.source_input??n.source_root;return new _(`Extension entry "${e.entry}" is absent from GitHub source "${o}". pm package install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,g.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm package install ${n.source_root}`]:[`pm package install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm package install npm:<package-name>."],recovery:{attempted_command:`pm install ${o}`,normalized_args:["install",o],...i?{next_best_command:i}:{}}})}async function zn(e,t={}){let n=Is.join(e,"manifest.json");if(!await O(n))throw new _(`Extension manifest is missing at "${n}".`,g.USAGE);let r;try{r=JSON.parse(await uf.readFile(n,"utf8"))}catch(a){throw new _(`Failed to parse extension manifest at "${n}": ${m0(a)}`,g.USAGE)}let i=Rs(r);if(!i)throw new _(`Extension manifest at "${n}" is invalid.`,g.USAGE);let o=Is.resolve(e,i.entry);if(!he(e,o))throw new _(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await O(o))throw await u0(i,o,t);if(!await rl(e,o))throw new _(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:o,manifest:i}}function m0(e){return e instanceof Error?e.message:String(e)}import As from"node:fs/promises";import p0 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]="054bae8c-464f-5791-a78a-063588565393")}catch{}})();var f0=".managed-extensions.json",co=1;function Dr(e){return p0.join(e,f0)}function h0(){return{version:co,updated_at:C(),entries:[]}}function Pr(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function mf(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function xe(e){return typeof e=="string"?e:void 0}var _0=/^(?:npm_registry|github_remote)_lookup_timed_out$/u;function g0(e,t){let n=xe(t);return n===void 0||e.kind!=="github"||n.trim().length===0||/^[a-z0-9_]+$/u.test(n.trim())?n:"github_remote_lookup_failed"}function pf(e){return typeof e=="string"&&_0.test(e.trim())}function y0(e,t){return pf(e)&&typeof t=="number"&&Number.isSafeInteger(t)&&t>0?{update_check_timeout_ms:t}:{}}function w0(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function v0(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:xe(t.name),package:xe(t.package),version:xe(t.version),repository:xe(t.repository),owner:xe(t.owner),repo:xe(t.repo),ref:xe(t.ref),subpath:xe(t.subpath),commit:xe(t.commit)}}function b0(e){if(typeof e!="object"||e===null)return null;let t=e;if(!w0(t))return null;let n=v0(t.source);if(!n)return null;let r=el(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:$e(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:xe(t.last_update_check_at),last_update_remote_commit:xe(t.last_update_remote_commit),last_update_remote_version:xe(t.last_update_remote_version),update_available:pf(t.update_error)?null:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:g0(n,t.update_error),...y0(t.update_error,t.update_check_timeout_ms)}}function k0(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==co||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=b0(r);i&&n.push(i)}return{version:co,updated_at:xe(t.updated_at)??C(),entries:Pr(n)}}async function be(e){let t=Dr(e),n=h0();try{let r=await As.readFile(t,"utf8"),i=JSON.parse(r),o=k0(i);if(!o)throw new _(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE);return{path:t,state:o,warnings:[]}}catch(r){if(r instanceof _)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&j(r))return{path:t,state:n,warnings:[]};throw new _(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE)}}async function Wn(e,t){let n=Dr(e),r={version:co,updated_at:C(),entries:Pr(t.entries)};await As.mkdir(e,{recursive:!0}),await As.writeFile(n,`${JSON.stringify(r,null,2)}
29
+ `,"utf8")}function Lr(e,t){let n=e.entries.filter(r=>R(r.name)!==R(t.name)&&R(r.directory)!==R(t.directory));return n.push(t),{...e,updated_at:C(),entries:Pr(n)}}async function ff(e,t,n,r){let i=t.entries.find(a=>R(a.name)===R(n));if(!i)return t;let o=Lr(t,{...i,contributions:r});return await Wn(e,o),o}import{execFile as D0}from"node:child_process";import J from"node:fs/promises";import Ps from"node:os";import L from"node:path";import{fileURLToPath as P0}from"node:url";import{promisify as L0}from"node:util";import N0 from"npm-package-arg";import{extract as M0,list as j0}from"tar";import E0 from"node:fs/promises";import Be 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]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var S0="PM_CLI_PACKAGE_ROOT",hf={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},x0=new Set(["*","all"]);function Cs(){let e=[],t=process.env[S0];return typeof t=="string"&&t.trim().length>0&&e.push(Be.resolve(t.trim())),e.push(Ze(import.meta.url,["../../.."])),[...new Set(e)]}async function Nr(e){let t=e.trim().toLowerCase(),n=await gf(t);if(n)return n;let r=hf[t];if(!r)return null;for(let i of Cs()){let o=Be.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await O(Be.join(o,"manifest.json")))return o}return null}function _f(e){return x0.has(e.trim().toLowerCase())}function I0(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function R0(e,t){let n=await E0.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=Be.join(e,r.name);if(!await O(Be.join(i,"package.json")))continue;let o=await li(i),a=o.aliases&&o.aliases.length>0?o.aliases:[I0(r.name)];for(let s of a){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:i,package_name:o.package_name??null})}}}async function Ts(){let e=new Map;for(let t of Cs()){let n=Be.join(t,"packages");await O(n)&&await R0(n,e)}for(let[t,n]of Object.entries(hf))if(!e.has(t))for(let r of Cs()){let i=Be.join(r,"packages",n.package_directory);if(await O(Be.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function lo(){return(await Ts()).map(e=>e.alias)}async function gf(e){let t=e.trim().toLowerCase();return(await Ts()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function yf(e){let t=await gf(e);return t?(await li(t)).package_name??null:null}async function wf(e){let t=await Nr(e);if(!t)return null;try{let n=await ui(t);return n.length!==1?null:(await zn(n[0])).manifest.name}catch{return null}}function A0(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function C0(e,t,n,r,i,o){let a=r==="global"?"--global":"--project",s=Object.fromEntries(ga.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||o.has(Be.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${a}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:A0(e),media:e.catalog?.media}}}async function vf(e,t,n={}){let r=mn(M(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,o=await be(i),a=new Set(o.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>Be.resolve(m.source.location))),s=new Set(o.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),c=[],d=new Map;for(let m of await Ts()){let f=Be.resolve(m.package_root),p=d.get(f)??[];p.push(m),d.set(f,p)}for(let m of d.values()){let f=m[0],p=m.map(y=>y.alias).sort((y,w)=>y.localeCompare(w)),h=await li(f.package_root);c.push(C0(h,f,p,e,s,a))}let l=$0(n.fields),u=l?c.map(m=>O0(m,l)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:ga.filter(m=>m!=="extensions"),packages:u}}var T0=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function $0(e){if(e===void 0)return;let t=Bu(e);if(t.length===0)throw new _("Package catalog --fields requires a comma-separated list of field names",g.USAGE);let n=t.filter(r=>!T0.has(r));if(n.length>0)throw new _(`Unknown package catalog --fields value(s): ${n.join(", ")}`,g.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function O0(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;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]="fc993281-a2a0-59e8-9f4a-e520f1b94f3b")}catch{}})();var Ef=L0(D0),uo="@unbrained/pm-cli",F0={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},$s;async function Sf(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=L.resolve(t);for(;;){let i=L.join(r,"node_modules",...n.split("/")),o=L.join(i,"package.json");if(await O(o))try{let s=JSON.parse(await J.readFile(o,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let a=L.dirname(r);if(a===r)return null;r=a}}function Os(e,t,n){let r=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(r.length<2)return null;let i=r[0],o=r[1].replace(/\.git$/i,"");if(i.length===0||o.length===0)return null;let a=r.slice(2),s,c;return a[0]==="tree"&&a.length>=2?(s=a[1],c=a.slice(2).join("/")):a.length>0&&(c=a.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:o,repository:`https://github.com/${i}/${o}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function H0(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new _('npm package source must include a package spec after "npm:".',g.USAGE);if(t)throw new _('Options "--gh/--github" cannot be combined with npm: package sources.',g.USAGE);if(n)throw new _('Option "--ref" cannot be combined with npm: package sources.',g.USAGE);return{kind:"npm",input:e,spec:r}}function Mr(e,t={}){let n=e.trim();if(n.length===0)throw new _("Extension source is required for --install.",g.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return H0(n,t.forceGithub===!0,r);let i=(()=>{try{let a=new URL(n);if(a.hostname!=="github.com")return null;let s=a.pathname.replace(/^\/+/,"");return Os(s,n,r)}catch{return null}})();if(i)return i;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let a=Os(o,n,r);if(!a)throw new _(`Invalid GitHub source "${n}".`,g.USAGE);return a}if(t.forceGithub){let a=Os(n,n,r);if(!a)throw new _(`Invalid GitHub shorthand "${n}".`,g.USAGE);return a}if(/^https?:\/\//i.test(n))throw new _(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,g.USAGE);return{kind:"local",input:n,absolute_path:L.resolve(process.cwd(),n)}}async function bf(e,t=Ef,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new _(`Git command failed: git ${e.join(" ")}
30
+ ${o}`,g.GENERIC_FAILURE)}}function Ls(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Ns(e=process.platform){return e==="win32"}async function xf(e,t,n=Ef,r=process.platform,i=process.env){let o=Ls(r),a=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(o,e,{cwd:t,encoding:"utf8",env:a,shell:Ns(r)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",d=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new _(`npm command failed: ${o} ${e.join(" ")}
31
+ ${d}`,g.GENERIC_FAILURE)}}function If(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function Rf(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function U0(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("npm err! code e404")||t.includes("404 not found")||t.includes("is not in this registry")}function z0(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return U0(e)||t.includes("not found")}function W0(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function q0(e){let t=If(e),n=W0(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,o=i?`pm package install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:o?[o,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:o?[`Try ${o} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&o?{fallback_candidates:[{source:i,command:o,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:o}:{}}}}}function G0(e,t){if(!z0(t))return null;let n=q0(e);return new _(n.message,g.NOT_FOUND,n.context)}async function Af(e){if(L.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=L.resolve(process.cwd(),e);return await O(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=P0(t);return await O(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=L.resolve(process.cwd(),e);if(await O(t))return t}return null}async function B0(e){let t=await Af(e);if(t)return t;let n=J0(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function J0(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!Rf(e))return e;let i=e.slice(0,r),o=e.slice(r+n.length);if(o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${i}@${L.resolve(t,o)}`;let a;try{a=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(a)?a.slice(1):a;return`${i}@${s}`}function kf(e,t){let n=L.resolve(e,t),r=L.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${L.sep}`)||L.isAbsolute(r))throw new _("npm pack reported a package archive outside its isolated destination.",g.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function V0(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function K0(e){return(Array.isArray(e)?e.map(t=>({value:t})):typeof e=="object"&&e!==null?Object.entries(e).map(([t,n])=>({key:t,value:n})):[]).flatMap(({key:t,value:n})=>{let r=V0(n,t);return r?[r]:[]})}function Y0(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(a=>{let s=a.name?.trim().toLowerCase();return s!==void 0?s===n:a.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let i=e[0],o=i.name??i.key;return n&&o!==void 0&&o.trim().toLowerCase()!==n?void 0:i}function X0(e,t,n){let r;try{r=JSON.parse(e)}catch{let a=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!a)throw new _("npm pack did not report a tarball filename.",g.GENERIC_FAILURE);return{tarball:kf(t,a)}}let i=K0(r),o=Y0(i,n);if(!o)throw new _("npm pack --json returned an unsupported or ambiguous package receipt.",g.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:kf(t,o.filename),package:o.name??o.key,version:o.version}}async function Z0(e){return Q0(e,xf)}async function Q0(e,t){let n=await Af(e.spec);if(n){if((await J.stat(n)).isFile()&&Cf(n))return Ds(n);let o=L.join(n,"package.json"),a=await O(o)?JSON.parse(await J.readFile(o,"utf8")):{};return{directory:await mo(n,e.input),package:typeof a.name=="string"?a.name:void 0,version:typeof a.version=="string"?a.version:void 0,cleanup:async()=>{}}}let r=await J.mkdtemp(L.join(Ps.tmpdir(),"pm-npm-package-source-")),i=L.join(r,"pack");await J.mkdir(i,{recursive:!0});try{let o=await B0(e.spec),a=await t(["pack",o,"--json","--pack-destination",i]),s=X0(a,i,Rf(e.spec)?void 0:If(e.spec));if(!await O(s.tarball))throw new _("npm pack did not create its reported package archive.",g.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await Ds(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await J.rm(r,{recursive:!0,force:!0})}}}}catch(o){throw await J.rm(r,{recursive:!0,force:!0}),G0(e.spec,o)||o}}function Cf(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function bt(e){throw new _(e,g.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function eE(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&bt(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,i=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||i.some(o=>o===".."))&&bt(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&bt(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&bt(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&bt(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&bt(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&bt(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function Ds(e,t=F0){(await J.stat(e)).size>t.maxArchiveBytes&&bt(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await J.mkdtemp(L.join(Ps.tmpdir(),"pm-local-package-archive-")),r=L.join(n,"extract");await J.mkdir(r,{recursive:!0});let i={entries:0,expandedBytes:0,packageJsonEntries:0},o;try{if(await j0({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(o===void 0)try{eE(d,t,i)}catch(l){o=l}}}),o!==void 0)throw o;i.packageJsonEntries!==1&&bt(`Local package archive must contain exactly one package/package.json entry; found ${i.packageJsonEntries}.`),await M0({file:e,cwd:r,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let a=L.join(r,"package"),s=L.join(a,"package.json"),c=JSON.parse(await J.readFile(s,"utf8"));return await tE(a),{directory:await mo(a,e),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{await J.rm(n,{recursive:!0,force:!0})}}}catch(a){throw await J.rm(n,{recursive:!0,force:!0}),a}}async function tE(e,t=xf){let n=L.join(e,"package.json");if(!await O(n))return;let r;try{r=JSON.parse(await J.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,o=sE(i),a=nE(i);if(o.length===0&&!a)return;let s={...r};delete s.devDependencies;let c={...s};rE(c),await J.writeFile(n,`${JSON.stringify(c,null,2)}
32
+ `,"utf8");try{await Promise.all([J.rm(L.join(e,"package-lock.json"),{force:!0}),J.rm(L.join(e,"npm-shrinkwrap.json"),{force:!0})]),o.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),a&&await iE(e)}finally{await J.writeFile(n,`${JSON.stringify(s,null,2)}
33
+ `,"utf8")}}function nE(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&uo in t)return!0;return!1}function rE(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[uo],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function iE(e){let t=Ze(import.meta.url,["../../.."]),[n,r]=uo.split("/"),i=L.join(e,"node_modules",n),o=L.join(i,r);await J.mkdir(i,{recursive:!0}),await J.rm(o,{recursive:!0,force:!0}),await J.symlink(t,o,oE(process.platform))}function oE(e){return e==="win32"?"junction":"dir"}function aE(e,t){if(e.startsWith("-"))throw new _(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,g.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(n=>{let r=n.charCodeAt(0);return r<=31||r===127||"&|;()`\"'".includes(n)}))throw new _(`Extension runtime dependency "${e}" has an unsafe version specifier.`,g.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{N0.resolve(e,t)}catch{throw new _(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,g.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function sE(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===uo||typeof i!="string"||i.trim().length===0||t.has(r))continue;let o=i.trim();t.set(r,aE(r,o))}return[...t.values()]}async function mo(e,t){let n=await ui(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>L.relative(e,i).replaceAll(L.sep,"/")).sort((i,o)=>i.localeCompare(o));throw new _(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,g.USAGE)}throw new _(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,g.USAGE)}async function cE(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(L.posix.join(".agents/pm/extensions",t.subpath)),n.push(L.posix.join(".custom/pm-extensions",t.subpath)),n.push(L.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let o=L.resolve(e,i);if(he(e,o)&&await O(L.join(o,"manifest.json")))return{directory:o,resolved_subpath:i}}if(await O(L.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await mo(e,t.input);return{directory:r,resolved_subpath:L.relative(e,r).replaceAll(L.sep,"/")}}function dE(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function lE(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!dE(n))return new _(t,g.NOT_FOUND);let r=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,a=typeof o=="string"&&o.trim().length>0?L.resolve(o.trim()):"";$s?.key!==a&&($s={key:a,aliases:await lo()}),r=$s.aliases}catch{}let i=[`Retry with pm package install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${r.join(", ")}`];return new _(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,g.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm package install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm package install npm:${n}`}})}async function Tf(e){if(e.kind==="local"){let r;try{r=await J.stat(e.absolute_path)}catch{throw await lE(e)}if(r.isFile()&&Cf(e.absolute_path)){let o=await Ds(e.absolute_path);return{source:e,directory:o.directory,source_root:L.dirname(o.directory),resolved_subpath:L.relative(L.dirname(o.directory),o.directory).replaceAll(L.sep,"/"),npm_package:o.package,npm_version:o.version,cleanup:o.cleanup}}if(!r.isDirectory())throw new _(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,g.USAGE);let i=await mo(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await Z0(e);return{source:e,directory:r.directory,source_root:L.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:L.relative(L.dirname(r.directory),r.directory).replaceAll(L.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await J.mkdtemp(L.join(Ps.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await bf(n);let r=await bf(["-C",t,"rev-parse","HEAD"]),i=await cE(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await J.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await J.rm(t,{recursive:!0,force:!0}),r}}async function qn(e,t){if(!await O(e)||!await O(t))return!1;let[n,r]=await Promise.all([J.realpath(e),J.realpath(t)]);return n===r}import jr from"node:fs/promises";import Fr 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]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var Ms=1,en="2026.6.24",uE=">=22.18.0",mE={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},$f=new Set([...Qd.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Zd).map(e=>e.toLowerCase()),"scaffold"]),pE="^6.0.0",fE="^22.0.0",Pf=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],at=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Of(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Lf(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function Nf(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var hE={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Df=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Mf={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},_E={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},gE={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},yE={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},jf="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",wE={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},vE={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},bE={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},kE={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function Ff(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function Hf(e,t){return e==="schema"?bE[t]:e==="profile"?kE[t]:vE[t]}function EE(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(a=>a.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),o=r>0&&(r===t.length||i!==void 0&&$f.has(i));return`${($f.has(n)||o?["starter",...t]:t).join(" ")} ping`}function Uf(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],o=`${e.replace(/-/g,"_")}_owner`,a="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(a)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(o)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(a)}],`,` [${JSON.stringify(a)}, "in_progress"],`,` [${JSON.stringify(a)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function SE(e,t,n){let r=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,a=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return a;if(n==="search")return[...a,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...a,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...a,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...Uf(e).map(s=>` ${s}`)," });"]:n==="importers"?[...a,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(o)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(o)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...a,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...a,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...a,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...a,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function xE(e,t,n){let r=n==="hooks",i=n==="search",o=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",m=_E[n],f=e,p=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...at,"});",""]:[],k=i?js(e,t,"search",m):[],E=o?js(e,t,"importers",m):[],x=a?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Of(Lf({extensionName:e,itemTypeName:f,itemTypeFolder:p,fieldName:h,migrationId:y,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...at,"});",""]:[],$=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Of(Nf(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...at,"});",""]:[],S=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...at,"});",""]:[],b=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...at,"});",""]:[],D=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...at,"});",""]:[],U=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...at,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Pf,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...at,"});","",...v,...k,...E,...x,...$,...S,...b,...D,...U,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
34
+ `)}function IE(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var RE={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},AE={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function CE(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function TE(e,t,n){let r=[],i=[...CE(e,t,n)],o=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),m=u===d?[]:[u],f=`${e.replace(/-/g,"_")}_note`,p=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),o.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(a)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),o.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),o.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(f)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(p)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),o.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...Uf(e),"});"),o.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),o.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),o.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),o.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),o.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:o}}function $E(e,t,n){let r=TE(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((i,o)=>i.localeCompare(o)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
35
+ `)}function js(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,o=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],m=f=>[...u," let deactivated = false;"," try {",...f.map(p=>p===""?p:` ${p}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...at];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(o)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(a)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(Lf({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Nf(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function OE(e,t,n){let r=n==="parser",i=JSON.stringify([...Mf[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...Pf,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(en)},`," },",` target: { pmVersion: ${JSON.stringify(en)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...at,"});","",...js(e,t,n,i)].join(`
36
+ `)}function DE(e,t,n){let r=Ff(n,"package"),i=Hf(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${RE[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",jf,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${AE[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Ms}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${en}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
37
+ `)}function PE(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function LE(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function NE(e,t,n,r){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function ME(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function jE(e,t,n,r="commands",i=!1){let o=`pm-${e}`,a=Mf[r],s=IE(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Ms,pm_min_version:en,trusted:!0,sandbox_profile:"strict",permissions:{...mE},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
38
+ `,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...SE(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
39
+ `),l=`${JSON.stringify(hE,null,2)}
40
+ `,u=gE[r],m=Ff(r,"package"),f=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:uE},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${en}`},devDependencies:{"@types/node":fE,typescript:pE},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
41
+ `,p=xE(e,t,r),h=yE[r],y=["node_modules/","*.log","*.tsbuildinfo",""].join(`
42
+ `),w=PE(e),v=["```ts",`import { ${LE(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...NE(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...ME(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],k=[`# ${o}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,h,jf,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...v,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...wE[r],...Hf(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${en}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Ms}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${en}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
43
+ `);return{"package.json":f,"manifest.json":c,"index.ts":i?$E(e,t,r):d,"index.test.ts":i?OE(e,t,r):p,"tsconfig.json":l,".gitignore":y,"README.md":i?DE(o,t,r):k}}async function zf(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!Df.includes(i))throw new _(`Unknown scaffold capability "${n}". Supported capabilities: ${Df.join(", ")}.`,g.USAGE);let o=i;if(r&&t!=="package")throw new _("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",g.USAGE);let a=r?"declarative":"imperative",s=e.trim(),c=Fr.resolve(process.cwd(),s),d=so(Fr.basename(c)).replace(/^(?:pm-)+/u,""),l=EE(d),u=jE(d,l,t,o,r),m=!1;if(await O(c)){if(!(await jr.stat(c)).isDirectory())throw new _(`Scaffold target "${c}" exists and is not a directory.`,g.CONFLICT)}else await jr.mkdir(c,{recursive:!0}),m=!0;for(let[p,h]of Object.entries(u)){let y=Fr.join(c,p);if(await O(y)&&await jr.readFile(y,"utf8")!==h)throw new _(`Scaffold file "${p}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,g.CONFLICT)}let f=[];for(let[p,h]of Object.entries(u)){let y=Fr.join(c,p);if(await O(y)){f.push({path:p,status:"unchanged"});continue}await jr.mkdir(Fr.dirname(y),{recursive:!0}),await jr.writeFile(y,h,"utf8"),f.push({path:p,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:o,style:a,target_path:c,created_directory:m,files:f}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function Wf(e,t){return`${e}:${R(t)}`}function FE(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let a of i){let s=o.get(a.command)??[];o.set(a.command,[...s,a])}for(let[a,s]of o){if(t!==null&&!s.some(d=>t.has(R(d.name))))continue;let c=s.at(-1);n.push({command:a,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function qf(e,t,n){let r=new Set(n.failed.map(d=>Wf(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(Wf(d.layer,d.name))?"failed":"ok",surfaces:Mn(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:Mn(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),o=typeof e=="string"?R(e):null,a=o===null?null:new Set(t.loaded.filter(d=>R(d.name)===o||typeof d.source_package=="string"&&R(d.source_package)===o||(d.source_aliases??[]).some(l=>R(l)===o)).map(d=>R(d.name)).concat(o)),s=a===null?i:i.filter(d=>a.has(R(d.name))),c=a===null?{}:{extensionNames:[...a]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Mn(n,c),command_ownership:FE(n,a)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="573b0fd6-f003-55d8-8f49-c2a5e81cbc31")}catch{}})();function Fs(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function po(e,t,n){let r=R(t),i=n.trim();if(r.length===0||i.length===0)return;let o=e.get(r)??new Set;o.add(i),e.set(r,o)}function HE(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)po(t,r.name,r.command),po(n,r.name,r.action);for(let r of e.commands.handlers)po(t,r.name,r.command);for(let r of e.commands.overrides)po(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Gf(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function UE(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:o}=e;return t?i.has(n)||o.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function fo(e,t,n){let r=new Set(t.loaded.map(c=>R(c.name))),i=new Set(t.failed.map(c=>R(c.name))),o=new Set(n.failed.map(c=>R(c.name))),{commandPathsByExtension:a,actionPathsByExtension:s}=HE(n);return e.map(c=>{let d=R(c.name),l=Gf(a.get(d)),u=Gf(s.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},f=UE({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:i,activationFailedNames:o});return{...c,...f,...m}})}function zE(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function ue(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Vf=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function WE(e){return Vf.has(eh(e))}function Bf(e){return e==="project"||e==="global"}function Kf(e){let t=e.split(":"),n=t[0];if(!n||!Vf.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),o=t.at(-2),a=t.at(-1)?.trim();return!Bf(r)||!Bf(o)||!i||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:o,name:a}}}function qE(e){let t=new Set;for(let n of e){let r=Kf(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Hs(e,t){let n=e.filter(WE);if(n.length===0)return null;let r=qE(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function GE(e,t,n,r){let i=t.map(u=>Kf(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let o=e==="global"?"--global":"--project",a=ue(r,"deactivate"),s=`${ue(r,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(u=>[R(u.name),u])),d=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let f=R(m);d.set(f,(d.get(f)??0)+1)}let l=[...d.entries()].map(([u,m])=>{let f=c.get(u),p=f?.name??u,h=f?.command_paths??[],y=f?.action_paths??[];return{action:"deactivate",extension:p,command:`${a} ${p} ${o}`,affected_collisions:m,feature_loss:{command_paths:[...h].sort((w,v)=>w.localeCompare(v)),action_paths:[...y].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let f=m.affected_collisions-u.affected_collisions;if(f!==0)return f;let p=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,h=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return p!==h?p-h:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:d.size,next_best_command:s,collisions:i,remediation_candidates:l}}function Yf(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function Xf(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function Zf(e,t){let n=[];for(let r of Xl(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var BE=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${ue(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${oi.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${ue(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${ue(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${ue(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${ue(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${ue(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${ue(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function JE(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:a,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=t.map(Ar).filter(f=>f!==void 0),m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:a};if(t.length>0){let f=Hs(t,{deactivate:`${ue(n,"deactivate")} <name> ${i}`,doctor:`${ue(n,"doctor")} ${i} --detail deep --trace`});f&&u.push(f);for(let p of BE)p.matches(t,m)&&u.push(p.build(m))}return s>0&&u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${ue(n,"manage")} ${i} --fix-managed-state (or ${ue(n,"adopt-all")} ${i}, ${ue(n,"adopt")} <name> ${i}, or reinstall via ${ue(n,"install")} ${i} <source>).`),d>0&&u.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&u.push(`Update-check coverage is partial: some sources have no completed check. Run ${ue(n,"manage")} ${i} to request update checks.`),l>0&&u.push(`Update available managed extensions via ${ue(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${ue(n,"manage")} ${i} after extension changes.`),u}function ho(e,t,n,r={}){let i=[...new Set(t)].sort((b,D)=>b.localeCompare(D)),o=n.filter(b=>b.managed).length,a=n.filter(b=>b.enabled).length,s=n.filter(b=>b.active).length,c=n.filter(b=>b.update_check_status==="checked"&&b.update_available===!0).length,d=n.filter(b=>b.managed===!1),l=d.filter(b=>Jf(b)).map(b=>b.name).sort((b,D)=>b.localeCompare(D)),u=d.filter(b=>!Jf(b)).map(b=>b.name).sort((b,D)=>b.localeCompare(D)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let b of n)m[b.update_check_status]+=1;let f=m.failed,p=n.filter(b=>b.update_check_status==="skipped_non_github"&&b.source?.kind!=="builtin").length,h=Object.entries({skipped_unmanaged:u.length,skipped_non_github:p,failed:f,not_checked:m.not_checked}).filter(([,b])=>b>0).map(([b,D])=>`extension_update_health_partial_coverage:${b}:${D}`),y=h.length>0,w=y?"partial":"full",v=[...new Set([...i,...h])].sort((b,D)=>b.localeCompare(D)),k=[...new Set(v.map(b=>eh(b)))].sort((b,D)=>b.localeCompare(D)),E=zE(v),x=e==="global"?"--global":"--project",$=GE(e,i,n,r),S=JE({normalizedWarnings:v,options:r,scope:e,scopeFlag:x,updateCheckFailedTotal:f,policyWarningCount:E.warning_count,unmanagedActionRequiredTotal:u.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:p,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:k,warnings:v,policy_warning_count:E.warning_count,policy_violation_count:E.violation_count,policy_blocked_count:E.blocked_count,total_extensions:n.length,managed_total:o,enabled_total:a,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:y,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(b=>b.name).sort((b,D)=>b.localeCompare(D)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:f,top_warnings:v.slice(0,8),remediation:S,...$?{collision_plan:$}:{}}}function Qf(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new _(`Invalid --detail value "${e}". Expected summary or deep.`,g.USAGE)}function eh(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Hr(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let o=Dd(r);return o?[o]:Pd(r)})();for(let o of i){let a=`${o.layer}:${o.name}:${o.capability}`;t.has(a)||(t.add(a),n.push(o))}}return n}function Ur(){return{version:ai.version,capabilities:[...ai.capabilities],legacy_aliases:{...ai.legacy_aliases}}}function Jf(e){let t=R(e.name),n=R(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function th(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let o=[...new Set(t.filter(d=>d.active).map(d=>R(d.name)))].sort((d,l)=>d.localeCompare(l)),a=[...new Set(n.filter(d=>d.layer==="project").map(d=>R(d.name)))].sort((d,l)=>d.localeCompare(l)),s=new Set(r.map(d=>R(d.name))),c=o.filter(d=>!a.includes(d)&&!s.has(d)).sort((d,l)=>d.localeCompare(l));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:o.length,loaded_project_count:a.length,active_project_names:o,loaded_project_names:a,missing_active_project_names:c}}}import nh 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]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function zr(e,t,n,r){let i=nh.relative(e,n);if(i!==""&&!he(e,n)||n===t||he(t,n))return!1;let o=i.split(nh.sep);return o.includes(".git")?!1:r?!o.some(a=>a===".agents"||a==="node_modules"||a.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as VE}from"node:crypto";import ie from"node:fs/promises";import KE from"node:os";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]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var rh=3,YE=120,ih=250,XE=12e4,ZE=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),oh=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,ah=e=>ZE.has(String(oh(e))),_o=(e,t)=>oh(e)===t,sh=e=>new Promise(t=>{setTimeout(t,e)}),ch=async e=>{let t=Z.join(e,"package.json");await O(t)||await ie.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
44
+ `,"utf8")},dh=async e=>{let t=Ze(import.meta.url,["../../.."]),n=Z.join(e,"node_modules","@unbrained"),r=Z.join(n,"pm-cli");await ie.mkdir(n,{recursive:!0}),await ie.rm(r,{recursive:!0,force:!0}),await ie.symlink(t,r,process.platform==="win32"?"junction":"dir")},Wr=async e=>{let t=Z.resolve(e),n=Z.dirname(t),r=Z.parse(n).root,i=await ie.realpath(r).catch(()=>r),o=Z.relative(r,n),a=o===""?[]:o.split(Z.sep);for(let[s,c]of a.entries()){let d=Z.join(i,c);try{i=await ie.realpath(d)}catch{i=Z.join(i,...a.slice(s));break}}return Z.join(i,Z.basename(t))},lh=async(e,t,n,r=KE.tmpdir())=>Bt("extension_install_copy",async()=>{let i=Z.resolve(e),o=await ie.realpath(i).catch(()=>i),a=await Wr(t);if(o===a)return;if(!he(o,a)){await n(o,t,{recursive:!0,force:!0,filter:u=>zr(o,a,Z.resolve(u),!1)});return}let s=await ie.realpath(Z.resolve(r)).catch(()=>Wr(r)),c=he(o,s)?Z.dirname(o):s;if(he(o,c))throw new _(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,g.USAGE,{code:"extension_install_source_contains_destination"});let d=await ie.mkdtemp(Z.join(c,"pm-extension-copy-")),l=Z.join(d,"extension");try{await n(o,l,{recursive:!0,force:!0,filter:u=>zr(o,a,Z.resolve(u),!0)}),await n(l,t,{recursive:!0,force:!0})}finally{await ie.rm(d,{recursive:!0,force:!0})}}),uh=async(e,t,n=ie.cp)=>{for(let r=1;r<=rh;r+=1)try{await Bt("extension_install_copy",async()=>{await ie.rm(t,{recursive:!0,force:!0}),await lh(e,t,n)});return}catch(i){if(!ah(i)||r===rh)throw i;await sh(ih)}},Us=async e=>{let t;try{t=await ie.readFile(Z.join(e,"owner.json"),"utf8")}catch(i){if(!Xe(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},mh=async(e,t)=>await Us(e)!==t?!1:(await ie.rm(e,{recursive:!0,force:!0}),!0),QE=async(e,t)=>{let n;try{n=await ie.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await Us(e);return r===null?(await ie.rm(e,{recursive:!0,force:!0}),!0):mh(e,r)},eS=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await Us(e)!==t)return;let o=new Date;await ie.utimes(e,o,o)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},tS=async(e,t)=>{await ie.mkdir(e);try{await ie.writeFile(Z.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
45
+ `,"utf8")}catch(n){throw await ie.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},nS=async(e,t,n,r,i)=>{for(let o=1;o<=n;o+=1)try{return await tS(e,t),!0}catch(a){if(!_o(a,"EEXIST"))throw a;await QE(e,i)?o-=1:await sh(r)}return!1},zs=async(e,t,n,r)=>Bt("extension_install",async()=>{let i=Z.join(e,"runtime","extension-install-locks"),o=Z.join(i,"scope.lock");await ie.mkdir(i,{recursive:!0});let{attempts:a=YE,delay_ms:s=ih,stale_ms:c=XE,heartbeat_ms:d}=r??{};if(![a,s,c,d].filter(w=>w!==void 0).every(Number.isFinite))throw new _("Extension install lock timings must be finite numbers.",g.USAGE);let l=Math.max(1,Math.floor(a)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),f=Math.floor(d??m/3);if(m<=0||f<=0||f>=m)throw new _("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",g.USAGE);let p={pid:process.pid,token:VE(),created_at:C(),destination:t};if(!await nS(o,p,l,u,m))throw new _(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let h=eS(o,p.token,f),y=!1;try{let w=await n();return y=!0,w}finally{await h(),await mh(o,p.token).catch(w=>{if(y)throw 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]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function ph(e,t){let n=R(e),r=t.find(i=>R(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,o)=>i.localeCompare(o)),action_paths:[...r?.action_paths??[]].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]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function fh(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${R(o.name)}`]:[])),r=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>o.passThrough!==!0).filter(o=>!n.has(`${o.layer}:${R(o.name)}`)).map(o=>`extension_output_service_override_global:${o.service}:${o.layer}:${o.name}`),i=e.renderers.overrides.filter(o=>(o.commands?.length??0)===0&&o.resultDiscriminator===void 0).map(o=>`extension_output_renderer_override_global:${o.format}:${o.layer}:${o.name}`);return[...new Set([...r,...i])].sort((o,a)=>o.localeCompare(a))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var hh=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=$i(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{spawn as hS}from"node:child_process";import{AsyncLocalStorage as _S}from"node:async_hooks";import{isMainThread as gS}from"node:worker_threads";import yS from"npm-package-arg";import{spawn as rS}from"node:child_process";import{existsSync as go,readFileSync as iS}from"node:fs";import _h 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]="4b754f64-1bb8-54ef-a214-f1603b1711b8")}catch{}})();var gh=2e3;function oS(e,t){let n=new Map;for(let a of e.split(`
46
+ `)){let s=a.trim().split(/\s+/u);if(s.length!==2)continue;let[c,d]=s.map(Number);if(!Number.isSafeInteger(c)||!Number.isSafeInteger(d)||c<=0)continue;let l=n.get(d);l?l.push(c):n.set(d,[c])}let r=new Set([t]),i=[],o=(n.get(t)??[]).map(a=>({pid:a,parent:t}));for(let a=0;a<o.length;a+=1){let s=o[a];if(!r.has(s.pid)){r.add(s.pid),i.push(s);for(let c of n.get(s.pid)??[])o.push({pid:c,parent:s.pid})}}return i.reverse()}function Ws(e,t=yh){let n=t(`/proc/${e.pid}/stat`);if(n===void 0)return!go("/proc/self/stat");let r=n.slice(n.lastIndexOf(")")+1).trim().split(/\s+/u);return Number(r[1])===e.parent}function aS(e=yh,t=process.platform){let n=e("/proc/self/status");if(n===void 0)return t!=="linux"&&!go("/proc/self/status");let r=/^NSpid:\s*(.*)$/mu.exec(n)?.[1]?.trim().split(/\s+/u);return r?.length===1&&Number(r[0])===process.pid}function sS(e,t,n,r=Ws,i=new Map){let o=[],a=!0;for(let s=e;s!==t;){let c=i.get(s);if(c!==void 0){a=c;break}o.push(s);let d=n.get(s);if(d===void 0||!r({pid:s,parent:d})){a=!1;break}s=d}for(let s of o)i.set(s,a);return a}function yh(e){try{return iS(e,"utf8")}catch{return}}var cS=["/bin/ps","/usr/bin/ps"],dS={PATH:"/usr/bin:/bin",LC_ALL:"C"};function lS(e=go){return cS.find(t=>e(t))}var uS="C:\\Windows";function mS(e=process.env,t=go){let n=r=>Object.entries(e).find(([i])=>i.toLowerCase()===r)?.[1];return[n("systemroot"),n("windir"),uS].find(r=>typeof r=="string"&&/^[A-Za-z]:[\\/]/u.test(r)&&t(_h.win32.join(r,"System32","taskkill.exe")))}function wh(e){try{process.kill(e,"SIGKILL")}catch{}}function vh(e,t,n,r=gh){return new Promise(i=>{let o=!1,a="",s;try{s=rS(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0,...n===void 0?{}:{env:n}})}catch{i(void 0);return}let c=r===null?void 0:setTimeout(()=>{d(void 0),s.stdout?.destroy(),s.kill("SIGKILL"),s.unref()},r);function d(l){o||(o=!0,clearTimeout(c),i(l))}if(s.on("error",()=>d(void 0)),!s.stdout){d(void 0);return}s.stdout.setEncoding("utf8"),s.stdout.on("data",l=>{a+=l}),s.on("close",l=>d({code:l,stdout:a}))})}async function bh(e,t={kill:()=>wh(e),alive:()=>!0},n={}){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await pS(e,t,n.taskkillTimeoutMs===void 0?gh:n.taskkillTimeoutMs);return}try{process.kill(-e,"SIGKILL");return}catch{}await fS(e,t),t.kill()}}async function pS(e,t,n){let r=mS();if(r===void 0){t.alive()&&t.kill();return}let i=_h.win32.join(r,"System32","taskkill.exe");(await vh(i,["/pid",String(e),"/T","/F"],void 0,n))?.code!==0&&t.alive()&&t.kill()}async function fS(e,t){let n=lS();if(n===void 0||!aS())return;let r=await vh(n,["-A","-o","pid=","-o","ppid="],dS);if(r?.code!==0||!t.alive())return;let i=oS(r.stdout,e),o=new Map(i.map(s=>[s.pid,s.parent])),a=new Map;for(let s of i)Ws(s)&&sS(s.parent,e,o,Ws,a)&&wh(s.pid)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c4f3228-d035-53ae-b279-3f33bd5323c8")}catch{}})();var wS="PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS",qs=1e4,vS=1e3,bS=25e3,kS=2e3,ES="npm_registry_lookup_failed",SS="npm_registry_lookup_timed_out",xS="github_remote_lookup_failed",IS="github_remote_lookup_timed_out";function Gn(e=process.env){let t=e[wS]?.trim(),n=t?Number(t):Number.NaN;return Number.isFinite(n)?Math.min(bS,Math.max(vS,Math.trunc(n))):qs}var Ne=class extends Error{timeout_ms;teardown;constructor(t,n,r){super(t),this.name="UpdateQueryError",this.timeout_ms=n,this.teardown=r}},Sh=new WeakMap;function xh(e){return Sh.get(e)??Promise.resolve()}function Ih(e,t){let n={checked_at:e,available:null,error:t instanceof Error?t.message:String(t)};return t instanceof Ne&&t.timeout_ms!==void 0&&(n.timeout_ms=t.timeout_ms),t instanceof Ne&&t.teardown!==void 0&&Sh.set(n,t.teardown),n}var qr=new Set;function kh(){for(let e of qr)e()}var Rh=new _S;async function Ah(e){let t=new Set;try{return await Rh.run(t,e)}finally{gS||await Promise.all(t)}}function RS(e){return qr.size===0&&process.on("exit",kh),qr.add(e),()=>{qr.delete(e),qr.size===0&&process.off("exit",kh)}}function AS(e){let t=()=>e.exitCode!==null||e.signalCode!==null,n=()=>{t()||e.kill("SIGKILL")},r=()=>t()||e.pid===void 0?Promise.resolve():new Promise(o=>{let a=setTimeout(()=>{e.unref(),o()},kS);e.once("exit",()=>{clearTimeout(a),o()})}),i=()=>(n(),e.stdout?.destroy(),r());return{stop:()=>t()||e.pid===void 0?Promise.resolve().then(i):bh(e.pid,{kill:n,alive:()=>!t()}).then(i,i),killNow:n}}function Ch(e,t,n,r){return new Promise((i,o)=>{let a;try{a=hS(e,t,{env:r.env,shell:r.shell,stdio:["ignore","pipe","ignore"]})}catch{o(new Ne(r.failed));return}let s=a,c=performance.now()+n,d=!1,l="",u=0,m=AS(s),f=Rh.getStore(),p,h=()=>{let v=RS(m.killNow),k=new Promise(E=>{setTimeout(()=>{m.stop().then(E,E)},0)}).finally(v);return f?.add(k),p=k,k},y=setTimeout(()=>{w(new Ne(r.timedOut,n,h()))},n);function w(v){d||(d=!0,clearTimeout(y),performance.now()>=c?o(new Ne(r.timedOut,n,p)):v?o(v):i(l.trim()))}if(s.on("error",()=>w(new Ne(r.failed))),!s.stdout){w(new Ne(r.failed,void 0,h()));return}s.stdout.setEncoding("utf8"),s.stdout.on("data",v=>{if(!d){if(u+=Buffer.byteLength(v),u>r.maxBuffer){w(new Ne(r.failed,void 0,h()));return}l+=v}}),s.on("exit",(v,k)=>{v===0&&k===null||(w(new Ne(r.failed)),s.stdout.destroy())}),s.on("close",(v,k)=>w(v===0&&k===null?void 0:new Ne(r.failed)))})}function Eh(e,t,n){if(typeof t=="string")try{let r=yS.resolve(e,t);if(r.type==="version")return r.fetchSpec}catch{}throw new Error(n)}var CS=(e,t)=>Ch(Ls(),e,t,{env:{...process.env,npm_config_ignore_scripts:"true"},shell:Ns(),maxBuffer:64*1024,timedOut:SS,failed:ES}),TS=(e,t)=>Ch("git",e,t,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never"},maxBuffer:1024*1024,timedOut:IS,failed:xS});async function Th(e,t=CS,n=Gn()){let r=C();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let i=Eh(e.package,e.version,"missing_or_invalid_installed_npm_version"),o=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],n),a;try{a=JSON.parse(o)}catch{throw new Error("invalid_npm_registry_metadata")}let s=Array.isArray(a)&&a.length===1?a[0]:a,c=Eh(e.package,s,"invalid_npm_registry_version");return{checked_at:r,available:c!==i,remote_version:c}}catch(i){return Ih(r,i)}}var $S=(e,t,n)=>{let r=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),i=r.find(a=>a.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let o=t?.trim();return o?{checked_at:n,remote_commit:i.commit,available:i.commit!==o}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},Gs=async(e,t=TS,n=Gn())=>{let r=C();if(e.kind!=="github"||!e.repository)return{checked_at:r,available:null,error:"not_a_github_managed_source"};try{let i=[e.ref?.trim(),"HEAD"].find(Boolean),o=await t(["ls-remote",e.repository,i,`${i}^{}`],n);return $S(o,e.commit,r)}catch(i){return Ih(r,i)}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f307be2-a113-558f-be2e-8b8f209285a5")}catch{}})();var $h=4;function OS(e){let t=e,n=[];return{acquire:()=>t>0?(t-=1,Promise.resolve()):new Promise(r=>n.push(r)),release:()=>{let r=n.shift();r?r():t+=1}}}function Oh(e,t){let{update_check_timeout_ms:n,...r}=e;return t===void 0?r:{...r,update_check_timeout_ms:t}}async function Dh(e,t=!1,n=Gn(),r=!0){let i=OS($h),o=await Na(e.entries,$h,async a=>{if(!["github","npm"].includes(a.source.kind))return a;if(t)return Oh({...a,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0},void 0);await i.acquire();let s=a.source.kind==="github"?await Gs(a.source,void 0,n):await Th(a.source,void 0,n);return r?xh(s).then(i.release):i.release(),Oh({...a,last_update_check_at:s.checked_at,last_update_remote_commit:"remote_commit"in s?s.remote_commit:void 0,last_update_remote_version:"remote_version"in s?s.remote_version:void 0,update_available:s.available,update_error:s.error},s.timeout_ms)});return{...e,entries:Pr(o)}}import DS from"node:fs/promises";import PS 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]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function Bs(e){return PS.join(e,"extension-migrations.json")}function Ph(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Lh(e,t){return`${e.layer}:${e.name}:${t}`}async function LS(e){let t=Bs(e);if(!await O(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await DS.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function Js(e,t){let n=await LS(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let a=Ph(i,o),s=r.get(Lh(i,a));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function NS(e){let t=await Js(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),r=[],i=!1,o=e.migrations.map((l,u)=>({migration:l,index:u})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:u}of o){let m=Ph(l,u),f=Lh(l,m),p=n.get(f),h=String(l.definition.status??"pending").toLowerCase(),y=p?.status??(h==="applied"||h==="failed"?h:"pending");if(y==="applied"){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:y,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:y,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){r.push({key:f,layer:l.layer,extension:l.name,id:m,before:y,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:y}));let k={key:f,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(f,k),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:f,layer:l.layer,extension:l.name,id:m,before:y,outcome:"applied"}),i=!0}catch(k){let E=k instanceof Error?k.message:String(k),x={key:f,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:E};n.set(f,x),l.definition.status="failed",l.definition.reason=E,r.push({key:f,layer:l.layer,extension:l.name,id:m,before:y,outcome:"failed",error:E}),i=!0}}if(i){let l=await T(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,f)=>m.key.localeCompare(f.key))};await xn({pmRoot:e.pmRoot,filePath:Bs(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
47
+ `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let a=r.filter(l=>l.outcome==="pending").length,s=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:Bs(e.pmRoot),total:r.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function Nh(e){let t=await T(e.resolvedRoots.settings_root),n=await et({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await tt(n);e.warnings.push(...n.warnings,...r.warnings);let i=await NS({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17cca82e-e9f9-5633-8d91-bc6c2b560d5f")}catch{}})();function Mh(e,t){let n=e.filter(r=>r.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:r,result:i})=>{let o=i.details;return{alias:r,ok:i.ok,extension:o.extension,source:o.source,source_resolution:o.source_resolution,install_plan:o.install_plan,dry_run:o.dry_run,destination_path:o.destination_path,activated:o.activated,settings_changed:o.settings_changed,previous_state_preserved:o.previous_state_preserved,rollback:o.rollback,command_paths:o.command_paths,action_paths:o.action_paths,command_discovery:o.command_discovery,verification:o.verification,runtime_activation_status:o.runtime_activation_status,activation_diagnostics:o.activation_diagnostics,warnings:i.warnings}})}}import wo from"node:fs/promises";import yo 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]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var MS=new Set(["node_modules",".git","dist","build","coverage"]);async function jh(e,t,n,r){let i=e.source.kind==="local"?await wo.stat(e.source.absolute_path):void 0,o=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,a=await jS(e.directory,t,r),s={source_mode:o,...o==="archive"?{archive_bytes:i.size}:{},copy:a},c=e.source_root??e.directory;if(o==="directory"&&(!a.complete||a.development_entries>0||a.bytes>=16*1024*1024)&&await O(yo.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),o==="directory"&&!a.complete){let d=a.stop_reason==="entry_limit"?`${a.max_entries} entries`:`${a.max_depth} directory levels`;throw new _(`Local extension source scan stopped at ${d}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,g.USAGE,{code:"extension_install_incomplete_source_scan",reason:a.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function jS(e,t,n={}){let{maxEntries:r=1e4,maxDepth:i=64,signal:o}=n;if(![r,i].every(u=>Number.isSafeInteger(u)&&u>0))throw new _("maxEntries and maxDepth must be positive safe integers.",g.USAGE);o?.throwIfAborted();let a=await wo.realpath(e),s=await Wr(t),c=await qn(a,s);o?.throwIfAborted();let d=c?"in_place":he(a,s)?"nested_filtered_snapshot":"directory_snapshot",l={copy_scope:d,source_directory:a,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:r,max_depth:i};return d==="in_place"||await Fh(a,0,l,o),l}async function Fh(e,t,n,r){r?.throwIfAborted();let i=await wo.opendir(e);for await(let o of i){if(r?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let a=yo.join(e,o.name);if(!zr(n.source_directory,n.destination_directory,a,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(yo.relative(n.source_directory,a).split(yo.sep).some(s=>MS.has(s))&&(n.development_entries+=1),await FS(a,t,n,r),!n.complete)return}}async function FS(e,t,n,r){let i=await wo.lstat(e);if(r?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await Fh(e,t+1,n,r)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import HS from"node:fs/promises";import US 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]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function zS(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function WS(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function Vs(e){let t=US.join(e,"manifest.json"),n;try{n=await HS.readFile(t,"utf8")}catch(s){if(Xe(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=r,o=Hd(i),a=zS(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:o.findings,warnings:o.findings.map(s=>WS(a,s)),remediation:o.findings.map(s=>s.message)}}function Hh(e){return Vs(Qe(e))}import qS from"node:fs/promises";import GS from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bef4424-f5b8-511b-91f7-0b39cf11f515")}catch{}})();async function BS(e,t){if(e.kind!=="local"||e.input.startsWith(".")||e.input.includes("\\")||e.input.includes("/")&&!/^@[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/u.test(e.input))return e;try{return await qS.lstat(e.absolute_path),e}catch(o){if(!j(o))throw o}let n=e.input.trim(),r=t.filter(o=>o.source.kind==="npm"),i=(r.find(o=>o.name===n)??r.find(o=>o.directory===n)??r.find(o=>o.source.package===n))?.source.package;if(i===void 0)return e;try{let o=GS(i);if(!o.registry||o.name!==i)return e}catch{return e}return Mr(`npm:${i}`,{})}async function Uh(e,t,n,r=[]){let i=typeof t=="string"?null:await Nr(e),o=i===null?null:e.trim().toLowerCase(),a=o===null?null:await yf(o),s=await BS(Mr(i??e,{forceGithub:typeof t=="string",ref:n}),r),c=o===null?null:await Sf(e);return{bundledAliasName:o,bundledPackageName:a,installSource:s,sourceResolution:{requested:e,selected:{kind:o===null?s.kind:"builtin",input:o??s.input,...a===null?{}:{package:a}},ambiguous:c!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...o===null?[]:[{kind:"builtin",input:o,...a===null?{}:{package:a},command:`pm install ${o}`}],...c===null?[]:[{kind:"npm",input:`npm:${c.package}`,package:c.package,...c.version===void 0?{}:{version:c.version},directory:c.directory,command:`pm install npm:${c.package}`}]]}}}import Je from"node:fs/promises";import Bn 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]="7c06c702-29ea-5552-aadc-52dfc9c238ef")}catch{}})();var Ks=async e=>Je.readFile(e).catch(t=>{if(_o(t,"ENOENT"))return null;throw t}),JS=async(e,t,n,r,i)=>Bt("extension_install_backup",async()=>{let o=Dr(e),a=un(t),[s,c]=await Promise.all([Ks(o),Ks(a)]);return r&&await Je.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:o,managedStateContents:s,settingsPath:a,settingsContents:c}}),zh=async e=>Bt("extension_install_rollback",async()=>{await Je.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Je.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])if(n===null)await Je.rm(t,{force:!0});else if(t===e.settingsPath){let r=Bn.dirname(e.settingsPath),i=await T(r);try{await xn({pmRoot:r,filePath:t,raw:n.toString("utf8"),op:"extension:install:rollback",author:W(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms})}finally{yu(r)}}else await Je.mkdir(Bn.dirname(t),{recursive:!0}),await Je.writeFile(t,n)});async function Wh(e,t){let n=await O(e.destinationDirectory),r=await qn(e.sourceDirectory,e.destinationDirectory);await Je.mkdir(e.selectedRoot,{recursive:!0});let i=Bn.join(Bn.dirname(e.selectedRoot),"runtime","extension-installs");await Je.mkdir(i,{recursive:!0});let o=await Je.mkdtemp(Bn.join(i,".pm-extension-install-backup-")),a=Bn.join(o,"destination"),s=["package","install",a,`--${e.scope}`],c=K(s),d=!1;try{let l=await JS(e.selectedRoot,e.settingsRoot,e.destinationDirectory,n,a),u;try{u=await t()}catch(m){try{await zh(l)}catch(f){d=!0;let p=new _(`Extension install failed: ${String(m)}; rollback failed: ${String(f)}`,g.GENERIC_FAILURE,{code:"extension_install_rollback_failed",original_code:m instanceof _?m.code:void 0,required:"Restore the previous package before retrying the replacement. Previous state was not preserved.",nextSteps:[n?c:"Repair the reported metadata write failure, then retry the original install."],...n?{recovery:{suggested_retry:c,suggested_retry_args:s}}:{}});throw Object.defineProperty(p,"cause",{value:m,configurable:!0,writable:!0}),p}throw m}if(u.ok)return u;if(!n||r)return{...u,details:{...u.details,previous_state_preserved:!1}};try{await zh(l)}catch(m){return d=!0,{...u,details:{...u.details,previous_state_preserved:!1,rollback:{status:"failed",error:String(m),backup_directory:a,recovery_command:c,recovery_args:s}}}}return{...u,details:{...u.details,overwritten:!1,settings_changed:!1,previous_state_preserved:!0,rollback:{status:"restored"}}}}finally{d||await Je.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f38f530-4e71-5b67-9073-0681198ff96d")}catch{}})();var Jh=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],VS=Jh.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),KS={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},YS="__pm_native_output",XS=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Vh=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],ZS=["disabled","require_trusted","require_provenance"],Kh={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},QS=e=>{let t=e??Kh,n={};for(let r of XS)n[r]=$e(t[r]??[]);return n},ex=(e,t)=>{for(let n of Vh)t[n].length>0&&(e[n]=t[n]);return e},tx=(e,t)=>{for(let n of ZS)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},nx=e=>{let t={};for(let n of Vh)t[n]=$e(e[n]??[]);return t},rx=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:ex(tx({name:t},e),nx(e))},ix=e=>(e??[]).map(t=>rx(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),ox=e=>{let t=Object.assign({},Kh,e??{}),n=QS(e),r=ix(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},Yh=async(e,t)=>{let n=[t],r=await wf(t);r&&n.push(r);let i=[...new Set(n.map(o=>R(o)).filter(o=>o.length>0))];for(let o of i){let a=e.find(c=>R(c.name)===o);if(a)return a;let s=e.find(c=>R(c.directory)===o);if(s)return s}},Xh=(e,t)=>{let n=t.trim(),r=new Set($e(e.extensions.enabled));return new Set($e(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},Zh=(e,t)=>{let n=t.trim(),r=new Set($e(e.extensions.enabled)),i=new Set($e(e.extensions.disabled)),o=[...r],a=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},ax=(e,t)=>{let n=t.trim(),r=new Set($e(e.extensions.enabled)),i=new Set($e(e.extensions.disabled)),o=[...r],a=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},sx=(e,t)=>{let n=t.trim(),r=new Set($e(e.extensions.enabled)),i=new Set($e(e.extensions.disabled)),o=[...r],a=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},cx=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=Jh.map(([i,o,a])=>({action:o,flag:a,distance:Od(t,i,n)})).filter(i=>i.distance!==null).sort((i,o)=>i.distance-o.distance)[0];return r?{action:r.action,flag:r.flag}:null},dx=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=cx(e);if(!r)return new _(`One action flag is required. Use one of: ${VS}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let i=`pm ${n} ${r.flag}`;return Di({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(Qh),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},lx=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],Qh={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},ux=e=>Qh[e]??null,mx=(e,t)=>{let n=[...new Set(lx.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=ux(e.trim().toLowerCase());if(r)return r;throw dx(e,t)}if(n.length>1)throw new _("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},px=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new _('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"},fx=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],e_=e=>{for(let t of fx){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},t_=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,last_update_remote_version:i.last_update_remote_version,update_error:i.update_error,...r.status==="failed"&&i.update_check_timeout_ms!==void 0?{update_check_timeout_ms:i.update_check_timeout_ms}:{},update_check_status:r.status,update_check_reason:r.reason}},hx=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),o=r?Xh(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:t_({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:o},t,r,e_(r))}},_x=async(e,t,n,r,i,o)=>{let a=Me.join(e,t),s=Me.join(a,"manifest.json"),c=o.get(R(t));if(!await O(s))return hx(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await Jn.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=Rs(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(R(u.name))??o.get(R(t));return{summary:t_({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:Xh(r,u.name)},n,m,e_(m))}},st=async(e,t,n,r)=>{if(!await O(e))return{extensions:[],warnings:[]};let i=(await Jn.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,l)=>d.localeCompare(l)),o=new Map(r.entries.map(d=>[R(d.name),d])),a=new Map(r.entries.map(d=>[R(d.directory),d])),s=[],c=[];for(let d of i){let l=await _x(e,d,t,n,o,a);l.warning&&s.push(l.warning),l.summary&&c.push(l.summary)}return{extensions:c.sort((d,l)=>d.name.localeCompare(l.name)),warnings:s.sort((d,l)=>d.localeCompare(l))}},gx=Kl(),yx=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,wx=(e,t,n,r)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),o=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&a.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:yx(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:a,...o?{sdk_dependency_status:"missing"}:{}}},vx=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},n_=e=>e.map(t=>vx(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),r_=(e,t,n)=>{let r=R(e);return t.find(i=>(n===void 0||i.layer===n)&&R(i.name)===r)},bx=(e,t,n,r)=>n.find(i=>i.scope===t&&R(i.name)===R(e))?.activation_status??(r?"failed":"unknown"),i_=(e,t,n,r,i)=>gx.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,a=await Jn.mkdtemp(Me.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Ze(import.meta.url,["../.."]);try{let s=await et({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:_a(),cache_bust:!0,module_graph_snapshot_root:a}),c=await tt({...s}),d=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...n_(c.failed)],l=Object.fromEntries(s.loaded.map(u=>[R(u.name),tl(Mn(c,{extensionName:u.name}))]));return{installed:fo(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await Jn.rm(a,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),Xs=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),o=[...i].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),a=r,s=[];for(let c of o){let d=Me.join(e,c.directory),l=await zn(d),u=C(),m={kind:"local",input:c.name,location:d};a=Lr(a,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:u,updated_at:u,source:m}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return s.length>0&&await Wn(e,a),{state:a,adopted_entries:s,unmanaged_candidates:o,already_managed_count:n.length-i.length}},kx=(e,t)=>{let n=M(process.cwd(),t.path),r=mn(n,process.cwd()),i=e==="global"?ci(process.cwd()):n,o=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:o,roots:r}},vo=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new _('Options "--gh" and "--github" must match when both are provided.',g.USAGE);return n[0]},Ex=e=>KS[e],Sx=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,o=Ex(e),a=`<${r}>`,s=`pm ${n} ${o} ${a}`;throw new _(`Action "${e}" requires ${i} input.`,g.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},bo=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new _('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',g.USAGE);return Sx(t,n)},xx=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${R(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${R(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,i,o)=>o.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},Ix=(e,t)=>{let n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(r=>r.triggered&&!r.allowed);if(n)throw new _(n.message,g.USAGE)},Rx=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},Ax=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},Cx=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:Ax(e),warnings:[...new Set(e.warnings)].sort((i,o)=>i.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(r,YS,{value:!0,enumerable:!1,configurable:!1}),r},Zs=async(e,t,n)=>{let r=mx(e,t);Ix(r,t);let i=Rx(e,r,t),o=px(t),a=kx(o,n),s={action:r,normalizedTarget:i,scope:o,resolvedRoots:a,warnings:[],options:t,global:n},c={...s,withResult:(d,l=!0)=>Cx(s,d,l)};return await Ah(()=>cI(c))},Tx=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=fi(r),o={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},a={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[o[n],...s,`Install the scaffold: ${K(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},$x=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([vo(r),r.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new _('Action "init" does not accept --gh/--github/--ref options.',g.USAGE);let o=bo(n,t,r),a=await zf(o,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:a.created_directory||a.files.some(s=>s.status==="created"),extension:{name:a.extension_name,command:a.command_name},capability:a.capability,style:a.style,target_path:a.target_path,created_directory:a.created_directory,files:a.files,next_steps:Tx(a,r)})},Ox=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:o,withResult:a}=e;if(t!==void 0)throw new _('Action "reload" does not accept a target argument.',g.USAGE);let s=await T(n.settings_root),c=_a(),d=await et({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await tt(d);r.push(...l.warnings);let u={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(u)},Dx=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:o}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new _('Action "catalog" does not accept a package target.',g.USAGE);return o(await vf(n,i,r))},Px=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Lx=e=>({kind:"local",input:e.input,location:e.absolute_path}),Nx=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),Mx=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),jx=(e,t,n,r)=>e?Px(e,t):n.kind==="local"?Lx(n):n.kind==="npm"?Nx(n,r):Mx(n,r),Fx=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:mf(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},Hx=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:o,destinationDirectoryName:a}=t,s=await T(r.settings_root),c=await be(r.selected_root);i.push(...c.warnings);let d=Me.join(r.selected_root,a),l=await O(d),u=await qn(o.directory,d);await Jn.mkdir(r.selected_root,{recursive:!0});let m=jx(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),f=c.state.entries.find(w=>R(w.name)===R(o.manifest.name)),p=Fx(f,o.manifest.version,m,C()),h=Lr(c.state,{name:o.manifest.name,directory:a,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,...p,source:m}),y=Zh(s,o.manifest.name);return u||await uh(o.directory,d),await ch(d),await dh(d),await Wn(r.selected_root,h),y&&await Li(r.settings_root,s,"settings:write"),{settings:s,managedState:h,sourceRecord:m,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:y}},Ux=async(e,t,n)=>{let r=n.filter(i=>R(i.name)===R(t)).flatMap(i=>i.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&r.length>0&&await $r(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},zx=(e,t,n,r,i)=>{let o=r_(t,n.activation_failures,e.scope),a=bx(t,e.scope,n.installed,o),s=[!n.extensions_disabled,a==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${a}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:a,failure:o,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:a,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},Wx=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:o,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t;return Wh({selectedRoot:r.selected_root,settingsRoot:r.settings_root,destinationDirectory:Me.join(r.selected_root,c),sourceDirectory:s.directory,scope:n},async()=>{let d=await Hx(e,t),l=await st(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let u=await i_(r.pm_root,Me.dirname(r.selected_root),d.settings,l.extensions,o);i.push(...u.warnings);let m=await Ux(e,s.manifest.name,u.item_type_registrations),f=ph(s.manifest.name,u.installed),p=zx(e,s.manifest.name,u,f,m),h=u.contribution_inventories[R(s.manifest.name)];return h&&(d.managedState=await ff(r.selected_root,d.managedState,s.manifest.name,h)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:p.activated,settings_changed:d.activationChanged,runtime_activation_status:p.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:h,command_discovery:wx(s.manifest.name,d.sourceRecord,f,p.failure),verification:p.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:p.failure??null}},p.activated)})},qx=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new _('Action "install all" does not accept --ref.',g.USAGE);let o=[],a=new Map;for(let s of await lo()){let c=await Nr(s),d=Me.resolve(c),l=a.get(d);l===void 0&&(l=await Zs(s,{...t,install:!0},n),a.set(d,l)),o.push({alias:s,result:l})}return r.push(...o.flatMap(s=>s.result.warnings)),i(Mh(o,t.dryRun===!0),o.every(s=>s.result.ok))},Gx=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:o,installSource:a,sourceResolution:s}=await Uh(t,n,e.options.ref,(await be(r.selected_root)).state.entries);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${d.package}`)}let c=await Tf(a);try{let d=await zn(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),l=so(d.manifest.name),u=e.options.dryRun===!0||a.kind==="local"&&i===null?await jh(c,Me.join(r.selected_root,l),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:d.manifest.name,version:d.manifest.version},source_resolution:s,install_plan:u}):await zs(r.settings_root,l,()=>Wx(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:o,sourceResolution:s,installSource:a,resolvedSource:c,installPlan:u}))}finally{c.cleanup&&await c.cleanup()}},Bx=async e=>{let t=vo(e.options),n=t??bo(e.normalizedTarget,e.action,e.options);return[t===void 0,_f(n)].every(Boolean)?qx(e):Gx(e,n,t)},Jx=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:a}=e;if(t!==void 0)throw new _('Action "adopt-all" does not accept a target argument.',g.USAGE);if(vo(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new _('Action "adopt-all" does not accept --gh/--github/--ref options.',g.USAGE);let s=await T(r.settings_root),c=await be(r.selected_root);i.push(...c.warnings);let d=await st(r.selected_root,n,s,c.state);i.push(...d.warnings);let l=await Xs(r.selected_root,n,d.extensions,c.state),u=await st(r.selected_root,n,s,l.state);i.push(...u.warnings);let m=ho(n,i,u.extensions,o);i.push(...m.warnings);let f=new Map(u.extensions.map(y=>[`${R(y.name)}:${R(y.directory)}`,y])),p=new Map(u.extensions.map(y=>[R(y.directory),y])),h=l.adopted_entries.map(y=>{let w=R(y.directory),v=f.get(`${R(y.name)}:${w}`)??p.get(w);return{...y,...o_(v)}});return a({adopted_all:h.length>0,adopted_count:h.length,already_managed_count:l.already_managed_count,extensions:h,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},o_=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),Vx=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=Mr(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new _(`Invalid GitHub shorthand "${e}".`,g.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},Kx=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:a,withResult:s}=e,c=bo(n,t,a),d=vo(a),l=await T(i.settings_root),u=await be(i.selected_root);o.push(...u.warnings);let m=await st(i.selected_root,r,l,u.state);o.push(...m.warnings);let f=await Yh(m.extensions,c);if(!f)throw new _(`Installed extension "${c}" was not found in ${r} scope.`,g.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let p=Me.join(i.selected_root,f.directory),h=await zn(p),y=C(),w=Vx(d,c,p,a.ref),v=Lr(u.state,{name:h.manifest.name,directory:f.directory,scope:r,manifest_version:h.manifest.version,manifest_entry:h.manifest.entry,capabilities:[...h.manifest.capabilities],contributions:h.manifest.contributions,installed_at:y,updated_at:y,source:w});await Wn(i.selected_root,v);let k=await st(i.selected_root,r,l,v);o.push(...k.warnings);let E=k.extensions.find(x=>R(x.name)===R(h.manifest.name))??k.extensions.find(x=>R(x.directory)===R(f.directory));return s({adopted:!0,extension:{name:h.manifest.name,directory:f.directory,version:h.manifest.version,entry:h.manifest.entry},source:w,...o_(E)})},a_=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:a}=e,s=bo(n,t,a),c=await T(i.settings_root),d=await be(i.selected_root);o.push(...d.warnings);let l=await st(i.selected_root,r,c,d.state);o.push(...l.warnings);let u=await Yh(l.extensions,s);if(!u)throw new _(`Installed extension "${s}" was not found in ${r} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},Yx=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:o}=await a_(e),a=Me.join(t.selected_root,o.directory);await Jn.rm(a,{recursive:!0,force:!0});let s={...i.state,updated_at:C(),entries:i.state.entries.filter(d=>R(d.name)!==R(o.name)&&R(d.directory)!==R(o.directory))};await Wn(t.selected_root,s);let c=sx(r,o.name);return c&&await Li(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:a,settings_changed:c})},qh=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:o}=e,{settings:a,candidate:s}=await a_(e),c=t==="activate"?Zh(a,s.name):ax(a,s.name);c&&await Li(n.settings_root,a,"settings:write");let d=t==="activate"?await i_(n.pm_root,Me.dirname(n.selected_root),a,[s],i).then(l=>(r.push(...l.warnings),r_(s.name,l.activation_failures,e.scope))):void 0;return d&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),o({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},d===void 0)},Xx=(e,t,n,r,i,o)=>{let a=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=i?.adopted_entries.length??0,d=[[o!==null,o??""],[t>0,`Run pm ${a} explore --project and pm ${a} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${a} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},Ys=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Zx=(e,t,n,r)=>{if(e!=="project"||t||!Ys(r))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Qx=(e,t,n)=>{if(String(e??"").trim().length>0)throw new _('Action "doctor" does not accept a target argument.',g.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new _("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",g.USAGE);let i=Qf(n.detail),o=n.trace===!0;if([o,i!=="deep"].every(Boolean))throw new _("--trace requires --detail deep with --doctor.",g.USAGE);return{isolated:r,detailMode:i,includeTrace:o}},eI=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await Xs(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},tI=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:Ys(r),rerun_command:null,pm_global_path_recipe:null};let o=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:Ys(r),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},nI=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:a,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=Qx(t,n,o),u=await T(r.settings_root),m=await be(r.selected_root);i.push(...m.warnings);let f=await st(r.selected_root,n,u,m.state);i.push(...f.warnings);let{state:p,fix:h}=await eI(e,f.extensions,m.state),y=await st(r.selected_root,n,u,p);i.push(...y.warnings);let w=await et({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await tt({...w,loaded:w.loaded}),k=await Hh(r.pm_root);i.push(...k.warnings,...w.warnings),i.push(...Yf(w.failed)),i.push(...v.warnings),i.push(...Xf(v.failed)),i.push(...Zf(w,v)),i.push(...fh(v,w)),i.push(...xx(w,v)),i.push(...hh(v));let E=fo(y.extensions,w,v),x=th(n,E,w.loaded.map(N=>({layer:N.layer,name:N.name})),w.failed.map(N=>({name:N.name})),w.disabled_by_flag);i.push(...x.warnings);let $=E.filter(N=>N.update_check_status==="failed").map(N=>`extension_update_check_failed:${N.name}`);i.push(...$);let S=ho(n,i,E,o);i.push(...S.warnings);let b=[...S.warnings],D={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},U=Hr(b),I=Ur(),G=S.warning_codes,Re=Zx(n,c,o.vocabulary,w),Fe=Xx(S.remediation,w.failed.length,v.failed.length,o.vocabulary,h,Re),se=tI(n,c,o.vocabulary,w),At={status:S.status,scope:n,warning_count:S.warning_count,warning_codes:G,total_extensions:E.length,managed_total:E.filter(N=>N.managed).length,enabled_total:E.filter(N=>N.enabled).length,active_total:E.filter(N=>N.active).length,unmanaged_loaded_extension_count:S.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:S.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:S.unmanaged_expected_extension_count,runtime_active_total:E.filter(N=>N.runtime_active===!0).length,activation_status_totals:{ok:E.filter(N=>N.activation_status==="ok").length,failed:E.filter(N=>N.activation_status==="failed").length,not_loaded:E.filter(N=>N.activation_status==="not_loaded").length,unknown:E.filter(N=>N.activation_status==="unknown").length},unknown_capability_count:U.length,capability_contract_version:I.version,update_available_total:S.update_available_total,update_check_status_totals:S.update_check_status_totals,update_health_coverage:S.update_health_coverage,update_health_partial:S.update_health_partial,update_check_failed_total:E.filter(N=>N.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Fs(w.failed),activation_failures:Fs(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:x.warnings.length,trace_enabled:l,isolation:se,policy:D,remediation:Fe},lt=h?{requested:!0,applied:h.adopted_entries.length>0,adopted_count:h.adopted_entries.length,already_managed_count:h.already_managed_count,adopted_extensions:h.adopted_entries.map(N=>N.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:y.extensions.filter(N=>N.managed).length,adopted_extensions:[]},Ye={mode:d,summary:At,triage:S,trace_enabled:l,capability_contract:I,capability_guidance:U,managed_state_fix:lt,author_manifest:k,isolation:se,policy:w.policy};if(d==="deep"){let N=l?v.failed:v.failed.map(H=>{let{trace:Ct,...sn}=H;return sn});Ye.deep={warnings:b,warning_codes:G,capability_contract:I,capability_guidance:U,trace_enabled:l,managed_state:{path:m.path,count:p.entries.length,entries:p.entries},installed_extensions:E,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(H=>({layer:H.layer,directory:H.directory,name:H.name,version:H.version,entry:H.entry,priority:H.priority}))},activation:{failed:N,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:x.summary},l&&(Ye.deep.trace={activation_failures:v.failed.filter(H=>H.trace!==void 0).map(H=>({layer:H.layer,name:H.name,entry_path:H.entry_path,error:H.error,method:H.trace.method,command:H.trace.command,capability:H.trace.capability,missing_capability:H.trace.missing_capability,registration_index:H.trace.registration_index,expected_schema:H.trace.expected_schema,hint:H.trace.hint,received:H.trace.received}))})}return s(Ye)},rI=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:a,withResult:s}=e,c=await T(r.settings_root),d=await et({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),l=await tt(d);i.push(...d.warnings),i.push(...l.warnings);let u=qf(t,d,l);if(t!==void 0&&u.extensions.length===0){let m=o.vocabulary==="package"?"package":"extension",f=[...new Set(d.loaded.map(h=>o.vocabulary==="package"&&typeof h.source_package=="string"&&h.source_package.trim().length>0?h.source_package.trim():h.name))].sort((h,y)=>h.localeCompare(y)),p=f.length>0?` Loaded ${m} names: ${f.join(", ")}.`:"";throw new _(`No loaded ${m} named "${t}" was found in ${n} scope.${p} Run pm ${m} explore to list discovered ${m}s.`,g.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},iI=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await Xs(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let o=e.options.fixManagedState===!0;r=await Dh(r,e.options.offline,o?qs:Gn(),!o)}return{state:r,fix:i}},oI=async(e,t,n)=>{let r=await et({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await tt({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:fo(n,r,i),failures:n_(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...r.warnings,...i.warnings])].length,policy:r.policy}}},aI=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},Gh=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:a}=e,s=await T(r.settings_root),c=ox(s.extensions.policy),d=await be(r.selected_root);i.push(...d.warnings);let l=await st(r.selected_root,n,s,d.state);i.push(...l.warnings);let{state:u,fix:m}=await iI(e,l.extensions,d.state),f=await st(r.selected_root,n,s,u);if(i.push(...f.warnings),t==="manage"&&o.offline===!0)for(let v of f.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=f.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);i.push(...v)}let p=await oI(e,s,f.extensions),h=p.installed,y=ho(n,i,h,o);i.push(...y.warnings);let w={total:h.length,managed_total:h.filter(v=>v.managed).length,enabled_total:h.filter(v=>v.enabled).length,active_total:h.filter(v=>v.active).length,extensions:h,triage:y,policy:c};return p.failures!==void 0&&(w.activation_diagnostics={failed_count:p.failures.length,failed:p.failures}),t==="explore"&&(w.runtime_probe=p.summary),t==="manage"&&(w.runtime_probe=p.summary,w.managed_state_fix=aI(m,h)),a(w)},Bh={init:$x,install:Bx,uninstall:Yx,explore:Gh,manage:Gh,describe:rI,reload:Ox,doctor:nI,catalog:Dx,adopt:Kx,"adopt-all":Jx,activate:qh,deactivate:qh,migrate:Nh},sI=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),cI=e=>sI(e)?zs(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Bh[e.action](e)):Bh[e.action](e);import{execFile as dI}from"node:child_process";import{realpath as lI}from"node:fs/promises";import s_ from"node:path";import{promisify as uI}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]="9af87d55-dbe2-561b-9f3f-6f12c0416147")}catch{}})();var mI=uI(dI),pI=32*1024*1024,fI=1e4,hI=["search/eval-queries.json"];function Qs(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function _I(e){return`'${e.replaceAll("'","'\\''")}'`}async function gI(e,t=lI){return t(e).catch(()=>s_.resolve(e))}async function ko(e){let t=await Nt(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 gI(e),r=Qs(s_.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=tm.map(o=>`${r}/${Qs(o)}`);try{let{stdout:o}=await mI("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:pI,windowsHide:!0,timeout:fI}),a=new Set(hI.map(d=>`${r}/${d}`)),s=[...new Set(o.split("\0").filter(d=>d.length>0&&!a.has(Qs(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>s.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:s,tracked_path_count:s.length,remediation_command:s.length===0?null:`git rm --cached -r -- ${c.map(d=>_I(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import c_ from"node:path";import{realpath as yI}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6754b18a-9583-5e3b-88f9-7d0451f45311")}catch{}})();async function d_(e,t){let n=t===null?[]:await im(t,[c_.relative(t,c_.join(await yI(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function l_(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await Tn(e,Cn(n),{gitWorkspaceRoot:t});if(i.status==="ok")return{audit:i,count:0,warnings:[]};let o=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:o,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${o}`]:[]}}function u_(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}import{execFile as fR}from"node:child_process";import{randomUUID as hR}from"node:crypto";import{readdir as _R,realpath as Ut,stat as gR}from"node:fs/promises";import ae from"node:path";import{promisify as yR}from"node:util";import wI 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]="b3ef9db1-1d20-5d88-927e-a08edf563cd5")}catch{}})();function m_(e,t,n){let r=pt(e,t);if(r.ok)return r.document;let i=structuredClone(e);for(let[o,a]of t.entries()){let s=/^\/metadata\/([^/]*)$/u.exec(a.path)?.[1],c=s!==void 0&&!Object.hasOwn(i.metadata,s.replaceAll("~1","/").replaceAll("~0","~"));if(c&&a.op==="remove")continue;let d=c&&a.op==="replace"?{...a,op:"add"}:a,l=pt(i,[d]);if(!l.ok)throw new _(`History union cannot rebase a scalar patch at ${n.branch} line ${n.line} (${n.op}), operation ${o+1} ${a.op} ${a.path}; preserve the source histories for manual recovery.`,g.CONFLICT,{code:"history_union_rebase_conflict",field:a.path,history_merge:{...n,patch_index:o,patch_path:a.path},nextSteps:["Preserve all three history inputs and both item snapshots. Review the named branch event against the merged replay state; do not drop the event or concatenate unchecked patches. After resolving the history and item deliberately, run pm history <id> --verify and pm merge reconcile --dry-run before committing."]});i=l.document}return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daf42303-3202-5824-975c-054e24d275d4")}catch{}})();var vI=Object.freeze({pm_item_scalar_missing:!0});function Vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function V(e){return e===void 0?vI:e}function Ht(e){return Ae(A(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function ec(e,t){let n=Pe(e);if(n)throw new _(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,o]of e.split(/\r?\n/).entries()){let a=o.trim();if(a)try{let s=JSON.parse(a);if(typeof s!="object"||s===null||Array.isArray(s))throw new TypeError("history entry must be an object");r.push(s)}catch{throw new _(`History merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}}return r}function So(e){if(e.op!=="history_repair"||Object.hasOwn(e,"bridge")||!Array.isArray(e.patch)||e.patch.length>0)return;let t=e.reanchor_evidence;if(Array.isArray(t))return t.map(n=>n!==null&&typeof n=="object"?n.record:void 0).reverse().find(n=>n!==null&&typeof n=="object"&&Object.hasOwn(n,"bridge"))}function pe(e){let t=So(e)??e;return bI(t)}function bI(e){return A({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null,...Object.hasOwn(e,"bridge")?{bridge:e.bridge}:{}})}function y_(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&pe(e[r])===pe(t[r]);)r+=1;return r}function kI(e,t,n,r){let i=[...e,...n],o=new Map(i.map((u,m)=>[u,m])),a=new Map(i.map((u,m)=>[pe(u),m])),s=i.map(()=>new Set);for(let u of[e,t]){let m=u.map(f=>o.get(f)??a.get(pe(f)));for(let f=1;f<m.length;f+=1)m[f-1]!==m[f]&&s[m[f-1]].add(m[f])}let c=i.map(()=>0);for(let u of s)for(let m of u)c[m]+=1;let d=i.map((u,m)=>m).filter(u=>c[u]===0),l=[];for(;d.length>0;){d.sort((m,f)=>{let p=i[m],h=i[f],y=Jt(p.ts,h.ts),w=pe(p),v=pe(h);return y||Number(r.has(v))-Number(r.has(w))});let u=d.shift();l.push(i[u]);for(let m of s[u])c[m]-=1,c[m]===0&&d.push(m)}if(l.length!==i.length)throw new _("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",g.GENERIC_FAILURE);return l}function p_(e){return{entries:e,positions:new Map(e.map((t,n)=>[pe(t),n])),index:-1,document:Pt()}}function ac(e,t){let n=t??e.index;for(;e.index<n;){let r=pt(e.document,e.entries[e.index+1].patch);if(!r.ok)throw new _("History union cannot preserve a patch that does not apply in its original branch.",g.GENERIC_FAILURE);e.document=r.document,e.index+=1}return e.document}function f_(e,t){if(t!==void 0&&t>e.index+1)throw new _("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",g.GENERIC_FAILURE);return ac(e,t)}function EI(e,t,n){if(n===0)return;let r=p_(e),i=p_(t),o=ac(r,n-1);ac(i,n-1);let a=0,s=new Set([...k_,...E_]);return(c,d)=>{if(a++<n)return c.patch;let l=pe(c),u=f_(r,r.positions.get(l)),m=f_(i,i.positions.get(l)),f=wi(c.patch).filter(v=>{let[k,E]=v.path.slice(1).split("/");return k!=="metadata"||!s.has(E)}),p=r.positions.get(l),h=m_(d,f,{branch:p===void 0?"theirs":"ours",line:(p??i.positions.get(l))+1,op:c.op}),y=I_(o.metadata,u.metadata,m.metadata,"ours","latest_document_update",String(u.metadata.updated_at),String(m.metadata.updated_at));for(let v of s)Object.hasOwn(y.merged,v)?h.metadata[v]=y.merged[v]:delete h.metadata[v];WI(h.metadata,o.metadata,u.metadata,m.metadata);let w=wn({metadata:h.metadata,body:h.body});return wI.compare(d,w)}}function w_(e){let t=jl(e);return typeof t=="object"?A({bridge:t,patch:e.patch,before_hash:e.before_hash,after_hash:e.after_hash,item_hash_version:e.item_hash_version,hash_algorithm:e.hash_algorithm}):null}function sc(e,t,n,r=[]){let i=h_(e).positions,o=new Set;return[...t,...r].forEach((a,s)=>{let{occurrence:c}=h_(a),d=l=>SI(i,a,c,l);a.forEach((l,u)=>{l.replay_inexact===!0&&v_(o,d(u))}),n&&s<t.length&&xI(o,a,d)}),n||II(o,e),o}function h_(e){let t=new Map,n=e.map((r,i)=>{let o=pe(r),a=t.get(o);return a===void 0?(t.set(o,[i]),0):(a.push(i),a.length-1)});return{positions:t,occurrence:n}}function SI(e,t,n,r){return e.get(pe(t[r]))?.[n[r]]}function v_(e,t){t!==void 0&&e.add(t)}function xI(e,t,n){for(let r of Sa(t).segments){for(let a of zl([r]))v_(e,n(a));let i=n(r.start),o=n(r.end);if(!(i===void 0||o===void 0))for(let a=i;a<o;a+=1)e.add(a)}}function II(e,t){for(let n of Sa(t).segments)if(n.exact)for(let r=n.start;r<n.end;r+=1)e.delete(r)}function cc(e,t){let n=!1;return{entries:e.map((r,i)=>r.replay_inexact===!0||!t.has(i)?r:(n=!0,Wl(r))),changed:n}}function RI(e,t,n,r,i){let o=AI(e,t,n);if(o===null)return null;let a=[...e,...o],s=cc(a,sc(a,[e,t],!1,i)),c=e.every((u,m)=>s.entries[m]===u),d=s.entries.slice(e.length),l=r.endsWith(`
48
+ `)||d.length===0?"":`
49
+ `;return{merged:c?`${r}${l}${d.map(u=>`${JSON.stringify(u)}
50
+ `).join("")}`:Vt(s.entries),strategy:"equivalent_bridges",common_entries:n,entries_from_ours:e.length-n,entries_from_theirs:o.length,entries_total:a.length,reanchored:!1}}function AI(e,t,n){let r=e.slice(n),i=t.slice(n),o=new Set([...r,...i].map(s=>w_(So(s)??s)));if(r.length===0||i.length===0||o.size!==1||o.has(null))return null;let a=b_(r,i,e.at(-1).after_hash);return[e,t,[...e,...a]].every(s=>ve(s).ok)?a:null}function dc(e){return e===void 0?null:w_(So(e)??e)}function b_(e,t,n){let r=new Set(e.map(pe));return t.filter(i=>!r.has(pe(i))).map(i=>{let o=So(i)??i,{bridge:a,replay_inexact:s,...c}=o;return Ei(o,{...c,patch:[],before_hash:n,after_hash:n,...i.replay_inexact===!0?{replay_inexact:!0}:{}},{retainOriginalPatch:!0,retainPriorRecord:!0})})}function CI(e,t){let n=new Set(e.map(pe));return t.some(r=>n.has(pe(r)))}function TI(e,t,n){return!CI(e,t)&&n.every(r=>ve(r).ok)}function __(e,t,n){let r=0;for(;dc(e[t+r])===n;)r+=1;return r}function $I(e,t){let n={ours:e,theirs:t,normalization:null},r=y_(e,t),i=dc(e[r]);if(i===null||dc(t[r])!==i)return n;let o=e.slice(r,r+__(e,r,i)),a=t.slice(r,r+__(t,r,i)),s=e.slice(r+o.length),c=t.slice(r+a.length);if(s.length===0&&c.length===0)return n;let d=b_(o,a,o.at(-1).after_hash),l=[...e.slice(0,r),...o,...d],u={ours:[...l,...s],theirs:[...l,...c]},m=[e,t,u.ours,u.theirs];return TI([...o,...a],[...s,...c],m)?{...u,normalization:{shared:r,neutralCopies:d.length}}:n}function OI(e,t){let n=e.entries_from_theirs+t.neutralCopies;return{...e,strategy:e.strategy==="union_reanchor"?"union_reanchor":"equivalent_bridges",common_entries:t.shared,entries_from_ours:e.entries_total-t.shared-n,entries_from_theirs:n}}function lU(e,t,n){let r=ec(e,"base"),i=[ec(t,"ours"),ec(n,"theirs")],{ours:o,theirs:a,normalization:s}=$I(i[0],i[1]),c=PI(r,o,a,s===null||s.neutralCopies===0?t:Vt(o),s===null?[]:i);return s===null?c:DI(OI(c,s),i[0],t)}function DI(e,t,n){let r=e.merged.split(`
51
+ `);return t.every((i,o)=>r[o]===JSON.stringify(i))?{...e,merged:`${n.replace(/(?<!\n)$/u,`
52
+ `)}${r.slice(t.length).join(`
53
+ `)}`}:e}function PI(e,t,n,r,i){let o=[e,t,n].map(h=>h.filter(y=>y.op==="create"));if(o[0].length===0&&o.slice(1).every(h=>h.length>0)||o.some(h=>h.length>1)||new Set(o.flat().map(pe)).size>1)throw new _("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict"});let a=y_(t,n),s=h=>Vt(cc(h,sc(h,[t,n],!1,i)).entries);if(a===t.length&&a===n.length)return{merged:s(t),strategy:"identical",common_entries:a,entries_from_ours:0,entries_from_theirs:0,entries_total:t.length,reanchored:!1};if(a===n.length)return{merged:s(t),strategy:"fast_forward_ours",common_entries:a,entries_from_ours:t.length-a,entries_from_theirs:0,entries_total:t.length,reanchored:!1};if(a===t.length)return{merged:s(n),strategy:"fast_forward_theirs",common_entries:a,entries_from_ours:0,entries_from_theirs:n.length-a,entries_total:n.length,reanchored:!1};let c=t.slice(a),d=RI(t,n,a,r,i);if(d!==null)return d;let l=new Set(c.map(pe)),u=n.slice(a).filter(h=>!l.has(pe(h))),m=kI(c,n.slice(a),u,l),f=[...t.slice(0,a),...m],p=vi(cc(f,sc(f,[t,n],!0,i)).entries,void 0,{continuousHashSurface:!0,projectPatch:EI(t,n,a),callerMarksBridgeCoverage:!0});if(p.skippedOps>0)throw new _(`History union cannot preserve ${p.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,g.GENERIC_FAILURE);return{merged:Vt(p.entries),strategy:"union_reanchor",common_entries:a,entries_from_ours:c.length,entries_from_theirs:u.length,entries_total:p.entries.length,reanchored:!0}}function tc(e,t){let n=Pe(e);if(n)throw new _(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,o]of e.split(/\r?\n/).entries()){let a=o.trim();if(!a)continue;let s;try{s=JSON.parse(a)}catch{throw new _(`Relationship merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}if(typeof s!="object"||s===null||Array.isArray(s)||typeof s.eventId!="string"||typeof s.sequence!="number")throw new _(`Relationship merge input (${t}) line ${i+1} is not a relationship event (eventId + sequence required).`,g.GENERIC_FAILURE);r.push(s)}return r}function Eo(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
54
+ `)}
55
+ `}function LI(e){return e.map((t,n)=>({...t,sequence:n+1}))}function uU(e,t,n){tc(e,"base");let r=tc(t,"ours"),i=tc(n,"theirs"),o=Math.min(r.length,i.length),a=0;for(;a<o&&r[a].eventId===i[a].eventId;)a+=1;if(a===r.length&&a===i.length)return{merged:Eo(r),strategy:"identical",common_entries:a,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(a===i.length)return{merged:Eo(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:Eo(i),strategy:"fast_forward_theirs",common_entries:a,entries_from_ours:0,entries_from_theirs:i.length-a,entries_total:i.length,reanchored:!1};let s=r.slice(a),c=new Set(s.map(m=>m.eventId)),d=i.slice(a).filter(m=>!c.has(m.eventId)),l=[...s,...d].sort((m,f)=>{if(m.timestamp!==void 0&&f.timestamp!==void 0){let y=Jt(m.timestamp,f.timestamp);if(y!==0)return y}else{if(m.timestamp===void 0&&f.timestamp!==void 0)return 1;if(m.timestamp!==void 0)return-1}let p=c.has(m.eventId),h=c.has(f.eventId);return p!==h?Number(h)-Number(p):0}),u=LI([...r.slice(0,a),...l]);return{merged:Eo(u),strategy:"union_reanchor",common_entries:a,entries_from_ours:s.length,entries_from_theirs:d.length,entries_total:u.length,reanchored:!0}}var k_=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events","deferred_fields"],E_=["acceptance_criteria"],NI=["updated_at"];function tn(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:A(e)===A(t)}function g_(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(l=>A(l))),o=r(t),a=new Set(o.map(l=>A(l))),s=r(n),c=new Set(s.map(l=>A(l))),d=o.filter(l=>{let u=A(l);return!i.has(u)||c.has(u)});for(let l of s){let u=A(l);!a.has(u)&&!i.has(u)&&d.push(l)}return d}function Gr(e){if(typeof e!="object"||e===null||Array.isArray(e))return A(e);let{provenance:t,...n}=e;return A(n)}function MI(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function jI(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(Gr)),o=r(t),a=new Set(o.map(Gr)),s=r(n),c=new Set(s.map(Gr)),d=o.filter(l=>{let u=Gr(l);return!i.has(u)||c.has(u)});for(let l of s){let u=Gr(l);!a.has(u)&&!i.has(u)&&d.push(MI(l))}return d}function FI(e,t){return Jt(String(e),String(t))>=0?e:t}function lc(e,t,n,r){return tn(t,n)?{value:t,from_theirs:!1,conflict:!1}:tn(e,t)?{value:n,from_theirs:!0,conflict:!1}:tn(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function S_(e,t,n,r,i,o,a){let s=lc(e,t,n,r);if(!s.conflict)return{...s,conflict:!1};if(i==="preferred_side")return{...s,resolution_basis:"requested_preference",retained_side:s.from_theirs?"theirs":"ours"};let c=Jt(o,a);if(i==="latest_document_update"&&c!==0){let l=c<0;return{value:l?n:t,from_theirs:l,conflict:!0,resolution_basis:"document_updated_at",retained_side:l?"theirs":"ours"}}let d=A(V(n)).localeCompare(A(V(t)))<0;return{value:d?n:t,from_theirs:d,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:d?"theirs":"ours"}}function nc(e){return{...e.metadata}}function rc(e,t,n){try{let r=Cl(Dt(e,{...n,requireSupportedFormat:!0}),n),i=Object.entries(r.metadata).find(([,o])=>Vn(o))?.[0];if(i!==void 0)throw new TypeError(`metadata field ${i} uses the reserved missing-scalar evidence marker`);return r}catch(r){throw r instanceof _&&r.context?.code==="item_format_version_unsupported"?r:new _(`Item merge input (${t}) is not a readable item document: ${String(r)}`,g.GENERIC_FAILURE)}}function HI(e,t,n,r){return e==="tests"?jI(t,n,r):e==="deferred_fields"?x_(t,n,r):e==="acceptance_criteria"?g_(Oi(t),Oi(n),Oi(r)).join("; "):g_(t,n,r)}function x_(e,t,n){let r=c=>new Map((Array.isArray(c)?c:[]).map(d=>[String(d.field),d])),[i,o,a]=[r(e),r(t),r(n)],s=[];for(let c of[...new Set([...o.keys(),...a.keys()])].sort()){let[d,l,u]=[i.get(c),o.get(c),a.get(c)];if(l===void 0||u===void 0){s.push(l??u);continue}let m=lc(d,l,u,"ours");s.push(m.conflict&&A(u).localeCompare(A(l))<0?u:m.value)}return s}function UI(e){if(!e.unionFieldSet.has(e.field))return!1;let t=HI(e.field,e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,tn(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function zI(e){let t=S_(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution,e.oursUpdatedAt,e.theirsUpdatedAt);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:V(e.baseValue),ours:V(e.oursValue),theirs:V(e.theirsValue),retained:V(t.value),discarded:V(t.from_theirs?e.oursValue:e.theirsValue),retained_side:t.retained_side,resolution_basis:t.resolution_basis})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function I_(e,t,n,r,i,o,a){let s=new Set([...k_,...E_]),c=new Set(NI),d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,m)=>u.localeCompare(m)),l={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let u of d){let m=e[u],f=t[u],p=n[u];if(!UI({field:u,baseValue:m,oursValue:f,theirsValue:p,unionFieldSet:s,accumulator:l})){if(c.has(u)){l.merged[u]=FI(f,p);continue}zI({field:u,baseValue:m,oursValue:f,theirsValue:p,preferred:r,conflictResolution:i,oursUpdatedAt:o,theirsUpdatedAt:a,accumulator:l})}}return R_(l.merged),l}function WI(e,t,n,r){let i=x_(t.deferred_fields,n.deferred_fields,r.deferred_fields);e.deferred_fields=i,R_(e),e.deferred_fields.length===0&&delete e.deferred_fields}function R_(e){Array.isArray(e.deferred_fields)&&(e.deferred_fields=e.deferred_fields.filter(t=>!Il(e,String(t.field))))}function mU(e,t,n,r={}){let i=r.preferred??"ours",o=r.conflictResolution??"preferred_side",a=rc(t,"ours",r),s=rc(n,"theirs",r);if(e.trim().length===0)throw new _("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict",item_id:a.metadata.id});let c=rc(e,"base",r);if(c.metadata.id!==a.metadata.id||c.metadata.id!==s.metadata.id)throw new _("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",g.CONFLICT,{code:"item_identity_conflict",item_id:c.metadata.id});let d=nc(c),l=nc(a),u=nc(s),{merged:m,conflictFields:f,fieldsFromTheirs:p,unionFields:h,conflictDecisions:y}=I_(d,l,u,i,o,a.metadata.updated_at,s.metadata.updated_at),w=S_(c.body,a.body,s.body,i,o,a.metadata.updated_at,s.metadata.updated_at);w.conflict?(f.push("body"),y.push({field:"body",base:V(c.body),ours:V(a.body),theirs:V(s.body),retained:V(w.value),discarded:V(w.from_theirs?a.body:s.body),retained_side:w.retained_side,resolution_basis:w.resolution_basis})):w.from_theirs&&p.push("body");let v=m;return v.pm_format_version=Sl(Math.max(...[c.metadata,a.metadata,s.metadata,v].map(El))),{merged:Al({metadata:v,body:w.value},r),conflict_fields:f,fields_from_theirs:p,union_fields:h,conflict_decisions:y,requested_preference:i,requested_preference_applied:o==="preferred_side",conflict_resolution:o}}function ic(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function oc(e,t){let n=Pe(e);if(n)throw new _(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,g.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new _(`JSON merge input (${t}) is not valid JSON.`,g.GENERIC_FAILURE)}}function qI(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=d=>{let l=new Map;for(let u of d){let m=A(u);l.set(m,(l.get(m)??0)+1)}return l},i=r(e),o=r(t),a=r(n);for(let[d,l]of i)if((o.get(d)??0)<l||(a.get(d)??0)<l)return null;let s=new Map(o),c=[];for(let d of n){let l=A(d),u=s.get(l)??0;u>0?s.set(l,u-1):c.push(d)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function GI(e,t,n,r,i,o,a){if(!ic(t)||!ic(n))return null;let s=ic(e)?e:{},c={},d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,u)=>l.localeCompare(u));for(let l of d){let u=i.length>0?`${i}.${l}`:l,m=BI(s,t,n,l,r,u,o,a);m!==void 0&&(c[l]=m)}return c}function A_(e,t,n,r,i,o,a){if(tn(t,n))return t;let s=qI(e,t,n);if(s!==null)return s.acceptedTheirs&&a.push(i),s.merged;let c=GI(e,t,n,r,i,o,a);if(c!==null)return c;let d=lc(e,t,n,r);return d.conflict?o.push(i):d.from_theirs&&a.push(i),d.value}function BI(e,t,n,r,i,o,a,s){let c=Object.prototype.hasOwnProperty.call(t,r),d=Object.prototype.hasOwnProperty.call(n,r),l=Object.prototype.hasOwnProperty.call(e,r);if(c&&d)return A_(e[r],t[r],n[r],i,o,a,s);if(c){if(l&&tn(e[r],t[r])){s.push(o);return}return l?(a.push(o),i==="theirs"?void 0:t[r]):t[r]}if(!(l&&tn(e[r],n[r])))return l?(a.push(o),i==="theirs"?n[r]:void 0):(s.push(o),n[r])}function pU(e,t,n,r={}){let i=r.preferred??"ours",o=oc(e,"base"),a=oc(t,"ours"),s=oc(n,"theirs"),c=[],d=[],l=A_(o,a,s,i,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
56
+ `,conflict_paths:c,paths_from_theirs:d,preferred:i}}import Io from"node:path";import{execFile as JI}from"node:child_process";import{createHash as C_}from"node:crypto";import{readdir as VI}from"node:fs/promises";import KI from"node:path";import{promisify as YI}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]="af5442e7-c8af-5d81-8c89-7f1a98159cec")}catch{}})();var kt=YI(JI),xo=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function bU(e,t,n){let r=t.trim(),i=/^(['"])(.*)\1$/su.exec(r)?.[2]??r;for(let o of["rebase-merge","rebase-apply"])try{let{stdout:a}=await kt("git",["rev-parse","--path-format=absolute","--git-path",`${o}/orig-head`],{cwd:e,timeout:1e4}),s=(await _r(a.trim(),128))?.trim();if(s===void 0||!xo.test(s))continue;let{stdout:c}=await kt("git",["rev-parse","--verify",`${s}:${i}`],{cwd:e,timeout:1e4}),d=c.trim();return{kind:"rebase",original_head:s,original_blob:d}}catch{}if(n!==void 0&&Object.keys(process.env).some(o=>/^GITHEAD_[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(o)))try{let{stdout:o}=await kt("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[a,s]=o.trim().split(/\r?\n/u);if(a!==s||!xo.test(a))return;let{stdout:c}=await kt("git",["rev-parse","--verify",`${a}:${i}`],{cwd:e,timeout:1e4}),d=c.trim(),l=C_(d.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(n)}\0`).update(n).digest("hex");return d!==l?void 0:{kind:"merge",original_head:a,original_blob:d}}catch{}}function T_(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&(t.kind==="rebase"||t.kind==="merge")&&typeof t.original_head=="string"&&xo.test(t.original_head)&&typeof t.original_blob=="string"&&xo.test(t.original_blob)}async function $_(e,t,n,r){if(r!==void 0&&C_(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(r)}\0`).update(r).digest("hex")!==n.original_blob)return!1;try{let{stdout:i}=await kt("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),o=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await VI(i.trim())).some(d=>o.has(d)))return!1;let{stdout:a}=await kt("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(a.trim()!==n.original_head)return!1;let{stdout:s}=await kt("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(s.trim()!==n.original_blob)return!1;let{stdout:c}=await kt("git",["hash-object","--",KI.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await kt("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!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]="35c5d9a8-5ae0-5e97-9ea3-f8a70a5fd7d0")}catch{}})();var XI=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,ZI=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,Ao=2048,QI=64,eR=1e5,tR=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function Et(e){return XI.test(e)}var nR=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),Co="bounded_non_sensitive_scalars_v1",rR=new Set(["open","in_progress","blocked","closed","canceled"]),iR=new Set(["risk","confidence","severity"]),oR=new Set(["low","medium","high","critical"]),D_=new Map([["priority",new Set([0,1,2,3,4].map(A))],["status",new Set([...rR].map(A))],...[...iR].map(e=>[e,new Set([...oR].map(A))])]);function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function P_(e,t){return Object.keys(e).every(n=>t.has(n))}function Ro(e){return Array.isArray(e)&&e.length<=Ao&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Br(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>eR||r.depth>QI)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(ct(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function L_(e){if(!ct(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[P_(e,nR),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),Br(e.base),Br(e.ours),Br(e.theirs),Br(e.retained),Br(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function aR(e){if(!ct(e))return!1;let t=Object.entries(e);return t.length<=Ao&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function sR(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||Io.posix.isAbsolute(e))return!1;let n=Io.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&Io.posix.basename(n,Io.posix.extname(n))===t}function cR(e){return!Ro(e.fields_from_theirs)||!Ro(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>Ao||!e.decisions.every(L_)?!1:e.merged_field_hashes===void 0||aR(e.merged_field_hashes)}function dR(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],r=[void 0,"clone_local","hash_only","bounded_inline","mixed"],i=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===Co)&&i.includes(e.evidence_source)}function lR(e){return typeof e.created_at=="string"&&yn(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&yn(e.reconciled_at))}function O_(e,t){if(!ct(t)||Oo(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(i=>i==="pm_value_hash"||i==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let r=t.pm_value;return(r===null||D_.get(e)?.has(A(r))===!0)&&Ht(r)===t.pm_value_hash}function uR(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&O_(r.field,r.retained)&&O_(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,i)=>r+(ct(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(ct(i.discarded)&&Object.hasOwn(i.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===Co)}function mR(e){return e.operation!==void 0&&!T_(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function pR(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!P_(e,tR)?"required_fields":typeof e.id!="string"||!Et(e.id)?"receipt_id":typeof e.item_id!="string"||!ZI.test(e.item_id)?"item_id":sR(e.item_path,e.item_id)?null:"item_path"}function To(e,t){if(!ct(e))return"required_fields";let n=pR(e);return n!==null?n:mR(e)?cR(e)?dR(e)?lR(e)?t==="durable"&&!uR(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function $o(e){if(!ct(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(r=>!ct(r)||!Object.hasOwn(r,"retained")||!Object.hasOwn(r,"discarded")?r:{base:V(void 0),ours:V(void 0),theirs:V(void 0),...r})}}function N_(e){if(!ct(e))return;if(!Ro(e.fields_from_theirs))return"fields_from_theirs";if(!Ro(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>Ao)return"decisions";let t=e.decisions.findIndex(n=>!L_(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function uc(e,t){return To(e,t)===null}function Oo(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function mc(e,t){let n=Vn(t),r=Ht(n?void 0:t);return!n&&(t===null||D_.get(e)?.has(A(t))===!0)?{pm_value_hash:r,pm_value:t}:{pm_value_hash: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]="7bab0a8e-842c-5588-a0b2-22ef261ddb06")}catch{}})();var wR=yR(fR),Do=100;async function pc(e){try{let{stdout:t}=await wR("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}}async function F_(e,t){let n=ae.dirname(ae.resolve(e,t));for(let r=0;r<12;r+=1){if(await O(ae.join(n,"settings.json")))return n;let i=ae.dirname(n);if(i===n)break;n=i}return null}function Kn(e){return ae.join(e,"merge-receipts")}function zt(e){return`${e}.json`}async function M_(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await _r(e.receiptPath,Ui)}catch(o){if(Xe(o))return null;throw o}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=$o(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!uc(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||ae.basename(e.receiptPath)!==zt(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprints:Vr(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
57
+ `}}function Jr(e,t=!1){return Ae(A({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:Ae(A(V(n.retained))),discarded_hash:Ae(A(V(n.discarded)))})):Po(e).decisions}))}function Vr(e){let t=[Jr(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(Jr(e,!0)),t}function vR(e,t){let{reconciled_at:n,settlement:r,...i}=e;return t.state==="reconciled"?{...i,state:"reconciled",reconciled_at:t.reconciled_at,...t.settlement===void 0?{}:{settlement:t.settlement}}:{...i,state:"pending"}}async function bR(e,t,n){let r=new Map;for(let i of t){let o=e.get(i.id);if(i.state!=="reconciled"||o===void 0)continue;let a=r.get(o.item_id);if(a===void 0){try{a=await He(ae.join(n,"history",`${o.item_id}.jsonl`),o.item_id),ve(a).ok||(a=[])}catch{a=[]}r.set(o.item_id,a)}let s=o.settlement==="original_git_state_restored",c=A({...Po(o),...s?{reason:o.settlement,operation:o.operation}:{}});if(!a.some(d=>{if(d.op!=="merge_reconcile"||d.record_hash_version===void 0)return!1;let l=d.context?.merge;if(typeof l!="object"||l===null||Array.isArray(l))return!1;let u=l[s?"abandoned_receipts":"receipts"];return Array.isArray(u)&&u.some(m=>A(m)===c)})){let{reconciled_at:d,settlement:l,...u}=o;e.set(o.id,{...u,state:"pending"})}}}function Po(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,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Oo(t.retained)??Ht(Vn(t.retained)?void 0:t.retained),discarded_hash:Oo(t.discarded)??Ht(Vn(t.discarded)?void 0:t.discarded)}))}}async function GU(e){let t=await pc(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,i=ae.basename(r,ae.extname(r)),o={version:1,id:hR(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(s=>({...s,base:V(s.base),ours:V(s.ours),theirs:V(s.theirs),retained:V(s.retained),discarded:V(s.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:C(),value_availability:"clone_local"};await ar(t),await Q(ae.join(t,zt(o.id)),`${JSON.stringify(o,null,2)}
58
+ `);let a=await F_(e.cwd,o.item_path);if(a!==null){let s=Kn(a),c=o.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:mc(u.field,u.retained),discarded:mc(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),d=c.reduce((u,m)=>u+(Object.hasOwn(m.retained,"pm_value")?1:0)+(Object.hasOwn(m.discarded,"pm_value")?1:0),0),l={...o,decisions:c,value_availability:d===0?"hash_only":d===c.length*2?"bounded_inline":"mixed",value_policy:Co};await ar(s),await Q(ae.join(s,zt(o.id)),`${JSON.stringify(l,null,2)}
59
+ `)}return o}async function j_(e,t){let n;try{n=await _R(e)}catch(s){let c=await kR(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],i=0,o=[],a=(s,c)=>{if(i+=1,o.length>=Do)return;let d=s.slice(0,-5);o.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...Et(d)?{receipt_id:d}:{candidate_name_hash:Ae(s)}})};for(let s of n.sort((c,d)=>c.localeCompare(d))){if(!s.endsWith(".json"))continue;let c=await ER(e,s,t);c.receipt!==void 0?r.push(c.receipt):a(s,c)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:o,invalid_evidence_truncated:i>o.length}}async function kR(e,t,n=gR){if(!j(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!j(i))return!1;let o=ae.dirname(r);if(o===r)return!0;r=o}}async function ER(e,t,n){let r;try{r=await _r(ae.join(e,t),Ui)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=$o(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let o=To(i,n);if(o!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(o)?"identity_invalid":"schema_invalid",validation_error:o,...o==="collections"?{validation_path:N_(i)}:{}};let a=i;if(t!==zt(a.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...d}=a;return{receipt:{...d,requested_preference:a.requested_preference??s??"ours",requested_preference_applied:a.requested_preference_applied??(a.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:a.conflict_resolution??"preferred_side",evidence_source:n}}}async function SR(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:r}=await import("./indexed-receipt-blobs-AF4U3F3D.js"),i=await xR(t),o=await r(i?.workspace??e,Kn(t),n.map(a=>zt(a.id)),Ui,i?.directory);return n.flatMap(a=>{try{let s=$o(JSON.parse(o.get(zt(a.id))??""));if(To(s,"durable")!==null)return[];let c=s,d=Vr(a);return c.id===a.id&&Vr(c).some(l=>d.includes(l))?[a.id]:[]}catch{return[]}})}async function xR(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT,n=process.env.PM_SOURCE_PM_PATH,r=process.env.PM_PATH;if(!(process.env.PM_SOURCE_CONTEXT_ACCESS!=="read_only"||!t||!n||!r))try{if(await Ut(e)!==await Ut(r))return;let i=ae.relative(await Ut(t),await Ut(n)),o=i===".."||i.startsWith(`..${ae.sep}`)||ae.isAbsolute(i),a=Kn(o?ae.join(await Ut(t),".agents","pm"):await Ut(n)),[s,c]=await Promise.all([Ut(a),Ut(Kn(n))]);return s!==c?void 0:{workspace:t,directory:a}}catch{return}}async function St(e,t={}){let n=await pc(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await j_(n,"clone_local"),i=t.pmRoot??ae.join(e,".agents","pm"),o=await j_(Kn(i),"durable"),a=new Map(o.receipts.map(u=>[u.id,u])),s=0,c=[];for(let u of r.receipts){let m=a.get(u.id);if(m!==void 0&&!(m.value_policy===void 0?Vr(u):[Jr(u)]).includes(Jr(m))){a.delete(u.id),s+=1,r.invalid_evidence.length+o.invalid_evidence.length+c.length<Do&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:u.id});continue}a.set(u.id,m===void 0?u:vR(u,m))}await bR(a,o.receipts,i);let d=o.receipts.filter(u=>a.has(u.id)),l=new Set(await SR(e,i,d));return{durable_receipt_ids:[...l],unstaged_durable_receipt_ids:d.filter(u=>!l.has(u.id)).map(u=>u.id),receipts:[...a.values()].filter(u=>(t.includeReconciled||u.state==="pending")&&(t.includeLossless!==!1||u.decisions.length>0)).sort((u,m)=>u.created_at.localeCompare(m.created_at)),invalid_evidence_count:r.invalid_evidence_count+o.invalid_evidence_count+s,invalid_evidence:[...r.invalid_evidence,...o.invalid_evidence,...c].slice(0,Do),invalid_evidence_truncated:r.invalid_evidence_truncated||o.invalid_evidence_truncated||r.invalid_evidence_count+o.invalid_evidence_count+s>Do,clone_local_evidence_resolved:n!==null}}function H_(e,t,n){let r=new Set([...t?.durable_receipt_ids??[],...n?t?.unstaged_durable_receipt_ids??[]:[]]),i=[...e].filter(o=>!r.has(o));if(i.length!==0)throw new _(`Merge reconciliation refused ${i.length} receipt(s) without validated tracked evidence; no audit history was written.`,g.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function Yn(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function BU(e,t,n={}){let r=await pc(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!uc(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let o=C(),a=ae.join(r,zt(t.id)),s=await F_(e,t.item_path),c=s===null?null:ae.join(Kn(s),zt(t.id)),d=(await Promise.all([M_({receiptPath:a,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:o,settlement:n.settlement}),...c===null?[]:[M_({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:o,settlement:n.settlement})]])).filter(l=>l!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(l=>l.modern)?[Jr(t)]:Vr(t)).some(l=>d.every(u=>u.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let l of d)await Q(l.path,l.content)}async function JU(e){let t=await St(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:C()}}import{createHash as IR}from"node:crypto";import Lo 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]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var RR="2026-08-09T16:15:18.000Z",z_=Symbol("pre-durable-disposition-eligible");function xt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fc(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function U_(e){return xt(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function W_(e,t){if(typeof e!="string")return!1;let n=Lo.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!Lo.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(Lo.posix.basename(n)===`${t}.toon`||Lo.posix.basename(n)===`${t}.md`)}function AR(e,t){return typeof e.receipt_id=="string"&&Et(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&W_(e.item_path,t)}function q_(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,o=Array.isArray(i)?new Set(i.flatMap(a=>U_(a)?[a.field]:[])):new Set;return fc(t)&&fc(n)&&fc(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(U_)&&o.size===i.length&&t.length===o.size&&t.every(a=>o.has(a))}function CR(e,t){return AR(e,t)&&q_(e)}function TR(e,t){return typeof e.receipt_id=="string"&&Et(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&W_(e.item_path,t)&&q_(e)}function $R(e){return e[z_]===!0}function G_(e,t){if(!xt(e)||!xt(e.context))return[];let n=e.context.merge;return!xt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!xt(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:CR(r,t),[z_]:TR(r,t),...typeof e.ts=="string"&&yn(e.ts)?{eventTimestamp:e.ts}:{}}])}function B_(e,t,n){if(!xt(e)||e.op!=="merge_reconcile")return[];if(!xt(e.context)||!xt(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!xt(i)||typeof i.receipt_id!="string"||!Et(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!yn(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function J_(e,t,n=[]){let r=new Map;for(let o of n){let a=`${o.itemId}\0${o.originalHistoryLine}\0${o.receiptId}\0${o.originalEventTimestamp}`;r.set(a,Math.max(r.get(a)??0,o.auditHistoryLine))}let i=o=>$R(o)&&o.eventTimestamp!==void 0&&Jt(o.eventTimestamp,RR)<0&&(r.get(`${o.itemId}\0${o.line}\0${o.receiptId}\0${o.eventTimestamp}`)??0)>o.line;return{missing:e.filter(o=>!o.legacySummaryAccepted&&!t.has(o.receiptId)&&!i(o)).map(o=>({item_id:o.itemId,history_line:o.line,...Et(o.receiptId)?{receipt_id:o.receiptId}:{receipt_reference_hash:IR("sha256").update(o.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(o=>o.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}import{isUtf8 as OR}from"node:buffer";import{readFile as DR}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="28c1b131-2a07-5308-96de-40bac827a210")}catch{}})();function PR(e){let t=e.trim(),n;try{n=JSON.parse(t)}catch{if(t.startsWith("{")&&t.includes("}"))throw new _("History salvage cannot discard a potentially complete record with trailing corruption.",g.CONFLICT,{code:"history_salvage_refused"});return{kind:"invalid"}}if(Nl(n))return{kind:"non_record"};if(Ll(n)!==null)throw new _("History salvage would conceal interior corruption or a malformed record.",g.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});let r=n;if(!Array.isArray(r.patch)||![r.ts,r.author,r.op,r.before_hash,r.after_hash].every(i=>typeof i=="string"))throw new _("History salvage requires complete history records before the invalid tail.",g.CONFLICT,{code:"history_salvage_refused"});return{kind:"record",entry:r}}function LR(e){return[...e].reverse().find(t=>ze.includes(t.item_hash_version))?.item_hash_version}function NR(e){if(Pe(e))throw new _("Resolve history merge conflicts before salvage.",g.CONFLICT,{code:"history_salvage_refused"});let t=MR(e),n=jR(t);return{entries:t.entries,...n,...WR(e,t.nonRecord,t.invalidOffset,t.invalidLine,t.entries.length)}}function MR(e){let t={entries:[],nonRecord:[],invalidOffset:void 0,invalidLine:0},n=0;for(let[r,i]of e.split(`
60
+ `).entries()){let o=n;if(n+=i.length+1,!i.trim())continue;let a=PR(i);if(a.kind==="record"){if(t.invalidOffset!==void 0)throw new _("History salvage would discard a record or conceal interior corruption.",g.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.entries.push(a.entry)}else a.kind==="non_record"&&t.invalidOffset===void 0?t.nonRecord.push({start:o,end:Math.min(n,e.length),line:r+1}):t.invalidOffset===void 0&&(t.invalidOffset=o,t.invalidLine=r+1)}return t}function jR(e){let t=ve(e.entries),n=t.ok&&t.item_hash_version!==void 0;if(!(e.invalidOffset===void 0&&e.nonRecord.length>0)&&(e.entries.length===0||!n)){let r=e.entries.length>0&&e.invalidOffset===void 0;throw new _("History salvage requires a nonempty verified prefix.",g.CONFLICT,{code:"history_salvage_refused",verification_errors:t.errors,required:"Recover an intact history prefix from version control or a backup.",...r?{nextSteps:["Run pm history-repair <id> --append-only --dry-run: salvage has nothing to discard, and the chain needs a repair."]}:{}})}return{itemHashVersion:n?t.item_hash_version:LR(e.entries),verification:{ok:t.ok,errors:t.errors}}}function FR(e){try{return we(e.hash_algorithm)}catch{let t=typeof e.hash_algorithm=="string";throw new _(t?"History salvage cannot anchor its record: the last kept record uses a digest algorithm this pm version cannot compute.":"History salvage cannot anchor its record: the last kept record's digest label is malformed.",g.CONFLICT,{code:"history_salvage_refused",required:t?"Upgrade pm to a version that reads the stream's digest algorithm; no bytes were changed.":"Recover the damaged record from version control or a backup; no bytes were changed.",nextSteps:[t?"Run npm install -g @unbrained/pm-cli@latest, then preview the salvage again.":"Run pm history <id> --verify --full to locate the record, then restore the stream from version control or a backup."]})}}function HR(e,t,n){let r=e.entries.at(-1);if(r===void 0)return e.prefix;let i=Tt,{item_hash_version:o,...a}=Si({hashAlgorithm:FR(r),nowIso:C(),author:t,op:"history_salvage",before:i,after:i,message:n,context:{history_salvage:e.receipt}}),s=bn({...a,before_hash:r.after_hash,after_hash:r.after_hash,...e.itemHashVersion===void 0?{}:{item_hash_version:e.itemHashVersion}});return`${e.prefix}${JSON.stringify(s)}
61
+ `}function UR(e,t){if(typeof t.metadata.id=="string"&&t.metadata.id!==e)throw new _("History belongs to another item; salvage refused.",g.CONFLICT,{code:"history_salvage_refused"})}function zR(e,t){let n=t.verification.ok,r=Pt(),i=r;for(let o of t.entries){let a=n?pt(r,o.patch):void 0;r=a?.ok===!0?a.document:Hl(r,o.patch,o.op).document,UR(e,r),Object.keys(r.metadata).length>0&&(i=r)}return n&&t.entries.length>0?{final:ku(t.entries,t.entries.length-1),lastItem:i}:{final:r,lastItem:i}}function WR(e,t,n,r,i){let o=n??e.length,a=[...t.map(({start:d,end:l})=>e.slice(d,l)),e.slice(o)].join(""),s="",c=0;for(let{start:d,end:l}of t)s+=e.slice(c,d),c=l;return s+=e.slice(c,o),s!==""&&!s.endsWith(`
62
+ `)&&(s+=`
63
+ `),a===""?{prefix:s,receipt:null}:{prefix:s,receipt:{first_invalid_line:t[0]?.line??r,discarded_bytes:Buffer.byteLength(a),discarded_sha256:Ae(a),retained_entries:i,...t.length>0?{non_record_lines:t.length}:{}}}}function qR(e,t,n){let r=t.metadata?.assignee;if(!(n||r===void 0||r===null||typeof r=="string"))throw new _(`The recorded owner of ${e} is not a name, so salvage cannot check ownership.`,g.CONFLICT,{code:"history_salvage_refused",item_id:e,reason:"owner_malformed",details:{reason:"owner_malformed"},required:"Recover the damaged record from version control or a backup, or override ownership deliberately; no bytes were changed.",nextSteps:[`Inspect ${e}'s raw history stream file or restore it from version control or a backup, or rerun the salvage with --force to override ownership.`]})}async function V_(e,t,n){if(!e)return{itemRaw:null,document:n,live:null};let r=await Tu(e,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n,live:r.document}}function K_(e,t,n){n.itemRaw!==null&&n.live===null&&Vl(e,t,n.itemRaw);let r=n.live??Tt;return ur(e,r,t),r}async function Y_(e){let t;try{t=await DR(e)}catch(n){if(j(n))return null;throw n}if(!OR(t))throw new _("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",g.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function X_(e){let{subject:t,settings:n,options:r,author:i}=e;if([r.normalizeProvenance,r.auditOperation,r.auditContext,r.auditContextById,r.forceAuditEntry,r.mergeReceiptProof,r.mergeReceiptProofById].some(Boolean))throw new _("Tail salvage cannot be combined with other repair modes.",g.USAGE);let o=await Y_(t.historyPath);if(o===null)throw new _(`No history stream exists for ${t.id}.`,g.NOT_FOUND);await We({path:t.historyPath,scope:"project"});let a=NR(o),s=zR(t.id,a),c=xa(s.final),d=a.receipt===null?o:HR(a,i,r.message),l=await V_(t.located,n,xa(s.lastItem));qR(t.id,l.document,r.force===!0);let u=ds({itemDocument:l.document,subjectId:t.id,author:i,force:r.force,settings:n}),m=r.dryRun===!0,f=a.receipt!==null;if(f&&!m){let p=await oe(e.pmRoot,t.id,n.locks.ttl_seconds,i,!!r.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await Y_(t.historyPath),y=await ge(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),w=y?await B(y.itemPath):null;if(h!==o||w!==l.itemRaw)throw K_(e.pmRoot,t.id,await V_(y,n,c)),new _("History or item changed while waiting for salvage lock; retry.",g.CONFLICT);let v=K_(e.pmRoot,t.id,l);await eo({historyPath:t.historyPath,historyRawUnderLock:o,nextHistoryRaw:d}),xi(e.pmRoot,v,t.id),u.push(...await Y({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return BR(t,a,{changed:f,dryRun:m,warnings:u})}function GR(e,t){return t.entries.length===0?e.located===null?[]:[`history_stream_empty:${e.id}:run pm history-repair ${e.id}`]:t.verification.ok?[]:[`history_chain_unverified:${e.id}:run pm history-repair ${e.id} --append-only --dry-run, or pm history-repair ${e.id} --dry-run when a bridge refuses`]}function BR(e,t,n){let r=t.itemHashVersion,{ok:i,errors:o}=t.verification;return{id:e.id,dry_run:n.dryRun,changed:n.changed,history:{path:e.historyPath,entries_scanned:t.entries.length,chain_drift_before:!i,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:n.changed&&!n.dryRun&&t.entries.length>0,verify_ok:i,verify_errors:o,item_hash_version_before:r??null,item_hash_version_after:r??1,version_disposition:"preserved"},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...t.receipt?{salvage:t.receipt}:{},warnings:[...n.warnings,...GR(e,t)],generated_at:C()}}import{isUtf8 as Q_}from"node:buffer";import{constants as hc}from"node:fs";import{lstat as JR,open as VR,readFile as KR,stat as YR}from"node:fs/promises";import XR 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]="0c0c89bc-0ba8-5679-b3e0-e972c2922104")}catch{}})();var ZR=/^verify_failed:before_hash_mismatch:entry_(\d+)$/u,QR=/^verify_failed:patch_apply_failed:entry_(\d+)$/u;function ke(e,t,n,r=[]){throw new _(n,g.CONFLICT,{code:"history_append_only_repair_unavailable",item_id:e,reason:t,...r.length>0?{verification_errors:r}:{},required:"An append-only repair can only bridge chain breaks whose recorded links and patches still replay.",nextSteps:[`Run pm history-repair ${e} --dry-run to preview the rewriting repair, which re-anchors the recorded entries instead.`]})}function eA(e,t){if(t.ok)return null;let n=t.errors.length===1?t.errors[0]:"",r=QR.exec(n);r!==null&&ke(e,"patch_does_not_replay",`History entry ${r[1]} of ${e} does not apply without the unrecorded change, so only a rewriting repair can keep its effect.`,t.errors);let i=ZR.exec(n),o=i===null?0:Number(i[1])-1;return o<1&&ke(e,"chain_failure_not_a_break",`History for ${e} fails verification for a reason an append-only bridge cannot name (${t.errors.join(", ")}).`,t.errors),o}function tA(e,t){let n=Pt();for(let[r,i]of t.entries()){let o=pt(n,i.patch);o.ok||ke(e,"patch_does_not_replay",`History entry ${r+1} of ${e} does not apply without the unrecorded change, so only a rewriting repair can keep its effect.`),n=o.document}return n}function nA(e,t,n,r,i){let o;try{o=we(t.at(-1).hash_algorithm)}catch{ke(e,"chain_failure_not_a_break",`History for ${e} ends with record ${t.length}, whose digest algorithm this build cannot anchor on.`)}let a=[...t].reverse().find(m=>ze.includes(m.item_hash_version))?.item_hash_version;if(a!==void 0)return{itemHashVersion:a,explicitVersion:!0,algorithm:o};let s=n===null?t:t.slice(0,n),c=ve(s).item_hash_version,d=t.at(-1).after_hash,l=ze.filter(m=>[r,i].some(f=>f!==null&&Ue(f,m,o).includes(d))),u=c;return l.includes(c)||(l.length===0&&ke(e,"hash_surface_ambiguous",`History for ${e} declares no hash epoch, and neither replay nor the on-disk item proves its last record's epoch.`),u=l.at(-1)),{itemHashVersion:u,explicitVersion:u!==1,algorithm:o}}function rA(e,t,n,r,i){let o=c=>Ue(c,t.itemHashVersion,t.algorithm),a=o(i);if(new Set(a).size===1)return 0;let s=[o(r),a].map(c=>c.indexOf(n)).find(c=>c>=0);return s===void 0&&ke(e,"hash_surface_ambiguous",`History for ${e} records an epoch-2 hash variant that neither replay nor the on-disk item proves, so an appended record cannot anchor on it.`),s}function iA(e){let{entries:t,surface:n,finalReplay:r,itemReplay:i}=e,o=t.at(-1).after_hash,a=rA(e.id,n,o,r,i),s={hash_algorithm:n.algorithm,ts:C(),author:e.author,op:"history_repair",patch:XR.compare(r,i),before_hash:o,after_hash:Ue(i,n.itemHashVersion,n.algorithm)[a],message:e.message,...n.explicitVersion?{item_hash_version:n.itemHashVersion}:{},...e.breaks.length===0?{}:{bridge:{version:1,breaks:e.breaks,segment_digest:Fl(t.slice(e.segmentStart),{hash_algorithm:n.algorithm})}}};return bn({...s,event_class:bi(s)})}function oA(e,t,n){return e!==void 0?e:`${[...t>0?[`history-repair bridged ${t} chain break${t===1?"":"s"} without rewriting recorded entries`]:[],...n?["reconciled replay with the on-disk item"]:[]].join("; ")}.`}function aA(e,t){if(t===null)return[];let n=[Ea(e[t-1],e[t])];for(let r=t+1;r<e.length;r+=1)e[r].before_hash!==e[r-1].after_hash&&n.push(Ea(e[r-1],e[r]));return n}async function Z_(e,t,n,r){let[i,o]=[await t.stat(),await r(n).catch(()=>null)];(o===null||o.ino!==i.ino||o.dev!==i.dev)&&ke(e,"stream_changed",`History for ${e} was replaced while the repair appended; the bridge was not recorded, retry.`)}async function sA(e,t){let n=Buffer.alloc(t),r=0;for(;r<t;){let{bytesRead:i}=await e.read({buffer:n,offset:r,length:t-r,position:r});if(i===0)break;r+=i}return n.subarray(0,r)}async function eg(e,t,n,r,i=YR){let o=await VR(t,hc.O_RDWR|hc.O_APPEND|hc.O_NOFOLLOW).catch(a=>{throw Xe(a)&&ke(e,"stream_changed",`History for ${e} was removed after the repair verified it; retry.`),a.code==="ELOOP"&&ng(e),a});try{let a=await o.readFile();Q_(a)||ke(e,"stream_not_utf8",`History for ${e} is not valid UTF-8, so its bytes cannot be kept exactly.`);let s=a.toString("utf8");s!==n&&ke(e,"stream_changed",`History for ${e} changed after the repair verified it; retry.`);let c=`${s===""||s.endsWith(`
64
+ `)?"":`
65
+ `}${JSON.stringify(r)}
66
+ `;await o.appendFile(c),await o.sync(),await Z_(e,o,t,i);let d=Buffer.concat([a,Buffer.from(c)]);(await sA(o,d.length+1)).equals(d)||ke(e,"stream_changed",`History for ${e} received another write while the repair appended; run pm health to re-verify the stream.`),await Z_(e,o,t,i)}finally{await o.close()}}async function cA(e,t,n){let r;try{r=await fl(t,`${JSON.stringify(n)}
67
+ `,{sync:!0})}catch(i){throw i instanceof pl?new _(`History for ${e} cannot be rebuilt here: the tracker's filesystem cannot publish a new stream atomically (${i.code}).`,g.CONFLICT,{code:"history_append_only_repair_unavailable",item_id:e,reason:"stream_publish_unsupported",required:"Rebuilding an absent stream needs a filesystem with hard links; no stream was published.",nextSteps:[`Restore ${e}'s history stream from version control or a backup, or run the repair from a clone on a filesystem with hard links.`]}):i}r||ke(e,"stream_changed",`History for ${e} was created after the repair verified it; retry.`)}async function tg(e,t,n,r){await(n===null?cA(e,t,r):eg(e,t,n,r)),await lr(t)}function ng(e){throw new _(`History for ${e} is a symbolic link, so an appended record could land in another stream.`,g.CONFLICT,{code:"history_append_only_repair_unavailable",item_id:e,reason:"stream_not_regular_file",required:"A history stream must be a regular file at its own path; no bytes were changed.",nextSteps:[`Restore ${e}'s own history stream as a regular file from version control or a backup. When none exists and the item is live, move the link aside and preview the rebuild with pm history-repair ${e} --dry-run.`]})}async function _c(e,t){(await JR(t).catch(()=>null))?.isSymbolicLink()===!0&&ng(e)}async function rg(e,t){await _c(e,t);let n=await KR(t).catch(()=>null);n!==null&&!Q_(n)&&ke(e,"stream_not_utf8",`History for ${e} is not valid UTF-8, so its bytes cannot be kept exactly.`)}function ig(e,t,n,r){let{entries:i}=n,o=e.id,a=ve(i),s=eA(o,a),c=aA(i,s);c.length>0&&n.loadedItem===null&&ke(o,"item_missing",`History for ${o} has a chain break, but no on-disk item exists to anchor an append-only bridge.`);let d=tA(o,i),l=n.loadedItem===null?null:wn(n.loadedItem.document),u=l===null?void 0:r.analyzeDiscard(i,d,l),m=u!==void 0,f=c.length>0||m,p=nA(o,i,s,d,l),h=f?iA({id:o,entries:i,surface:p,finalReplay:d,itemReplay:l,author:n.author,message:oA(t.message,c.length,m),breaks:c,segmentStart:s??i.length}):null,y=h===null?i:[...i,h],w=ve(y);w.ok||ke(o,"bridge_does_not_verify",`An append-only bridge for ${o} would not verify (${w.errors.join(", ")}).`,w.errors);let v=h?.bridge===void 0?void 0:{...h.bridge,first_break_entry:s+1},k=r.collectWarnings(f,0,u);return{changed:f,rewrittenEntries:y,applyRewrite:async E=>eg(o,e.historyPath,E.historyRawUnderLock,h),report:({verification:E,warnings:x})=>dA({subject:e,options:t,entries:i,before:a,surface:p,changed:f,itemReplay:l,reconciliation:u,receipt:v,verification:E,warnings:[...k,...x]})}}function dA(e){let{subject:t,entries:n,surface:r,itemReplay:i}=e;return{id:t.id,dry_run:e.options.dryRun===!0,changed:e.changed,history:{path:t.historyPath,entries_scanned:n.length,chain_drift_before:!e.before.ok,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:e.reconciliation!==void 0,audit_entry_added:e.changed&&e.options.dryRun!==!0,verify_ok:e.verification.ok,verify_errors:e.verification.errors,item_hash_version_before:e.before.item_hash_version??null,item_hash_version_after:r.itemHashVersion,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:i===null?null:Ue(i,r.itemHashVersion,r.algorithm).includes(n.at(-1).after_hash)},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...e.receipt===void 0?{}:{bridge:e.receipt},...e.reconciliation===void 0?{}:{reconciliation:e.reconciliation},warnings:[...new Set(e.warnings)].sort((o,a)=>o.localeCompare(a)),generated_at:C()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c389c6ea-195d-54ff-b3ff-215212036271")}catch{}})();function gc(e,t,n,r){let i={reason:r.absent?"missing_stream":"empty_stream",prior_versions:"unrecorded"},o=n.loadedItem,a=e.located.itemPath,s=Si({nowIso:C(),author:n.author,op:"history_repair",before:Tt,after:o.document,message:t.message??`history-repair rebuilt ${r.absent?"the missing":"the empty"} history stream from the on-disk item; earlier versions are not recorded.`,context:{history_reseed:{contract_version:1,...i}}}),c=t.dryRun===!0;return{changed:!0,rewrittenEntries:[s],applyRewrite:async d=>tg(e.id,e.historyPath,d.historyRawUnderLock,s),report:({verification:d,warnings:l})=>({id:e.id,dry_run:c,changed:!0,history:{path:e.historyPath,entries_scanned:0,chain_drift_before:!0,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!0,audit_entry_added:!c,verify_ok:d.ok,verify_errors:d.errors,item_hash_version_before:null,item_hash_version_after:vn,version_disposition:"preserved"},item:{exists:!0,path:a,matched_chain_before:!1},provenance_normalization:{requested:t.normalizeProvenance===!0,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},reseed:i,warnings:[...new Set(l)],generated_at:C()})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bf264bf-c03f-5b5d-a9ea-000dac514705")}catch{}})();var lA=/^(incomplete_record_hash_envelope|record_hash_mismatch|unsupported_record_hash_version|rewrite_evidence_[a-z_]+):entry_(\d+)$/u;function uA(e,t){return new _(`History entry ${t} of ${e} is sealed in a record format this pm version cannot read, so it cannot repair the stream.`,g.CONFLICT,{code:"history_record_version_unsupported",item_id:e,reason:"unsupported_record_hash_version",details:{entry:Number(t),reason:"unsupported_record_hash_version"},required:"Upgrade pm to a version that reads the stream's record format; no bytes were changed.",nextSteps:["Run npm install -g @unbrained/pm-cli@latest, then run pm health again."]})}function og(e,t,n){try{return n()}catch(r){let i=r instanceof TypeError?lA.exec(r.message):null;if(i===null)throw r;let o=t[Number(i[2])-1];throw o!==void 0&&ki(o)?uA(e,i[2]):new _(`History entry ${i[2]} of ${e} no longer matches its seal (${i[1]}), so a repair cannot tell which part of the record to keep.`,g.CONFLICT,{code:"history_record_integrity_invalid",item_id:e,reason:i[1],details:{entry:Number(i[2]),reason:i[1]},required:"Restore the item's history stream from version control or a backup; no bytes were changed.",nextSteps:[`Run pm history ${e} --verify --full to locate the record, restore the stream, then run pm history ${e} --verify --strict-exit.`]})}}import{realpath as lg}from"node:fs/promises";import yc from"node:path";import ug 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]="59addcc3-b4f7-5d72-9be4-50192a780fb1")}catch{}})();function ag(e,t){return t==="body"?e.body:e.metadata[t]}function mA(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=t;return e==="comments"?typeof n.created_at=="string"&&typeof n.author=="string"&&typeof n.text=="string":typeof n.path=="string"||e==="tests"&&typeof n.command=="string"}function pA(e){let t={...e};if(t.source_kind==="merge_union"&&(t.source_kind="local_mutation"),t.provenance!==null&&typeof t.provenance=="object"&&!Array.isArray(t.provenance)){let n={...t.provenance};n.source_kind==="merge_union"&&(n.source_kind="local_mutation"),t.provenance=n}return t}function sg(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(r=>mA(e,r)))return t;let n=t.map(r=>e==="comments"?r:pA(r));return[...new Map(n.map(r=>[A(r),r])).values()]}function wc(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(i=>{let o=t.findIndex((a,s)=>!r.has(s)&&wc(i,a));return o<0?!1:(r.add(o),!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,i])=>Object.hasOwn(n,r)&&wc(i,n[r]))}function cg(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let o=e[i],a=new Set;for(let c of wi(o.patch))a.add(Pi(c.path)),c.from&&a.add(Pi(c.from));let s=[...n].filter(c=>a.has(c));if(s.length!==0){for(let c of s)n.delete(c);r.push({index:i+1,ts:o.ts,author:o.author,op:o.op,fields:s.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function mg(e,t,n){let r=ug.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(Pi(p.path));let o=new Set([...i].filter(p=>wc(sg(p,ag(t,p)),sg(p,ag(n,p))))),a=new Set([...i].filter(p=>!o.has(p))),s=cg(e,a),c=cg(e,o),d=[...i].sort((p,h)=>p.localeCompare(h)),l=[...a].sort((p,h)=>p.localeCompare(h)),u=[...o].sort((p,h)=>p.localeCompare(h)),m=[...new Set(s.map(p=>p.author))].sort((p,h)=>p.localeCompare(h)),f=[...new Set(c.map(p=>p.author))].sort((p,h)=>p.localeCompare(h));return{reconciled_field_count:i.size,reconciled_fields:d,reverted_field_count:a.size,reverted_fields:l,discarded_events:s,discarded_authors:m,preserved_field_count:o.size,preserved_fields:u,preserved_events:c,preserved_authors:f,recovery_hint:s.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 fA(e){try{return await lg(e)}catch{return null}}async function hA(e){if(await fA(yc.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let t=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(o=>o.field)])].sort(),n=e.receipt.merged_field_hashes;if(!n||t.length===0)return null;let r=Object.keys(n).sort();if(t.length!==r.length||t.some((o,a)=>o!==r[a]))return null;let i=e.currentItemReplay.metadata;return t.every(o=>{let a=o==="body"?e.currentItemReplay.body:i[o];return[Ht(a),Ae(A(V(a)))].includes(n[o])})?{receipt:e.receipt,declaredFields:t}:null}async function _A(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(a=>a.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await lg(e.itemPath),r=[];for(let a of t){let s=await hA({receipt:a,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});s&&r.push(s)}let i=new Set(r.flatMap(({declaredFields:a})=>a)),o=e.reconciliation?.reconciled_fields;return r.length>0&&(o===void 0||o.length>0&&o.every(a=>i.has(a)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:a})=>a.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function dg(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:o}=e,a=t.currentItemPath===null?null:yc.relative(o,t.currentItemPath).split(yc.sep).join("/");if(!n||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||a!==i.item_path||i.operation===void 0||!await $_(o,i.item_path,i.operation,t.currentItemRawBeforeLock))throw new _("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function gA(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(a=>a.item_id===e.subjectId).map(a=>a.id)??[]),n=e.options.mergeReceiptProof?await St(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0,r=n?.receipts.filter(a=>a.item_id===e.subjectId&&t.has(a.id))??[];H_(t,n,e.options.dryRun===!0);let i=e.options.mergeReceiptProof?await _A({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(i&&!i.trusted&&e.options.force!==!0)throw new _(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${i.reason}).`,g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let o=i?.trusted?r.filter(a=>i.receipt_ids.includes(a.id)):[];return{mergeReceiptProof:i,effectiveAuditContext:o.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:o.map(Po)}}:e.options.auditContext}}function yA(e,t,n){let r=e.located?.itemPath??null,i=t.loadedItem,o=t.entries;if(!i)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let a=wn(i.document),s=o[o.length-1].after_hash;return{currentItemReplay:a,currentItemPath:r,matchedChainBefore:Ue(a,n,we(o.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:i.raw,loadedItem:i}}function wA(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 vA(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=we(e.reanchorEntries.at(-1)?.hash_algorithm),i=Ue(e.finalReplay,e.itemHashVersion,r),o=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,a=i.indexOf(o),s=Ue(n,e.itemHashVersion,r),c={hash_algorithm:r,ts:C(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?ug.compare(e.finalReplay,e.currentItemReplay):[],before_hash:i[a],after_hash:s[a],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(bn({...c,event_class:bi(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function pg(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function Kr(e,t,n){let{pmRoot:r,settings:i,typeRegistry:o}=await Fa(n.path),a=await Qu(r,e,i,o.type_to_folder);if(t.salvageTail===!0){if(t.appendOnly===!0)throw new _("Tail salvage cannot be combined with other repair modes.",g.USAGE);return X_({pmRoot:r,subject:a,settings:i,typeRegistry:o,options:t,author:W(t.author,i.author_default)})}if(t.appendOnly===!0)return kA(t),await rg(a.id,a.historyPath),ls({pmRoot:r,subject:a,settings:i,typeRegistry:o,operation:"history-repair",options:t,transform:c=>ig(a,t,c,{analyzeDiscard:mg,collectWarnings:pg}),reseed:(c,d)=>gc(a,t,c,d)});let s=bA(t)?void 0:async(c,d)=>(await _c(a.id,a.historyPath),gc(a,t,c,d));return ls({pmRoot:r,subject:a,settings:i,typeRegistry:o,operation:"history-repair",options:t,transform:c=>xA({pmRoot:r,subject:a,options:t},c),reseed:s})}function bA(e){return[e.auditOperation,e.auditContext,e.auditContextById,e.forceAuditEntry,e.mergeReceiptProof,e.mergeReceiptProofById,e.mergeAbandonmentProof].some(t=>t!==void 0&&t!==!1)}function kA(e){if([e.normalizeProvenance,e.auditOperation,e.auditContext,e.auditContextById,e.forceAuditEntry,e.mergeReceiptProof,e.mergeReceiptProofById,e.mergeAbandonmentProof].some(t=>t!==void 0&&t!==!1))throw new _("An append-only repair cannot be combined with other repair modes.",g.USAGE)}function EA(e,t,n){let r=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&n!==void 0&&t.some(i=>i.record_hash_version!==void 0&&i.op==="merge_reconcile"&&A(i.context)===A(n));return e.forceAuditEntry===!0&&!r}function SA(e){let t=cs(e);return t.receipt.changed?cs(ql(e)):t}async function xA(e,t){let{pmRoot:n,subject:r,options:i}=e,o=t.entries,a=t.verification,s=ve(o),c=i.normalizeProvenance?SA(o):{entries:o,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=Ul(c.entries),l=new Set(c.entries.map(U=>U.item_hash_version).filter(U=>U!==void 0)),u=og(r.id,c.entries,()=>vi(c.entries,d,{callerMarksBridgeCoverage:c.receipt.changed})),m=yA(r,t,d);await dg(i.mergeAbandonmentProof,m,a.ok,u);let f=u.finalDocument,p=Ue(f,d),h=!1;if(m.currentItemReplay!==null){let U=Ue(m.currentItemReplay,d);h=!p.some((I,G)=>I===U[G])}let y=h&&m.currentItemReplay?mg(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await gA({options:i,pmRoot:n,subjectId:r.id,itemReplayContext:m,reconciliation:y}),k=[u.entriesRehashed>0,u.entriesPatchRepaired>0,u.entriesResealed>0,h,EA(i,u.entries,v),c.receipt.changed].some(Boolean),E=t.author,x=!!i.dryRun,$=wA({message:i.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=vA({reanchorEntries:u.entries,changed:k,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:f,author:E,message:$,auditOperation:i.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),D=pg(k,u.skippedOps,y);return{changed:k,rewrittenEntries:S,beforeWrite:async()=>dg(i.mergeAbandonmentProof,m,a.ok,u),report:({verification:U,warnings:I})=>({id:r.id,dry_run:x,changed:k,history:{path:r.historyPath,entries_scanned:o.length,chain_drift_before:!a.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:h,audit_entry_added:b,verify_ok:U.ok,verify_errors:U.errors,item_hash_version_before:s.item_hash_version??null,item_hash_version_after:d,version_disposition:l.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},provenance_normalization:{requested:i.normalizeProvenance===!0,...c.receipt},...y?{reconciliation:y}:{},...w?{merge_receipt_proof:w}:{},warnings:[...new Set([...D,...I])].sort((G,Re)=>G.localeCompare(Re)),generated_at:C()})}}function yW(e,t){if(t&&e!==void 0)throw new _("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",g.USAGE);if(!t&&e===void 0)throw new _("history-repair: provide an item <id> or pass --all to repair every drifted stream.",g.USAGE)}async function wW(e,t){if(e.salvageTail===!0)throw new _("Tail salvage requires one explicit item ID; --all is not supported.",g.USAGE);let{pmRoot:n,settings:r,typeRegistry:i}=await Fa(t.path),o=[],a=await ht(n,r.item_format,i.type_to_folder,o,r.schema,{forceSourceScan:!0}),s=await Qt(n,a),c=e.normalizeProvenance?await lp(n):[],d=[...new Set([...s.driftedItems,...c])].sort((f,p)=>f.localeCompare(p)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let f of d)try{let p=await Kr(f,{...e,auditContext:e.auditContextById?.[f],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[f]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=p.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...p.warnings.map(y=>`${f}:${y}`)),l.push({id:f,outcome:h,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,l.push({id:f,outcome:"failed",error:p instanceof Error?p.message:String(p),...await om(p,n)})}return e.dryRun||await Gl(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:a.length,drifted_streams:s.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...o,...u])].sort((f,p)=>f.localeCompare(p)),generated_at:C()}}import{lstat as IA}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="935b37e6-f459-52de-a5c0-8b63af57c29f")}catch{}})();var vc="history_drift_chain_mismatch",RA="history_drift_chain_unbridgeable",_g="history_drift_unrepairable_stream",fg="history_drift_hash_mismatch",gg="history_drift_missing_stream",AA=["history_drift_unreadable_stream",_g,"history_drift_version_skew","history_drift_merge_receipt"],CA=new Set([vc,gg]);function No(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function TA(e,t){return e instanceof _?typeof e.context.reason=="string"?e.context.reason:e.code??t:t}async function hg(e,t,n){try{await Kr(e,{appendOnly:t,dryRun:!0},n);return}catch(r){return TA(r,t?"append_only_preview_failed":"rewrite_preview_failed")}}async function $A(e,t){let n=[];for(let r of No(e.check.details.missing_streams)){let[i]=await Promise.allSettled([IA(ut(t,r))]);i.status==="fulfilled"&&i.value.isSymbolicLink()&&n.push({id:r,reason:"stream_not_regular_file",rewrite_refusal:"stream_not_regular_file"})}return n}async function yg(e,t,n){let r=[],i=new Set(No(e.check.details.version_skews));for(let o of No(e.check.details.chain_mismatches)){if(i.has(o))continue;let a=await hg(o,!0,t);if(a===void 0)continue;let s=await hg(o,!1,t);r.push({id:o,reason:a,...s===void 0?{}:{rewrite_refusal:s}})}return[...r,...await $A(e,n)]}function OA(e,t,n){for(let r of[vc,gg]){if(!e.startsWith(`${r}:`))continue;let i=e.slice(r.length+1),o=t.get(i);return o===null?[]:[o===void 0?e:`${o}:${i}`]}return e.startsWith(`${fg}:`)?n.has(e.slice(fg.length+1))?[]:[e]:[e]}function wg(e,t){let n=No(e.check.details.version_skews),r=new Map([...n.map(o=>[o,null]),...t.map(o=>[o.id,o.rewrite_refusal===void 0?RA:_g])]),i=new Set([...n,...t.filter(o=>o.rewrite_refusal!==void 0).map(o=>o.id)]);e.warnings=e.warnings.flatMap(o=>OA(o,r,i)).sort((o,a)=>o.localeCompare(a)),t.length!==0&&(e.check.details={...e.check.details,repair_refusals:t})}function vg(e){if(AA.some(r=>Object.hasOwn(e,r)))return;let t=Object.keys(e),n=t.every(r=>CA.has(r));for(let r of t)n?e[r]="pm history-repair --all --append-only":r!==vc&&(e[r]="pm history-repair --all")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b30e1b22-1dee-52b2-af2b-3f3af31334d5")}catch{}})();var DA=5;function Mo(e,t){let n=[],r={};for(let o of e){let a=Rl(o);if(a.length!==0){for(let s of a)r[s.field]=(r[s.field]??0)+1;n.push({id:o.id,fields:a.map(s=>s.field),reasons:[...new Set(a.map(s=>s.reason))]})}}if(n.length===0)return;n.sort((o,a)=>o.id.localeCompare(a.id));let i=t?n.length:DA;return{details:{items:n.length,by_field:Object.fromEntries(Object.entries(r).sort(([o],[a])=>o.localeCompare(a))),rows:n.slice(0,i),truncated:n.length>i},warning:`validate_metadata_deferred_fields:${n.length}`}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b0bfb533-68c4-5218-bb53-27a325e2f114")}catch{}})();var Eg=25,PA=me.join("runtime","telemetry","events.jsonl"),LA=me.join("runtime","telemetry","state.json"),NA=2500,MA=500,Sg=Vu-3,jA=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Ic(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("extension_disabled_pm_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("in_progress_unowned:")||e.startsWith("in_progress_idle:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Rc(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Xn(e){return e.trim().toLowerCase()}function Ec(e,t){let n=Xn(e),r=Xn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function Ac(e){try{return(await It.stat(e)).isDirectory()}catch{return!1}}async function FA(e){let t=(await It.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>It.readdir(me.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>sr.some(o=>i.name.endsWith(o))).map(i=>me.parse(i.name).name)))}async function HA(e,t,n,r){let i=await We({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:i,overThreshold:!1,classification:"live"};let a;try{a=await It.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let s="live";if(o){let d=a.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{s=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?a.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function UA(e,t,n){let r=me.join(e,"history");if(!await Ac(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await It.readdir(r)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),o=t.enabled?t.max_entries:null,a=[],s=[],c=[],d=[];for(let l of i){let u=me.join(r,l),m=l.slice(0,-6),f=await HA(u,m,t,n);a.push(...f.warnings),f.classification==="tombstone"&&c.push(m),f.classification==="orphaned"&&d.push(m),f.overThreshold&&s.push(m)}return{count:i.length,warnings:[...a,...s.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:s,max_entries:o,tombstones:c,orphaned:d}}function Sc(e,t){return me.relative(e,t).replaceAll("\\","/")}async function xg(e,t){let n=[...new Set(Object.values(t))].sort((i,o)=>i.localeCompare(o)),r=[];for(let i of n){let o=me.join(e,i),a=[];try{a=await It.readdir(o)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&j(s))continue;continue}for(let s of a)sr.some(c=>s.toLowerCase().endsWith(c))&&r.push(me.join(o,s))}return r.sort((i,o)=>Sc(e,i).localeCompare(Sc(e,o))),r}function zA(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}function WA(e){let t=Mo(e,!1);return t===void 0?{}:{curation:{deferred_fields:t.details}}}async function qA(e,t,n){let r=await xg(e,t),i=[],o=[],a=[],s=[],c=ln(F());for(let d of r){let l=Sc(e,d),u;try{u=await It.readFile(d,"utf8")}catch{i.push(l);continue}let m=Pe(u);if(m){o.push({path:l,...m});continue}try{let f=Dt(u,{format:Bd(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:_i(f.metadata)})}catch{a.push(l)}}return{paths:r,unreadable:i,conflictMarkers:o,parseFailures:a,formatVersions:s}}async function GA(e){let t=me.join(e,"history"),n=[],r=[],i=[],o=[],a=[],s=[];try{s=(await It.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){zA(c)&&n.push("history")}for(let c of s){let d=c.slice(0,-6),l;try{l=await It.readFile(me.join(t,c),"utf8")}catch{n.push(d);continue}let u=Pe(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,f)=>{if(m.trim())try{let p=JSON.parse(m);o.push(...G_(p,d).map(h=>({itemId:d,line:f+1,...h}))),a.push(...B_(p,d,f+1))}catch{i.push({id:d,line:f+1})}})}return{files:s,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:o,mergeReceiptDispositions:a}}function Ig(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function BA(e,t,n,r,i,o){let a=await qA(e,t,n),s=await GA(e),c=gi(a.formatVersions,cr,hi),d=_e(n),l=Hi(o,I=>xl(I,d),hr()),u=await ko(e),m=await Nt(e),f=await d_(e,m),p=await l_(e,m,r,i),h=m===null?null:await $n(m),y=await St(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(y.durable_receipt_ids),v=J_(s.mergeReceiptReferences,w,s.mergeReceiptDispositions),k=v.missing,E=y.receipts.filter(I=>I.state==="pending"),{pendingDecisions:x,lossless:$}=Yn(E),S=h?.status==="missing"&&h.missing_keys.length===5&&h.drifted_keys.length===0,b=[...a.unreadable.map(I=>`integrity_item_unreadable:${I}`),...a.conflictMarkers.map(I=>`integrity_item_conflict_marker:${I.path}:L${I.line}`),...a.parseFailures.map(I=>`integrity_item_parse_failed:${I}`),...s.unreadable.map(I=>`integrity_history_unreadable:${I}`),...s.conflictMarkers.map(I=>`integrity_history_conflict_marker:${I.id}:L${I.line}`),...s.invalidJson.map(I=>`integrity_history_invalid_json:${I.id}:L${I.line}`),...c.outdated.map(I=>`integrity_item_outdated_format_version:${I}`),...c.ahead.map(I=>`integrity_item_ahead_format_version:${I}`),...Ig(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...h!==null&&h.status!=="ok"?[`merge_driver_configuration_${S?"missing":"drift"}:${h.missing_keys.length+h.drifted_keys.length}`]:[],...p.warnings,...f.warnings,...x.length>0?[`merge_decisions_unreviewed:${x.length}`]:[],...$.length>0?[`merge_receipts_pending:${$.length}`]:[],...u_({invalidEvidenceCount:y.invalid_evidence_count,missingHistoryReferenceCount:k.length})],D=[...new Set(b)].sort((I,G)=>I.localeCompare(G)),U=D.filter(I=>!I.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:U.length===0?"ok":"warn",ok:U.length===0,details:{checked_item_files:a.paths.length,checked_history_streams:s.files.length,counts:{item_unreadable:a.unreadable.length,item_conflict_markers:a.conflictMarkers.length,item_parse_failures:a.parseFailures.length,history_unreadable:s.unreadable.length,history_conflict_markers:s.conflictMarkers.length,history_invalid_json:s.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:h===null||h.status==="ok"?0:h.missing_keys.length+h.drifted_keys.length,merge_fence:p.count,ignored_merge_artifacts:f.rules.length,pending_merge_decisions:x.length,lossless_merge_receipts:$.length,invalid_merge_receipt_evidence:y.invalid_evidence_count,missing_merge_receipt_history_references:k.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.acceptedDispositionCount},item_unreadable:a.unreadable,item_conflict_markers:a.conflictMarkers,item_parse_failures:a.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,...WA(o),hierarchy_integrity:{...l,relations:Ge(l.relations,vp)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:h===null?null:{...h,required:i},merge_fence:p.audit,ignored_merge_artifacts:f.rules,pending_merge_decision_items:[...new Set(x.map(I=>I.item_id))].sort((I,G)=>I.localeCompare(G)),lossless_merge_receipt_items:[...new Set($.map(I=>I.item_id))].sort((I,G)=>I.localeCompare(G)),invalid_merge_receipt_evidence_details:y.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:y.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:k.slice(0,us),missing_merge_receipt_history_reference_details_truncated:k.length>us}},warnings:D,gitWorkspaceRoot:m,pendingMergeReceipts:E}}function JA(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function VA(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:JA(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function KA(e,t){return X(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function YA(e){let t=X(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function XA(e){return X(e.reason)??X(e.error)??X(e.message)}function bc(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function ZA(e){let t=[],n=[],r=[];e.forEach((o,a)=>{let s=KA(o.definition,a),c=YA(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:s,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:s,status:c,reason:XA(o.definition)});return}n.push({layer:o.layer,name:o.name,id:s,status:c})}),t.sort(bc),n.sort(bc),r.sort(bc);let i=[...r.map(o=>`extension_migration_failed:${o.layer}:${o.name}:${o.id}`),...n.map(o=>`extension_migration_pending:${o.layer}:${o.name}:${o.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function Rg(e,t,n,r,i,o,a,s,c){let d=[...new Set(e)].sort((y,w)=>y.localeCompare(w)),l=[...new Set(d.map(y=>Rc(y)))].sort((y,w)=>y.localeCompare(w)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=d.map(Ar).filter(y=>y!==void 0),h=Hs(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${oi.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):a.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:o,unmanaged_loaded_extension_count:a.length,unmanaged_loaded_extensions:a,unmanaged_expected_extension_count:s.length,unmanaged_expected_extensions:s,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function QA(e,t,n){let r=await Vs(Qe(e)),i=await et({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),o=i.loaded.map(S=>VA(S)),a=await cp(i.loaded,Qe(e)),s=await tt({...i,loaded:i.loaded}),[c,d]=await Promise.all([be(i.roots.project),be(i.roots.global)]);await Js(e,s.registrations.migrations);let l=ZA(s.registrations.migrations),u={failed:s.failed,warnings:s.warnings,hook_counts:s.hook_counts,command_override_count:s.command_override_count,command_handler_count:s.command_handler_count,parser_override_count:s.parser_override_count,preflight_override_count:s.preflight_override_count,service_override_count:s.service_override_count,renderer_override_count:s.renderer_override_count,registration_counts:s.registration_counts,registrations:s.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},m=new Set(c.state.entries.map(S=>Xn(S.name))),f=new Set(d.state.entries.map(S=>Xn(S.name))),p=[...new Map(i.loaded.filter(S=>!(S.layer==="project"?m:f).has(Xn(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,b)=>{let D=`${S.layer}:${S.name}`,U=`${b.layer}:${b.name}`;return D.localeCompare(U)}),h=p.map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),y=p.filter(S=>Ec(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=p.filter(S=>!Ec(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],k=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...a.warnings],E=Hr(k),x=Ur(),$=Rg(k,i.failed.length,s.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,y,w);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...i,loaded:o,warnings:k,activation:u,author_manifest:r,triage:$,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:E,host_version_census:a}},warnings:k}}function xc(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=bp(e,Eg);return{values:n.values,truncated:n.truncated,total:e.length}}function jo(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function eC(){let e=Wu();return e.source_context_source==="env_override"?e.source_context:null}function Ag(e){let t=0,n=0,r=0,i=0,o=0;for(let a of e.split(`
68
+ `)){let s=a.trim();if(s.length!==0){r+=1;try{let c=JSON.parse(s);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,o=Math.max(o,d),d>=Sg&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:o}}function tC(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function bg(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function nC(e,t){let n=Pa(e.telemetry.endpoint).trim();return!t||!e.telemetry.enabled||n.length===0||La().telemetry_disabled?void 0:{attempted:!0,...await Cg(n)}}function rC(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,o=n.last_failed_flush_at,a=o&&(!i||o>i),s=!i,c=t.validEntries>=MA;return(a||s||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function iC(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function oC(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Ju?[`telemetry_schema_version_behind:${t}`]:[]}function aC(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function sC(){return{...La(),pm_no_telemetry:jo("PM_NO_TELEMETRY"),telemetry_otel_disabled:jo("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:jo("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:eC()}}function cC(e,t){return e.telemetry.enabled&&t.validEntries>0}function dC(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}function kg(e){try{return decodeURIComponent(e)}catch{return e}}async function Cg(e){let t=e,n={};try{let r=new URL(e);r.pathname="/healthz",r.search="",r.hash="",(r.username.length>0||r.password.length>0)&&(n.authorization=`Basic ${Buffer.from(`${kg(r.username)}:${kg(r.password)}`).toString("base64")}`,r.username="",r.password=""),t=r.toString()}catch{}try{let r=await fetch(t,{method:"GET",headers:n,signal:AbortSignal.timeout(NA)});return{probe_url:An(t),ok:r.ok,status:r.status,max_schema_version:(()=>{for(let i of jA){let o=r.headers.get(i)?.trim();if(o&&o.length>0)return o}})()}}catch(r){return{probe_url:An(t),ok:!1,error:r instanceof Error?qu(r.message.replaceAll(t,An(t))):"probe_failed"}}}async function lC(e,t){let n=bg(await B(e)),r=e===t?n:bg(await B(t));return{runtimeState:n.runtimeState,spanState:r.runtimeState,stateParseFailed:n.stateParseFailed||r.stateParseFailed}}async function uC(e){let t=ci(process.cwd()),n=await T(t),r=me.join(me.dirname(me.join(t,PA)),Da("events.jsonl")),i=me.join(t,LA),o=me.join(me.dirname(i),Da("state.json")),a=await B(r),s=a!==null,c=a?Buffer.byteLength(a,"utf8"):0,d=a?Ag(a):tC(),{runtimeState:l,spanState:u,stateParseFailed:m}=await lC(o,i),f=Pa(n.telemetry.endpoint).trim(),p=An(f),h=await nC(n,e.checkTelemetry),y=[];m&&y.push("telemetry_state_invalid_json"),y.push(...rC(n,d,l),...iC(h),...oC(h),...aC(n,u));let w=cC(n,d),v=typeof u.pending_otel_spans=="number"?u.pending_otel_spans:0;return{check:{name:"telemetry",status:y.length===0?"ok":"warn",ok:y.length===0,details:{enabled:n.telemetry.enabled,capture_level:n.telemetry.capture_level,endpoint:p,global_pm_root:t,queue_path:r,queue_exists:s,queue_entries:d.validEntries,queue_draining:dC(w,y),queue_invalid_rows:d.invalidRows,queue_rows_total:d.totalRows,queue_size_bytes:c,queue_high_retry_entries:d.highRetryEntries,queue_high_retry_threshold:Sg,queue_max_attempts:d.maxAttempts,runtime_state_path:o,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:v,last_otel_attempt_at:u.last_otel_attempt_at??null,last_otel_success_at:u.last_otel_success_at??null,last_otel_failure_at:u.last_otel_failure_at??null,last_otel_failure_error:u.last_otel_failure_error??null,endpoint_probe:h??{attempted:!1},env_overrides:sC()}},warnings:y}}async function mC(e){let t;try{t=await Wp(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,...t.owner_dead_lock_samples?{owner_dead_lock_samples:t.owner_dead_lock_samples,recovery_command:"pm gc --scope locks"}:{},unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function pC(e){let t="metadata",n=e.items,r=await Qt(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),o=[],a=[];if(i.length>0){n=await ht(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Qt(e.pmRoot,n),o=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,k)=>v.localeCompare(k));let w=new Set(o);a=i.filter(v=>!w.has(v))}let{missingStreams:s,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:f,workspaceStateMissing:p,workspaceStateUnreadable:h}=r,y=[...s.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),...f.map(w=>`history_drift_workspace_state_mismatch:${w}`),...p.map(w=>`history_drift_workspace_state_missing:${w}`),...h.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:o,resolved_false_positive_items:a,authoritative_item_source:i.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:s.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:p.length,workspace_state_unreadable:h.length},missing_streams:s,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:p,workspace_state_unreadable:h}},warnings:y}}function fC(e,t){let n=Ni(e),r=fr(n.settings),i=Fi(n.settings,t),o=r.active?Kt(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(r.active&&i.active)}}function hC(){return{refreshed:[],skipped:[],warnings:[]}}async function _C(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?hC():zu(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function gC(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&In(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function yC(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function wC(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Tg(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:Ta(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:Ta(r,e.vector_store?.adapter??null)}}function vC(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function bC(e,t,n){return e.enabled&&n.length>0&&t}async function kC(e,t,n,r,i){let o=fC(t,e),a=await Rn(e),s=o.semanticRuntimeAvailable?Ha(n,a.entries):[],c=await _C({pmRoot:e,snapshot:o,refreshPolicy:r,staleBefore:s}),d=await Rn(e),l=o.semanticRuntimeAvailable?Ha(n,d.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,m=gC({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:a,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),f=yC({ledgerBefore:a,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=xc(s,i),h=xc(l,i),y=bC(r,o.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:o.semanticRuntimeAvailable,compatibility_mode_auto_defaults:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:o.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:o.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:vC(r),...Tg(t,o),embedding_identity_changed:m,embedding_identity_before:a.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(a.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Eg,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:y,refresh_skipped_reason:wC(r,o.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:f}}function EC(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function $g(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new _("--check-only cannot be combined with --refresh-vectors",g.USAGE);if(n&&e.noRefresh===!0)throw new _("--no-refresh cannot be combined with --refresh-vectors",g.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var SC=new Set(["extensions","locks","search"]);function xC(e){let t=new Set(Nd.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(Md));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of SC)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,o)=>i.localeCompare(o)),optionalDirs:[...n].sort((i,o)=>i.localeCompare(o)),optionalDirSet:n}}async function IC(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:o}=xC(t),a=[],s=[],c=[];for(let d of[...r,...i]){let l=me.join(e,d);c.push(...await We({path:l,scope:"project"})),!await Ac(l)&&(o.has(d)?s.push(d):a.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:a,missingOptionalDirs:s,missingDirs:n?[...a,...s]:[...a],hookWarnings:c}}function Og(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=e.summary===!0||t,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function RC(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?ft(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):ht(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function kc(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function AC(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function CC(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function TC(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var Cc=e=>e.unknown_event_count??0,Tc=e=>e.actionable_unknown_event_count??Cc(e);function $C(e,t,n,r,i,o,a){let s=Cc(r),c=Tc(r),d=s>0,l=c>0,u=i.count>0||a!==void 0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...d?{author_attribution:r}:{},...i.count>0?{stale_in_progress:i}:{},...a===void 0?{}:{in_progress_work:a},...o.outcomes.length>0?{provenance_resolver_outcomes:o.outcomes}:{},...o.invalid_values.length>0?{provenance_invalid_values:o.invalid_values}:{},provenance_sample:o.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Dg(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function OC(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function DC(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function PC(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function Pg(e){let t=new Map;for(let[r,i]of Object.entries(e.remediationSources))for(let o of i)t.has(o)||t.set(o,r);let n=new Map(e.checks.map(r=>[r.name,r]));return e.warnings.map(r=>{let i=t.get(r)??"integrity",o=ws(r)?.code??Rc(r),a=n.get(i)?.details,s=typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{},c=Ar(r)??(o==="agent_guidance_outdated"?"pm init --agent-guidance add":o==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":s[o]),d=Ic(r,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:r,code:o,check:i,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function LC(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1&&vg(e.remediationMap),e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function NC(e){for(let t of e.checks){let n=vs(e.remediationSources[t.name]);LC({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount});for(let[r,i]of Object.entries(t.name==="storage"?e.storageRemediation:{}))Object.hasOwn(n,r)&&(n[r]=i);Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function MC(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(a=>typeof a=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(a=>Array.isArray(a)?a:[])),i=new Map;for(let a of e.pendingMergeReceipts){let s=i.get(a.item_id)??[];s.push(a),i.set(a.item_id,s)}let o=[];for(let a of n){if(r.has(a))continue;let s=i.get(a);if(!(!s||s.length===0))try{await Kr(a,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:s}},e.global),o.push(a)}catch{}}return[...new Set(o)].sort((a,s)=>a.localeCompare(s))}function jC(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function Lg(e,t={}){let n=M(process.cwd(),e.path);await re(n);let r=un(n),{settings:i,warnings:o}=await wu(n),a=[...new Set(o)],s=z(i,F()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=$g(t),m=await IC(n,s,c),f=EC(i),p=await uC({checkTelemetry:t.checkTelemetry===!0}),h=await QA(n,i,!!e.noExtensions),y=Og(t),w=[],v=await RC({pmRoot:n,settings:i,typeRegistry:s,skipPolicy:y,itemReadWarnings:w}),k=v,E=to(_e(i.schema),v),x=[...(await $p({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(fe=>fe.startsWith("agent_guidance_")),...f,...no(E)],$=y.skipDrift?{warnings:[]}:await hu({pmRoot:n,settings:i,itemIds:v.map(fe=>fe.id),commandLabel:"health"}),S=await UA(n,i.history.compact_policy,await FA(n)),b=await Er(n,20,t.verboseAuthorEvents===!0),D=Tc(b),U=D>0?[`history_unknown_author_events:${D}`]:[],I=_e(i.schema),G=await Gu(n,v,{in_progress_status:I.in_progress_status,status_registry:I,threshold_hours:i.mutation_guard.stale_in_progress_hours}),Re=Dg(G.stale),Fe=_p(G,{in_progress:I.in_progress_status,open:I.open_status},Ai(e)),se=[...Re.warnings,...Fe.warnings],At=await pp(n),lt=At.warnings,Ye=await mC(n),N=y.skipIntegrity&&!l?{...kc("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await BA(n,s.type_to_folder,i.schema,i,l,v),H=y.skipDrift?kc("history_drift"):await pC({pmRoot:n,items:k,settings:i,typeRegistry:s,itemReadWarnings:w}),Ct=[...new Set(w)],sn=await MC({gitWorkspaceRoot:N.gitWorkspaceRoot,pendingMergeReceipts:N.pendingMergeReceipts,historyDriftCheck:H,global:e});jC(H,sn),wg(H,await yg(H,e,n));let cn=y.skipVectors?kc("vectorization"):await kC(n,i,k,u,t.verboseStaleItems===!0),dn=[AC(r,i,a),CC(m,c),TC(x,E),p.check,h.check,$C(v,i,S,b,Re.scan,At,Fe.details),Ye.check,N.check,H.check,cn.check],sa=OC({directoryState:m,normalizedSettingsReadWarnings:a,settingWarnings:x,normalizedItemReadWarnings:Ct,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:$.warnings,historySummary:S,authorAttributionWarnings:U,staleInProgressWarnings:se,provenanceWarnings:lt,locksCheck:Ye,integrityCheck:N,historyDriftCheck:H,vectorizationCheck:cn}),$d=PC({directoryState:m,normalizedSettingsReadWarnings:a,settingWarnings:x,normalizedItemReadWarnings:Ct,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:$.warnings,historySummary:S,authorAttributionWarnings:U,staleInProgressWarnings:se,provenanceWarnings:lt,locksCheck:Ye,integrityCheck:N,historyDriftCheck:H,vectorizationCheck:cn});NC({checks:dn,remediationSources:$d,historyDriftedCount:DC(H),overThresholdCount:S.over_threshold.length,storageRemediation:Fe.remediation});let ca=sa.filter(fe=>!Ic(fe,l)),da=Pg({warnings:sa,checks:dn,remediationSources:$d,requireMergeDrivers:l}),Zw=new Set(da.filter(fe=>fe.severity==="gate_failing").map(fe=>fe.check)),Qw=new Set(da.map(fe=>fe.check));for(let fe of dn)fe.ok=!Zw.has(fe.name),Qw.has(fe.name)&&(fe.status="warn");let ev={ok:ca.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&ca.length>0?g.GENERIC_FAILURE:0},checks:dn,warnings:sa,findings:da,failed_because:ca,generated_at:C()};return fs(ev,t,y.summaryMode)}var T2={buildHierarchyIntegrityWarnings:Ig,buildExtensionHealthTriageSummary:Rg,buildHealthFindings:Pg,buildCapabilityContractMetadata:Ur,buildStaleInProgressHealthSummary:Dg,buildVectorizationProviderDetails:Tg,collectUnknownCapabilityGuidance:Hr,isAdvisoryHealthWarning:Ic,isDirectory:Ac,isExpectedUnmanagedExtension:Ec,listItemDocumentPaths:xg,normalizeEndpointForDisplay:An,normalizeExtensionNameForMatch:Xn,parseTelemetryQueue:Ag,probeTelemetryEndpointHealth:Cg,projectHealthResult:fs,resolveActionableUnknownAuthorEventCount:Tc,resolveHealthSkipPolicy:Og,resolveUnknownAuthorEventCount:Cc,resolveVectorRefreshPolicy:$g,selectStaleItemDetail:xc,summarizeHealthCheckDetails:ms,summarizeExtensionList:xr,summarizeRecordList:Ge,summarizeStringList:q,telemetryEnvFlagEnabled:jo,warningCode:Rc};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a07d2f98-7c1d-5d0a-be70-5181ed0f7b4f")}catch{}})();function Ng(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!em(e,t).ok)return{reason:"unverified_history"};let r=Pt(),i={reason:"no_proven_transition"};for(let[o,a]of e.entries()){let s=n.has(String(r.metadata.status));r=bu(r,a.patch,o+1,a.op),n.has(String(r.metadata.status))?s||(i=["create","close","cancel","update","update_audit"].includes(a.op)&&Ot(a.ts)?{timestamp:a.ts,source_index:o+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function Mg(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function jg(e,t,n,r,i){let o=Mg(n),a=t.filter(d=>o.has(d.status)&&!d.closed_at),s=[],c=[];for(let d of r?a:[]){let l;try{let u=await He(ut(e,d.id),d.id),{body:m,...f}=d;l=Ng(u,{metadata:f,body:m},o)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}s.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:a.length,missing_closed_at_item_ids:a.slice(0,i).map(d=>d.id),missing_closed_at_item_ids_truncated:a.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:s.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...a.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:s,warnings:a.length>0?[`validate_metadata_missing_closed_at:${a.length}`]:[]}}async function Fg(e,t){let n=M(process.cwd(),t.path),r=await T(n),i=_e(r.schema);await _t({pmRoot:n,settings:r,id:e.item_id,op:"update",author:W(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(o){if(o.metadata.closed_at)return{changedFields:[]};let a=await He(ut(n,o.metadata.id),o.metadata.id),s=Mg(i),c=Ng(a,o,s);if(!("timestamp"in c)||c.timestamp!==e.value)throw new _("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",g.GENERIC_FAILURE);return o.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function FC(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function Hg(e){return`${e.item_id} ${e.link_kind}`}function Ug(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=FC(i.classification,r.classification),i.owners.set(Hg(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[Hg(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(o=>{let a=t(o.item_id);return{id:o.item_id,type:a?.type??"Unknown",title:a?.title??"",status:a?.status??"",field:o.link_kind}}).sort((o,a)=>{let s=o.id.localeCompare(a.id);return s!==0?s:o.field.localeCompare(a.field)})}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00f8052d-480b-5e38-86cf-4574a8ad1e92")}catch{}})();function zg(e,t,n,r,i=40){let o=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,a=new Map(t.map(d=>[d.path,d])),s={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=Ug(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=yi(f.status,r)??f.status;r.terminal_statuses.has(p)?(u.push(f),p===r.close_status&&(s.legacy_closed_missing_linked_links_count+=1)):l.push(f)}s.missing_linked_links_count+=d.items.length,s.active_missing_linked_links_count+=l.length,s.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(s.active_missing_linked_paths_count+=1);let m=a.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,o),items_truncated:d.items.length>o}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),s.missing_linked_path_rows_count=c.length,s.missing_linked_path_rows=c.slice(0,o),s.missing_linked_path_rows_truncated=c.length>o,s}import Zn from"node:fs/promises";import Qn 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]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function HC(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let o;try{o=await Zn.readdir(Qn.join(e,i))}catch{return}for(let a of o)for(let s of sr)if(a.toLowerCase().endsWith(s)){r.push({relativePath:`${i}/${a}`,id:a.slice(0,-s.length)});break}})),r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath))}function UC(e,t){let{id:n,relativePath:r,liveItemIds:i,out:o}=e,a=Pe(t);if(a){o.conflictMarkers.push({id:n,path:r,line:a.line,detail:`unresolved merge conflict marker ${a.marker}`});return}let s=zC(e,t);s!==null&&(s.op==="delete"&&i.has(n)&&o.resurrected.push({id:n,deleted_at:typeof s.ts=="string"?s.ts:"",deleted_by:typeof s.author=="string"?s.author:""}),s.op==="history_repair"&&Array.isArray(s.patch)&&s.patch.length>0&&(o.repairReconciliations+=1))}function zC(e,t){let{id:n,relativePath:r,out:i}=e,o=null,a=!1,s=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of s){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");o=d}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(o.op==="create"){if(a)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;a=!0}}return o}function $c(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 WC(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Zn.readdir(Qn.join(e,"history"))}catch{return n}for(let i of r.sort((o,a)=>o.localeCompare(a))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await Zn.readFile(Qn.join(e,"history",i),"utf8")}catch(a){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:$c("history stream",a)});continue}UC({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},o)}return n}function Wg(e){let t=Pe(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 qC(e){let t=[],n=0,r=null;try{r=await B(un(e))}catch(o){n+=1,t.push({path:"settings.json",detail:$c("configuration file",o)})}if(r!==null){n+=1;let o=Wg(r);o!==null&&t.push({path:"settings.json",detail:o})}let i;try{i=await Zn.readdir(Qn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of i.sort((a,s)=>a.localeCompare(s))){if(!o.endsWith(".json"))continue;n+=1;let a;try{a=await Zn.readFile(Qn.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:$c("configuration file",c)});continue}let s=Wg(a);s!==null&&t.push({path:`schema/${o}`,detail:s})}return{scanned:n,unparseable:t}}async function qg(e,t,n,r={}){let i=await HC(e,n),o=new Set(i.map(u=>u.id)),a=new Map;for(let u of i){let m=a.get(u.id);m===void 0?a.set(u.id,[u.relativePath]):m.push(u.relativePath)}let s=[...a.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).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=Qn.join(e,u.relativePath);return Dt(await Zn.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),d=await WC(e,o),l=await qC(e);return{item_files_on_disk:i.length,item_ids_on_disk:o.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:s,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import _d from"node:fs/promises";import{realpathSync as L$}from"node:fs";import{execFile as N$}from"node:child_process";import Ie from"node:path";import{promisify as M$}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]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();var GC=["metadata","resolution"],Oc=["metadata","resolution","estimates","timestamps","lifecycle"],BC="completed";function Dc(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Gg(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Bg(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Gg(n.close_reason)??BC;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Dc(r)}`,gate:"resolution"})}return t}function Jg(e){let t=[];for(let n of e){let r=Gg(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 ${Dc(r)}`,gate:"metadata"})}return t}function Vg(e,t){return e.map(n=>{let r=gu(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 Kg(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 Yg(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 ${Dc(n.path)}`})}return t}function Xg(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 _(`--fix-scope values must not be empty. Supported values: ${Oc.join(", ")}.`,g.USAGE);return new Set(GC)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Oc.includes(i)){n.add(i);continue}throw new _(`Unknown --fix-scope value "${r}". Supported values: ${Oc.join(", ")}.`,g.USAGE)}return n}function Zg(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 Yr(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]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();var JC=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function VC(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=JC.exec(n);if(!r)return null;let i=r[1],o=i.toUpperCase(),a=i.slice(0,i.lastIndexOf("-")),s=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${o}`)||d.includes(`ISSUE CODE \`${o}\``)||d.includes(`\`${o}\``)||d.includes(`[${o}]`);return a===a.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||s.has(a.toUpperCase())||l?o:null}function Qg(e){return typeof e=="string"&&e.trim().length>0}function KC(e){let t=new Set(e.map(a=>a.id.toLowerCase())),n=new Map,r=new Map;for(let a of e){let s=a.id.toLowerCase(),c=new Set([...a.parent===null?[]:[a.parent.toLowerCase()],...a.derivations].filter(d=>d!==s&&t.has(d)));n.set(s,c);for(let d of c){let l=r.get(d)??[];l.push(s),r.set(d,l)}}let i=[...[...n].filter(([,a])=>a.size===0).map(([a])=>a)],o=new Set;for(let a=0;a<i.length;a+=1)for(let s of r.get(i[a])??[]){let c=n.get(s);c.delete(i[a]),c.size===0&&(o.add(s),i.push(s))}return e.filter(a=>!o.has(a.id.toLowerCase()))}function ey(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||Qg(i.duplicate_of))continue;let o=VC(i.title,{...t,evidenceText:i.body});if(o===null)continue;let a=n.get(o);a||(a=[],n.set(o,a)),a.some(s=>s.id===i.id)||a.push({id:i.id,title:i.title,parent:Qg(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(s=>["discovered_from","supersedes","incident_from"].includes(s.kind)).map(s=>s.id.trim().toLowerCase()).filter(s=>s!==i.id.toLowerCase())})}let r=[];for(let[i,o]of n){if(o.length<2)continue;let a=KC(o);if(a.length<2)continue;let s=[...a].sort((c,d)=>c.id.localeCompare(d.id));r.push({code:i,count:s.length,ids:s.map(c=>c.id),titles:s.map(c=>c.title)})}return r.sort((i,o)=>i.code.localeCompare(o.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]="3c32504d-254c-5156-a41f-8ffd8e49107f")}catch{}})();function ty(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,o)=>i.localeCompare(o))){let i=t.get(r),o={};for(let a of[...i.keys()].sort((s,c)=>s.localeCompare(c)))o[a]=i.get(a);n[r]=o}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c577e41b-6642-554a-bc4d-0c22170c1e24")}catch{}})();function ny(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function ry(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let o of t){let a=ny(o);if(a.length===0)continue;let s=i.get(a);s?s.push(o):i.set(a,[o])}return e.map(o=>{if(o.includes(",")||o.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:o,classification:"malformed",candidates:[],candidates_truncated:!1};let a=(i.get(ny(o))??[]).filter(s=>s!==o).sort((s,c)=>s.localeCompare(c));return a.length===0?{path:o,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:o,classification:"moved",candidates:a.slice(0,r),candidates_truncated:a.length>r}})}function iy(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var YC=/^[a-z][a-z0-9+.-]+:\/\//i;function Xr(e){return YC.test(e.trim())}import vT from"node:fs/promises";import Oe from"node:path";import{readdir as sy,realpath as cy,stat as dy}from"node:fs/promises";import Ee 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]="427dd932-a013-557c-b3d8-5d7bb042e88c")}catch{}})();var XC=4096,ZC=32,QC=1e3,eT=5e4,tT={nodes:1e4,edges:4e4,stateIds:2e6},rn=47,er=class extends Error{},nT=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function ly(){return new _("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",g.USAGE)}function rT(e,t){let n=t+1;for((e[n]==="!"||e[n]==="^")&&(n+=1),e[n]==="]"&&(n+=1);n<e.length;){let r=e[n];if(r==="\\")n+=2;else if(r==="["&&e[n+1]===":"){let i=e.indexOf(":",n+2);i===-1||e[i+1]!=="]"?n+=1:n=i+2}else{if(r==="]")return n+1;n+=1}}return-1}function iT(e,t,n){let r=e[t];if(r==="{")return{index:t,kind:"{"};if(r!=="(")return;let i=e[t-1];return i!==void 0&&"@?*+!".includes(i)&&!uy(e,t-1)?{index:t-1,kind:"("}:n.some(o=>o.kind==="(")?{index:t,kind:"plain"}:void 0}function oT(e,t,n,r,i){let o=e[t],a=n.at(-1);if(o===")"&&a?.kind==="plain"){n.pop(),i.set(a.index,t);return}let s=o==="}"?"{":o===")"?"(":void 0;if(!(s===void 0||a?.kind!==s)&&(n.pop(),r.set(a.index,t),e[a.index]==="!"))throw ly()}function aT(e){let t=new Map,n=new Map,r=new Map,i=[],o=0;for(;o<e.length;){if(e[o]==="\\"){o+=2;continue}let a=e[o]==="["?rT(e,o):-1;if(a!==-1){n.set(o,a),o=a;continue}let s=iT(e,o,i);if(s!==void 0?i.push(s):oT(e,o,i,t,r),i.length>ZC)throw new er;o+=1}return{closers:t,brackets:n,groups:r}}function uy(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r-=1)n+=1;return n%2===1}function nn(e){return Array.from(e,t=>({kind:"char",value:t.codePointAt(0)}))}function sT(e){let t=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(e),n=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(e);if(t===null&&n===null)return;let[r,i]=t!==null?[Number(t[1]),Number(t[2])]:[n[1].codePointAt(0),n[2].codePointAt(0)];if(Math.abs(i-r)+1>QC)throw new er;let o=r<=i?1:-1,a=[];for(let s=r;s!==i+o;s+=o)a.push(t!==null?String(s):String.fromCodePoint(s));return a}function cT(e,t){if(e[t]!=="["||e[t+1]!==":")return;let n=e.indexOf(":",t+2);if(!(n===-1||e[n+1]!=="]"))return{ranges:nT.get(e.slice(t+2,n).join(""))??[],next:n+2}}function oy(e,t,n){let r=e[t]==="\\"&&t+1<n;return{codePoint:e[r?t+1:t].codePointAt(0),next:t+(r?2:1)}}function dT(e,t,n){let r=[];for(let i=t;i<n;i+=1)e[i]==="\\"&&i+1<n&&(i+=1),r.push(e[i].codePointAt(0));return r}function lT(e,t,n){let r=t+1,i=e[r]==="!"||e[r]==="^";i&&(r+=1);let o=[],a=n-1;for(;r<a;){let s=cT(e,r);if(s!==void 0){o.push(...s.ranges),r=s.next;continue}let c=oy(e,r,a);if(r=c.next,e[r]!=="-"||r+1>=a){o.push([c.codePoint,c.codePoint]);continue}let d=oy(e,r+1,a);r=d.next,c.codePoint<=d.codePoint&&o.push([c.codePoint,d.codePoint])}return{kind:"class",negated:i,ranges:o,literal:dT(e,t,n)}}var Pc=class{chars;closers;brackets;groups;constructor(t,n){this.chars=t,this.closers=n.closers,this.brackets=n.brackets,this.groups=n.groups}alternatives(t,n,r){let i=[],o=t;for(;;){let{nodes:a,stop:s}=this.sequence(o,n,r);if(i.push(a),s>=n)return i;o=s+1}}sequence(t,n,r){let i=[],o=t;for(;o<n;){if(this.chars[o]===r)return{nodes:i,stop:o};let a=this.token(o,n);i.push(...a.nodes),o=a.next}return{nodes:i,stop:n}}token(t,n){let r=this.chars[t];if(r==="\\")return{nodes:nn(t+1<n?this.chars[t+1]:"\\"),next:t+2};let i=this.closers.get(t);if(i!==void 0)return{nodes:r==="{"?this.brace(t,i):this.extglob(r,t,i),next:i+1};let o=this.groups.get(t);if(o!==void 0)return{nodes:[...nn("("),...this.sequence(t+1,o,void 0).nodes,...nn(")")],next:o+1};let a=this.brackets.get(t);return a!==void 0?{nodes:[lT(this.chars,t,a)],next:a}:r==="*"?this.stars(t,n):{nodes:r==="?"?[{kind:"any"}]:nn(r),next:t+1}}extglob(t,n,r){let i=this.alternatives(n+2,r,"|");return[t==="@"?{kind:"alt",options:i}:{kind:"repeat",optional:t!=="+",many:t!=="?",options:i}]}brace(t,n){let r=this.alternatives(t+1,n,",");if(r.length>1)return[{kind:"alt",options:r}];let i=sT(this.chars.slice(t+1,n).join(""));return i!==void 0?[{kind:"alt",options:i.map(nn)}]:[...nn("{"),...r[0],...nn("}")]}stars(t,n){let r=1;for(;this.chars[t+r]==="*"&&t+r<n&&!this.closers.has(t+r);)r+=1;if(r!==2)return{nodes:[{kind:"star"}],next:t+r};let i=t+r<n&&this.chars[t+r]==="/";return{nodes:[{kind:"globstar",slash:i}],next:t+r+(i?1:0)}}},Lc=["segment","inside"],Fo={kind:"any"};function Nc(e){return Lc.flatMap(t=>e[t]===void 0?[]:[e[t]])}var Mc=class{states=[];add(){if(this.states.length>=eT)throw new er;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(t,n,r=!0){this.states[t].epsilon.push(n),r&&this.states[t].syntactic.push(n)}consume(t,n,r){let i=this.add();for(let o of Nc(t))this.states[o].edges.push({test:n,to:i});return{[r]:i}}join(t){let n={};for(let r of Lc){let i=t.flatMap(o=>o[r]===void 0?[]:[o[r]]);if(i.length===1&&(n[r]=i[0]),i.length>1){let o=this.add();for(let a of i)this.epsilon(a,o);n[r]=o}}return n}feed(t,n){for(let r of Lc)t[r]!==void 0&&this.epsilon(t[r],n[r])}build(t,n){let r=n;for(let i of t)r=this.node(i,r);return r}alternation(t,n){return this.join(t.map(r=>this.build(r,n)))}star(t){let n=this.add();for(let r of Nc(t))this.epsilon(r,n,!1);return this.states[n].edges.push({test:Fo,to:n}),{inside:n}}segments(t){let n=this.add();this.epsilon(t,n,!1);let r=this.add();return this.states[n].edges.push({test:Fo,to:r}),this.states[r].edges.push({test:Fo,to:r},{test:{kind:"char",value:rn},to:n}),n}globstar(t,n){if(n){let i=[];return t.segment!==void 0&&i.push({segment:this.segments(t.segment)}),t.inside!==void 0&&i.push(this.consume(this.star({inside:t.inside}),{kind:"char",value:rn},"segment")),this.join(i)}let r=this.star(t);return t.segment!==void 0&&this.globstars.push({continuation:r.inside,entry:t.segment}),r}globstars=[];syntacticClosure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let i of this.states[r.pop()].syntactic)n.has(i)||(n.add(i),r.push(i));return n}resolveGlobstars(t){for(let{continuation:n,entry:r}of this.globstars){let i=this.syntacticClosure([n]);if(i.has(t)){let s=this.add();this.epsilon(r,s,!1),this.states[s].edges.push({test:{kind:"all"},to:s}),this.epsilon(s,t,!1)}let o=new Set;for(let s of i)for(let{test:c,to:d}of this.states[s].edges)my(c,rn)&&o.add(d);if(o.size===0)continue;let a=this.segments(r);for(let s of o)this.epsilon(a,s,!1)}}repeat(t,n){if(!t.many)return this.join([n,this.alternation(t.options,n)]);let r={segment:this.add(),inside:this.add()};return this.feed(t.optional?n:this.alternation(t.options,n),r),this.feed(this.alternation(t.options,r),r),r}node(t,n){switch(t.kind){case"char":return this.consume(n,{kind:"char",value:t.value},t.value===rn?"segment":"inside");case"any":return this.consume(n,Fo,"inside");case"star":return this.star(n);case"globstar":return this.globstar(n,t.slash);case"class":return this.join([this.consume(n,{kind:"class",negated:t.negated,ranges:t.ranges},"inside"),this.build(t.literal.map(r=>({kind:"char",value:r})),n)]);case"alt":return this.alternation(t.options,n);case"repeat":return this.repeat(t,n)}}};function my(e,t){switch(e.kind){case"char":return e.value===t;case"any":return t!==rn;case"all":return!0;case"class":return t!==rn&&e.ranges.some(([n,r])=>t>=n&&t<=r)!==e.negated}}var jc=class{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(t,n,r,i){this.nfa=t,this.acceptState=r,this.limits=i,this.start=this.node(this.closure([n]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let i of this.nfa.states[r.pop()].epsilon)n.has(i)||(n.add(i),r.push(i));return[...n].sort((i,o)=>i-o)}node(t){let n=t.join(","),r=this.nodes.get(n);if(r!==void 0)return r;(this.nodes.size>=this.limits.nodes||this.stateIds+t.length>this.limits.stateIds)&&this.reset();let i={id:this.nextId,generation:this.generation,states:t,accepting:t.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(n,i),this.stateIds+=t.length,i}step(t,n){let r=`${t.id}:${n}`,i=t.generation===this.generation?this.edges.get(r):void 0;if(i!==void 0)return i;let o=[];for(let s of t.states)for(let{test:c,to:d}of this.nfa.states[s].edges)my(c,n)&&o.push(d);let a=this.node(this.closure(o));return this.edges.size>=this.limits.edges&&this.reset(),t.generation===this.generation&&this.edges.set(r,a),a}advance(t,n){let r=t;for(let i of n){if(r.states.length===0)return r;r=this.step(r,i.codePointAt(0))}return r}};function uT(e,t=tT){let n=Array.from(e),r=new Pc(n,aT(n)).sequence(0,n.length,void 0).nodes,i=new Mc,o=i.add(),a=i.add();for(let s of Nc(i.build(r,{segment:o})))i.epsilon(s,a);return i.resolveGlobstars(a),new jc(i,o,a,t)}function mT(e){return!/[*?[\]{}()!@+\\]/u.test(e)}function ay(e){return e.isFile()?"file":e.isDirectory()?"directory":"other"}async function pT(e,t,n){if(!n.isSymbolicLink())return{kind:ay(n),real:Ee.join(t,n.name)};try{let r=await cy(Ee.join(e,n.name));return{kind:ay(await dy(r)),real:r}}catch{return}}async function py(e,t,n,r,i,o,a){let s;try{s=await sy(t,{withFileTypes:!0})}catch{return}for(let c of s){let d=e.advance(i,c.name);if(d.states.length===0)continue;let l=await pT(t,n,c);if(l===void 0)continue;let u=Ee.posix.join(r,c.name);if(l.kind==="file"&&d.accepting&&a.push(u),l.kind!=="directory")continue;let m=e.step(d,rn);m.states.length===0||o.has(l.real)||(o.add(l.real),await py(e,Ee.join(t,c.name),l.real,u,m,o,a),o.delete(l.real))}}function fT(e){let t=Ee.posix.normalize(e);return/^\/\/[^/]/u.test(e)?`/${t}`:t}function hT(e){let t=e;for(;t.length>1&&t.endsWith("/")&&!uy(t,t.length-1);)t=t.slice(0,-1);return t}async function fy(e,t){return(await sy(e).catch(()=>[])).includes(t)}async function hy(e,t){let n=e,r=0;for(;t[r]==="..";)n=Ee.dirname(n),r+=1;for(;r<t.length;r+=1){if(!await fy(n,t[r]))return!1;n=Ee.join(n,t[r])}return!0}function _y(e,t=process.platform){return e.startsWith("/")||t==="win32"&&/^[A-Za-z]:\//u.test(e)}async function _T(e,t){let n=Ee.resolve(t,e),r=await dy(n).catch(()=>{});if(r===void 0||!r.isFile())return[];let i=_y(e);return(i?await fy(Ee.dirname(n),Ee.basename(n)):await hy(t,e.split("/")))?[i?n.replaceAll("\\","/"):Ee.posix.normalize(e)]:[]}function gT(e,t){let n=e.split("/"),r=0;for(;r<n.length&&mT(n[r]);)r+=1;if(r===n.length)return;let i=r===0?"":`${n.slice(0,r).join("/")}/`,o=Ee.resolve(t,i),a=n.slice(r).join("/");if(_y(e))return{root:o,base:o.replaceAll("\\","/"),rest:a,prefix:[]};let s=Ee.posix.normalize(i===""?".":i).replace(/\/$/u,"");return{root:o,base:s==="."?"":s,rest:a,prefix:n.slice(0,r)}}function yT(e){try{return uT(e)}catch(t){if(t instanceof er)return;throw t}}async function gy(e,t){if(e.startsWith("!"))throw ly();if(Array.from(e).length>XC)return[];let n=hT(fT(e)),r=gT(n,t);if(r===void 0)return _T(n,t);let i=yT(r.rest);if(i===void 0||!await hy(t,r.prefix))return[];let o=await cy(r.root).catch(()=>{});if(o===void 0)return[];let a=[];return await py(i,r.root,o,"",i.start,new Set([o]),a),a.map(s=>wT(r.base,s))}function wT(e,t){return e.startsWith("//")?`/${Ee.posix.join(e.slice(1),t)}`:Ee.posix.join(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]="13ad37f7-4c20-57f1-840a-b2c25dcac090")}catch{}})();var Fc=["refuse","replace","append"],Uc="; ";function bT(e,t){if(e===void 0)return"refuse";let n=e.trim().toLowerCase();if(!Fc.some(r=>r===n))throw new _(`--note-conflict must be one of ${Fc.join(", ")}; got "${e}"`,g.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:e,required:`Pass --note-conflict ${Fc.join("|")}.`});if(!t)throw new _("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",g.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return n}function kT(e,t,n){if(t===void 0||t===e)return{note:e,outcome:"unchanged",conflict:!1};if(e===void 0)return{note:t,outcome:"note_added",conflict:!1};if(n==="replace")return{note:t,outcome:"note_replaced",conflict:!1};if(n==="append"){let r=Uc;return`${r}${e}${r}`.includes(`${r}${t}${r}`)?{note:e,outcome:"unchanged",conflict:!1}:{note:`${e}${Uc}${t}`,outcome:"note_appended",conflict:!1}}return{note:e,outcome:"unchanged",conflict:!0}}function ET(e){let t=e.conflicts[0],n=e.conflicts.length>1?` and ${e.conflicts.length-1} more`:"",r=e.retryArgs("append"),i=e.retryArgs("replace"),o=t.source==="stored"?`${e.itemId} already links ${e.noun} ${t.path} with the note "${t.existing_note}"${n}; the add was refused so that note is kept`:`The add names ${e.noun} ${t.path} on ${e.itemId} with two notes, "${t.existing_note}" and then "${t.requested_note}"${n}; the add was refused because they disagree`;return new _(o,g.CONFLICT,{code:"linked_artifact_note_conflict",item_id:e.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...r===void 0||i===void 0?{}:{nextSteps:[e.render(r),e.render(i)],recovery:{suggested_retry:e.render(r),suggested_retry_args:r}},details:{conflicts:e.conflicts.map(a=>({...a}))}})}var zc=["path","scope","note"],ST=["pattern","glob","path","scope","note"],xT=["path"],IT=["from","to"],RT=new Set(["note","scope"]);function yy(e){return JSON.parse(JSON.stringify(e))}function AT(e,t){let n=e.map(yy);return t.filter(r=>{let i=yy(r),o=n.findIndex(a=>ma(a,i));return o>=0&&n.splice(o,1),o<0})}function wy(e){let t=e.fullHistory?[...e.stored]:[...e.written],n=t.length<e.stored.length;return{entries:t,total_count:e.stored.length,returned_count:t.length,has_more:n,mutation_receipt:{changed_count:e.written.length,removed_count:e.removedCount,full_history_included:!n,...e.linkOutcomes&&e.linkOutcomes.length>0?{link_outcomes:[...e.linkOutcomes]}:{}},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function vy(e){let t=e??"project";if(!la.includes(t))throw new _(`Invalid scope "${e}". Valid scopes: ${la.join(", ")} (default: project).`,g.USAGE);return t}function Wc(e){if(e.startsWith("```")||e.includes(`
69
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||cu(e)}function CT(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function TT(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Wc(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let o=e.slice(t+2,-1).trim();if(o.length>0&&CT(o))return{path:o,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function Bc(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let o=TT(r);if(o!==void 0)return[o]}du(r,"--add",`${t} path`,Wc(r));let i=Wc(r)?mr(n,"--add"):{path:r};if(pr(i,"--add",zc),!i.path)throw new _(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return[{path:i.path,scope:vy(i.scope),note:i.note?.trim()||void 0}]}):[]}function $T(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=mr(n,"--add-glob");pr(r,"--add-glob",ST);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new _("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:i,scope:vy(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function OT(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=mr(n,"--remove"),i=Object.keys(r).filter(o=>RT.has(o.toLowerCase()));if(i.length>0)throw new _(`--remove identifies a linked artifact by path only and does not accept ${i.map(o=>`"${o}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,g.USAGE);if(pr(r,"--remove",xT),!r.path)throw new _("--remove key/value form requires path=<value>",g.USAGE);return r.path}return n}):[]}function DT(e){return e?e.map(t=>{let n=mr(t,"--migrate");pr(n,"--migrate",IT);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new _("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:r,to:i}}):[]}function tr(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 PT(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(o=>Wt(tr(o.path,n)))),i=[...new Set(t.map(o=>Wt(tr(o,n))).filter(o=>r.has(o)))].sort((o,a)=>o.localeCompare(a));if(i.length!==0)throw new _(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,g.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function Rt(e){return e.split(Oe.sep).join("/")}function qc(e,t,n=process.cwd()){let r=e.trim();if(Xr(r))return r;if(Oe.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return Rt(r.replaceAll("\\",Oe.sep));let i=Oe.relative(t,n);return i.startsWith(`..${Oe.sep}`)||i===".."||Oe.isAbsolute(i)?Rt(Oe.normalize(r)):Rt(Oe.relative(t,Oe.resolve(n,r)))}async function LT(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){if(Oe.resolve(n,i.pattern)===Oe.resolve(n))continue;let o=await gy(i.pattern,n),a=[...new Set(o.map(s=>qc(s,t,n)))].sort((s,c)=>s.localeCompare(c));for(let s of a)r.push({path:s,scope:i.scope,note:i.note})}return r}function NT(e,t,n){if(t===void 0)return e;if(!n)throw new _("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",g.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function Gc(e){return`${e.path}::${e.scope}`}function Jc(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function Vc(e){return[...new Map(e.map(t=>[Gc(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function MT(e,t=process.cwd()){let n=[...new Set(e)].sort((s,c)=>s.localeCompare(c)),r=[],i=[],o=[],a=[];for(let s of n){if(Xr(s)){a.push(s.trim());continue}let c=Oe.isAbsolute(s)?s:Oe.resolve(t,s);try{(await vT.stat(c)).isFile()?r.push(s):o.push(s)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&Xe(d)){i.push(s);continue}o.push(s)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:o,remote_references:a}}function jT(e,t,n,r){let i=0;for(let o=0;o<e.length;o+=1){let a=tr(e[o].path,r);a!==e[o].path&&(i+=1);let s=Wt(a);s!==e[o].path&&(e[o]={...e[o],path:s})}return{adds:t.map(o=>{let a=tr(o.path,r);return a!==o.path&&(i+=1),{...o,path:Wt(a)}}),removes:n.map(o=>Wt(tr(o,r))),count:i}}function Wt(e){return e.replaceAll("\\","/")}function Hc(e){return`${e.scope}\0${Wt(e.path)}`}function FT(e,t,n){let r=new Map(e.map(a=>[Hc(a),a.note])),i=new Map(t.map(a=>[Hc(a),a.note])),o=new Map;for(let a of n){let s=Hc(a);o.has(s)||o.set(s,{path:Wt(a.path),scope:a.scope,outcome:HT(r.has(s),r.get(s),i.get(s))})}return[...o.values()]}function HT(e,t,n){return e?n===t?"unchanged":t===void 0?"note_added":n?.startsWith(`${t}${Uc}`)?"note_appended":"note_replaced":"added"}function UT(e,t,n){let r=e.merged.findIndex(a=>a.path===t.path&&a.scope===t.scope),i=e.merged[r];if(i===void 0){e.merged.push(t),t.note!==void 0&&e.notedHere.add(t);return}let o=kT(i.note,t.note,n);if(o.conflict)e.conflicts.push({path:t.path,scope:t.scope,existing_note:i.note,requested_note:t.note,source:e.notedHere.has(i)?"this_write":"stored"});else if(o.note!==i.note){let a={...i,note:o.note};e.merged[r]=a,e.notedHere.add(a)}}function zT(e,t,n,r,i){let o=Vc(e),a={merged:[...o],notedHere:new Set,conflicts:[]};for(let d of t)UT(a,d,i);let{merged:s}=a,c=FT(o,s,t);if(n.length>0)for(let d=s.length-1;d>=0;d-=1)n.includes(s[d].path)&&s.splice(d,1);return{entries:r?s:Jc(s),outcomes:c,conflicts:a.conflicts}}async function by(e){let t=e.mutation?.entries??e.artifacts,n=e.options.validatePaths?e.artifacts:t,{counts:r,receipts:i}=VT(e.mutation);return{id:e.id,artifacts:t,changed:e.changed,count:t.length,...r,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed&&n.length>0?await MT(n.map(o=>o.path),e.workspaceRoot):void 0,...i}}function WT(e,t,n){let r=new Map;for(let o of t){let a=Gc(o);r.set(a,(r.get(a)??0)+1)}let i=0;for(let o of e){let a=Gc({...o,path:Wt(tr(o.path,n))}),s=r.get(a)??0;s>0?r.set(a,s-1):i+=1}return i}function qT(e,t){let n=/[\n\r]|^\s*[-*+`]/u.test(e)?[]:su(e),r=n.findIndex(l=>l.key?.toLowerCase()==="note");if(r<0)return;let i=n.slice(0,r).map(l=>l.raw.trim()),o=new Set(n.slice(0,r).map(l=>l.key?.toLowerCase())),a=[n[r].value],s;for(let l of n.slice(r+1)){let u=l.key?.toLowerCase();if((u==="path"||u==="scope")&&!o.has(u)){i.push(l.raw.trim()),o.add(u);continue}s??=l.key===void 0?void 0:{segment:l.text.trim(),key:l.key},a.push(l.text)}if(s===void 0)return;let c=a.join(",").trim(),d=[...i,`note=${JSON.stringify(c)}`].join(",");try{Bc([d],t)}catch{return}return{entry:d,note:c,...s}}function GT(e,t){return e.findIndex(n=>{try{return Bc([n],t),!1}catch{return!0}})+1}function Ho(e,t,n){return(t??[]).flatMap(r=>[e,n!==void 0&&r.trim()==="-"?`${n}=-`:r])}function ky(e){let{options:t}=e,n=e.noteConflict??t.noteConflict;return[...Ai(e.global),...e.guards.map(r=>`--expect-hash=${r}`),e.config.metadataKey,e.id,...Ho("--add",e.entries.map((r,i)=>i===e.position-1?e.rewritten:r),"path"),...Ho("--add-glob",e.resolved.addGlob,"pattern"),...Ho("--remove",e.resolved.remove,"path"),...Ho("--migrate",e.resolved.migrate),...t.note===void 0?[]:["--note",t.note],...n===void 0?[]:["--note-conflict",n],...e.config.supportsAppendStable&&t.appendStable===!0?["--append-stable"]:[],...t.validatePaths===!0?["--validate-paths"]:[],...t.fullHistory===!0?["--full-history"]:[],...t.author?["--author",t.author]:[],...t.message?["--message",t.message]:[],...t.force===!0?["--force"]:[]]}function BT(e){return zc.some(t=>t===e.toLowerCase())?`If "${e}" was meant as a key, give it once per entry.`:`If "${e}" was meant as a key, it is not one of: ${zc.join(", ")}.`}function JT(e){try{return Bc(e.entries,e.config.bareNoun)}catch(t){let n=e.entries,r=t,i=GT(n,e.config.bareNoun),o=qT(n[i-1],e.config.bareNoun);if(o===void 0)throw t;let a=Ia(e.pmRoot),s=a===void 0?void 0:ky({...e,entries:n,position:i,rewritten:o.entry,guards:a});throw new _(`--add read the note segment "${o.segment}" as a new key "${o.key}", so the ${e.config.bareNoun} link was refused (${r.message})`,g.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:n[i-1],required:`Retry with the note quoted so its commas stay prose (${s===void 0?`as ${o.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${BT(o.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...s===void 0?{}:{nextSteps:[K(s)]},details:{entry_index:i,misread_segment:o.segment,misread_key:o.key,note:o.note,rewritten_entry:o.entry,cause:r.context.code??"invalid_argument_value"},...s===void 0?{}:{recovery:{suggested_retry:K(s),suggested_retry_args:s}}})}}function VT(e){return e===void 0?{counts:{},receipts:{}}:{counts:{total_count:e.total_count,returned_count:e.returned_count,has_more:e.has_more},receipts:{mutation_receipt:e.mutation_receipt,omission_receipt:e.omission_receipt}}}async function KT(e){let{settings:t,config:n}=e,r=await ge(e.pmRoot,e.id,t.id_prefix,t.item_format,e.typeToFolder);if(!r)throw new _(`Item ${e.id} not found`,g.NOT_FOUND);let i=(await ye(r,{schema:t.schema})).document.metadata[n.metadataKey]??[],o=e.writeRequested?wy({collectionKey:n.metadataKey,stored:i,written:[],removedCount:0,fullHistory:e.options.fullHistory===!0}):void 0;return by({id:r.id,artifacts:i,changed:!1,options:e.options,workspaceRoot:e.workspaceRoot,mutation:o})}async function Uo(e,t,n,r){let{metadataKey:i}=r,o=lu(),a=M(process.cwd(),n.path),s=Qe(a),c=process.cwd();await re(a);let d=await T(a),l=z(d,F()),u=await o.resolveList(t.add,"--add"),m=await o.resolveList(t.addGlob,"--add-glob"),f=await o.resolveList(t.remove,"--remove"),p=await o.resolveList(t.migrate,"--migrate"),h=JT({id:e,pmRoot:a,entries:u,resolved:{addGlob:m,remove:f,migrate:p},options:t,global:n,config:r}).map(se=>({...se,path:qc(se.path,s,c)})),y=$T(m),w=await LT(y,s,c),v=h.length>0||y.length>0,k=NT([...h,...w],t.note,v),E=bT(t.noteConflict,v),x=OT(f).map(se=>qc(se,s,c)),$=DT(p);if(PT(k,x,$),!(k.length>0||x.length>0||$.length>0))return KT({id:e,pmRoot:a,settings:d,typeToFolder:l.type_to_folder,options:t,workspaceRoot:s,config:r,writeRequested:y.length>0});let S=W(t.author,d.author_default),b=[],D=0,U=[],I=await _t({pmRoot:a,settings:d,id:e,op:r.op,author:S,message:t.message,force:t.force,skipNoop:!0,mutate(se){let At=se.metadata,lt=At[i]??[],Ye=[...lt],N=jT(Ye,k,x,$),H=zT(Ye,N.adds,N.removes,r.supportsAppendStable&&t.appendStable===!0,E);if(H.conflicts.length>0){let cn=Ia(a);throw ET({itemId:se.metadata.id,noun:r.bareNoun,conflicts:H.conflicts,retryArgs:dn=>cn===void 0?void 0:ky({id:se.metadata.id,entries:u??[],position:0,rewritten:"",resolved:{addGlob:m,remove:f,migrate:p},options:t,global:n,config:r,guards:cn,noteConflict:dn}),render:K})}let Ct=H.entries;U=H.outcomes,Ct.length>0?At[i]=Ct:delete At[i];let sn=!ma(lt,Ct);return b=lt,D=WT(lt,Ct,$),{changedFields:sn?[i]:[],warnings:sn&&N.count>0?[`path_migrations_applied:${N.count}`]:[]}}}),G=I.item[i]??[],Re=I.warnings.find(se=>se.startsWith("path_migrations_applied:")),Fe=Re?Number(Re.slice(24)):0;return by({id:I.item.id,artifacts:G,changed:I.changedFields.includes(i),migrationsApplied:Fe,options:t,workspaceRoot:s,mutation:wy({collectionKey:i,stored:G,written:AT(b,G),removedCount:D,fullHistory:t.fullHistory===!0,linkOutcomes:U})})}function zo(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]="b1de9573-b582-502d-8fb1-9e6ba3a521b0")}catch{}})();async function Ey(e,t,n){let r=await Uo(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return zo(r,"docs")}import Sy from"node:fs/promises";import je 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]="ad4d4093-7e23-5361-bec4-efb37bd610b6")}catch{}})();var YT=32768;function Kc(e){return Rt(je.normalize(e))}async function Wo(e){try{return await Sy.realpath(e)}catch{return je.resolve(e)}}function nr(e,t){let n=je.isAbsolute(e.path)?je.resolve(e.path):je.resolve(t,e.path);return`${Kc(n)}::${e.scope}`}function qo(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)=>qo(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))qo(i,t?`${t}.${r}`:r,n)}function XT(e){let t=[];return qo(e.metadata,"metadata",t),qo(e.body,"body",t),t}function ZT(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 QT(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 o=new Set,a=i.value.slice(0,YT);for(let[s,c]of[[n,i.value],[r,a]]){s.lastIndex=0;for(let d of c.matchAll(s)){let l=ZT(d[0]);!l||o.has(l)||(o.add(l),t.push({field:i.field,value:l}))}}}return t}async function e$(e,t,n=t){let r=je.isAbsolute(e)?je.resolve(e):je.resolve(n,e),i;try{i=await Sy.stat(r)}catch{return}if(!i.isFile())return;let[o,a]=await Promise.all([Wo(t),Wo(r)]);if(he(o,a)){let s=je.relative(o,a);return!s||s.startsWith("..")||je.isAbsolute(s)?void 0:{path:Kc(s),scope:"project"}}return{path:Kc(r),scope:"global"}}async function t$(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>nr(c,t))),i=new Map,o=QT(XT(e)),a=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{a.set(c,await e$(c,t,n))}));let s=o.map(c=>({reference:c,resolved:a.get(c.value)}));for(let{reference:c,resolved:d}of s){if(!d)continue;let l=nr(d,t),u=i.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function xy(e,t,n){let r=await Uo(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return zo(r,"files")}async function n$(e,t){let n=await Wo(t),r=await Promise.all(e.map(async o=>{let a=o.trim();if(!a)throw new _("Files lookup paths must not be empty.",g.USAGE);if(!je.isAbsolute(a))return Rt(a);let s=await Wo(a);return he(n,s)?Rt(je.relative(n,s)):Rt(s)})),i=[...new Set(r)].sort((o,a)=>o.localeCompare(a));if(i.length===0)throw new _("Files lookup requires at least one path.",g.USAGE);return i}function r$(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new _(`Files lookup ${r} must be a non-negative integer.`,g.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function Iy(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Ry(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function i$(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(Rt(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(Ry)}async function o$(e){if(e.explain)return Qm({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function a$(e){if([e.strictRead,e.noTruncate,e.explain,Ql()].includes(!0))return null;let t=await Mi(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Au({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function s$(e){let t=[],n=await ji(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=i$({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(s=>/^item_list_(?:item|directory)_read_failed:/u.test(s));if(e.strictRead&&i.length>0)throw new _(`Files lookup could not read every item: ${i.join("; ")}`,g.GENERIC_FAILURE);let o=await o$({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(o?[...r].sort((s,c)=>{let d=o.explanations.get(c.item.id).score-o.explanations.get(s.item.id).score;return d!==0?d:Ry(s,c)}):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:Iy(s.item),files:s.files,...o?{traceability:o.explanations.get(s.item.id)}:{}})),...o?{traceability_receipt:o.receipt}:{}}}async function Xq(e,t){let n=M(process.cwd(),t.path),r=Qe(n);await re(n);let i=await n$(e.paths,r);if(e.lineRange&&i.length!==1)throw new _("Files lookup line attribution requires exactly one source path.",g.USAGE);let o=await T(n),a=z(o,F()),{offset:s,limit:c}=r$(e),d=await a$({pmRoot:n,typeToFolder:a.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:s,limit:c,has_more:s+d.matches.length<d.total,truncated:s+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:Iy(l.item),files:l.files}))}:s$({pmRoot:n,settings:o,typeToFolder:a.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function Zq(e,t,n){let r=M(process.cwd(),n.path),i=Qe(r);await re(r);let o=await T(r),a=z(o,F()),s=await ge(r,e,o.id_prefix,o.item_format,a.type_to_folder);if(!s)throw new _(`Item ${e} not found`,g.NOT_FOUND);let c=await ye(s,{schema:o.schema}),d=await t$(c.document,i,process.cwd()),l=d.filter(b=>b.status==="addable"),u=d.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let b=c.document.metadata.files??[];return{id:s.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let p=W(t.author,o.author_default),h=l.map(b=>({path:b.path,scope:b.scope,note:f})),y=[],w=new Set,v=await _t({pmRoot:r,settings:o,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let D=[...b.metadata.files??[]],U=new Set(D.map(Re=>nr(Re,i)));y=[],w.clear();for(let[Re,Fe]of h.entries()){let se=nr(Fe,i);U.has(se)||(D.push(Fe),U.add(se),y.push(Fe),w.add(Re))}let I=Vc(D),G=t.appendStable?I:Jc(I);return G.length>0?b.metadata.files=G:delete b.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==h.length?[`files_discover_skipped_existing:${h.length-y.length}`]:[]}}}),k=v.item.files??[],E=new Set(y.map(b=>nr(b,i))),x=k.filter(b=>E.has(nr(b,i))),$=l.filter((b,D)=>!w.has(D)),S=[...u,...$];return{id:v.item.id,files:k,changed:x.length>0,apply:!0,count:k.length,candidate_count:d.length,addable_count:l.length,added_count:x.length,skipped_existing_count:S.length,candidates:d,added:x,skipped_existing:S}}import{readFileSync as c$}from"node:fs";import Go 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]="d88c7294-44f1-5b65-9467-f94ed2db11ca")}catch{}})();var d$=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Zc=new Set(["--pm-path","--path","--author","--expect-hash"]),l$={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"])},u$=new Set(["-p","--package"]),m$=new Set(["-c","--call"]),p$=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),f$=new Set(["-C","--prefix","--userconfig","--cache"]),iG=new Set(["--cwd"]),oG=new Set(["--cwd"]),h$=new Set(["exec","x"]),aG=new Set(["run","run-script"]),sG=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Ay(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function _$(e,t=process.cwd()){let n=Ty(e.split(" ").filter(a=>a.length>0));if(n.length===0)return null;let[r,...i]=n;if(Bo(r)||Jo(r,t))return i;if(r==="node"&&i[0]&&Jo(i[0],t))return i.slice(1);let o=r==="npx"||r==="bunx"?Vo(i):r==="pnpm"?Dy(i):r==="npm"?Py(i):null;return o&&(Bo(o.command)||$y(o.command))?o.args:null}var Cy=(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 o=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),a=new Set;for(let s of Ay(o)){let c=_$(s),d=c?y$(c):null,l=d&&d$.has(d.subcommand)?w$(d.remaining,l$[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&a.add(l)}return[...a].sort((s,c)=>s.localeCompare(c))};function Ty(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 Xc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Zc.has(n)){t+=2;continue}t+=1;continue}return n}}function Bo(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function g$(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 $y(e){let t=g$(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Jo(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=Go.resolve(t,e);try{return JSON.parse(c$(Go.join(Go.dirname(Go.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Vo(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 o=i[1];return o?{command:o,args:e.slice(t+1)}:null}if(m$.has(r)){t+=1;break}t+=u$.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Oy(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 Dy(e){let t=Oy(e,p$);return t?.subcommand!=="dlx"?null:Vo(t.args)}function Py(e){let t=Oy(e,f$);return!t||!h$.has(t.subcommand)?null:Vo(t.args)}function y$(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Zc.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function w$(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("=")&&(Zc.has(r)||t.has(r))&&(n+=1)}}function Yc(e){return!e||!Bo(e.command)&&!$y(e.command)?!1:Xc(e.args)==="test-all"}var v$=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),b$=new Set(["npx","bunx"]);function Ly(e){let t=e.split(" ").filter(a=>a.length>0),n=Ty(t);if(n.length===0)return!1;let[r,...i]=n,o=v$.get(r);if(o){let a=i.findIndex(s=>o.test(s));return a>=0?Ly(i.slice(a+1).join(" ")):!1}return Bo(r)||Jo(r)?Xc(i)==="test-all":r==="node"&&i.length>0&&Jo(i[0])?Xc(i.slice(1))==="test-all":b$.has(r)?Yc(Vo(i)):r==="pnpm"?Yc(Dy(i)):r==="npm"?Yc(Py(i)):!1}function k$(e){let t=E$(e);return Ay(t).some(n=>Ly(n))}function cG(e){if(k$(e))throw new _('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',g.USAGE)}function E$(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}import{execFile as S$}from"node:child_process";import{readFile as x$}from"node:fs/promises";import My from"node:path";import{promisify as I$}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]="8f1a3301-8938-5208-9177-72ee29f3d174")}catch{}})();var R$=I$(S$),Qc=1,A$="linked-test-trust.json";function ed(e){return My.join(Jd(e),A$)}function Ny(){return{version:Qc,acknowledged:{}}}async function td(e){try{let t=JSON.parse(await x$(ed(e),"utf8"));return t.version!==Qc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Ny():{version:Qc,acknowledged:t.acknowledged}}catch{return Ny()}}async function nd(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await R$("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function rd(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function C$(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&bl(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Zr(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function T$(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function wG(e,t,n){if(!e||e.length===0)return e;for(let i of e)uu(i);let r=rd();return T$(e,t,n,await nd(r))}function jy(e){return Ae(A({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function vG(e,t,n){let r=await td(e);return Fy(t,n,r)}function Fy(e,t,n){let r=jy(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let o=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!C$(e.provenance)?o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Zr(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...Zr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...Zr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Zr(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...Zr(i,t)}}async function Hy(e,t,n){let r=await td(e);return t.map(i=>Fy(i,n,r))}async function bG(e,t,n){let r=await td(e),i=t.filter(o=>typeof o.command=="string"&&o.command.length>0).map(jy);for(let o of i)r.acknowledged[o]={acknowledged_at:n};return await ar(My.dirname(ed(e))),await Q(ed(e),`${JSON.stringify(r,null,2)}
70
+ `),{acknowledged:i.length,fingerprints:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8cca9707-86a7-5ab5-8c7b-92be560254d0")}catch{}})();async function Ko(e){return e.includeBody?ht(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):ji(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6322c4ff-92bd-59e5-aa64-ef8d3ef4b57f")}catch{}})();var $$=5;async function O$(e,t){let n=t.hashMismatches.filter(o=>o!==ne);if(n.length===0)return;let r=await T(e),i=z(r,F());for(let o of n){let a=await oe(e,o,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let s=await ge(e,o,r.id_prefix,r.item_format,i.type_to_folder);if(s===null)throw new _(`Item ${o} not found`,g.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await ye(s,{schema:r.schema});if(c.metadata.id!==o)throw new _(`Item identity changed while validating ${o}`,g.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await Hp(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(m=>m!==o),...d[u].filter(m=>m===o)].sort((m,f)=>m.localeCompare(f));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==o),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===o)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await a()}}}async function Yo(e,t,n){let r=await Qt(e,t);await O$(e,r);let i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),o=n?Number.POSITIVE_INFINITY:$$,a=r.driftedItems.slice(0,o),s=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:s.length>0?"error":i.length===0?"ok":"warn",ok:s.length===0&&i.length===0,details:{identity_discontinuities:s.slice(0,o),identity_discontinuities_count:s.length,identity_discontinuities_truncated:s.length>o,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,o)}},warnings:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fb73b204-3c60-5b9b-9576-e1c13ad537b3")}catch{}})();function id(e){let t=0,n=new Map,r=new Map,i=[],o=new Set,a=[],s=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),o.add(d);for(let u of e.get(d)??[])n.has(u)?o.has(u)&&r.set(d,Math.min(r.get(d),n.get(u))):(s(u),r.set(d,Math.min(r.get(d),r.get(u))));if(r.get(d)!==n.get(d))return;let l=[];for(;i.length>0;){let u=i.pop();if(o.delete(u),l.push(u),u===d)break}l.sort((u,m)=>u.localeCompare(m)),a.push(l)},c=[...e.keys()].sort((d,l)=>d.localeCompare(l));for(let d of c)n.has(d)||s(d);return a.filter(d=>{if(d.length>1)return!0;let l=d[0];return(e.get(l)??[]).includes(l)}).sort((d,l)=>d[0].localeCompare(l[0])||d.length-l.length||d.join(",").localeCompare(l.join(",")))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3caaa82b-d8c7-5bc4-94e5-6699da27fa3c")}catch{}})();function Xo(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],o=new Set([n]),a=s=>{for(let c of(t.get(s)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!o.has(c)){if(o.add(c),i.push(c),a(c))return!0;i.pop(),o.delete(c)}}return!1};return a(n)?[...i]:[...e,n]}function D$(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function P$(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let o=r.resolve(i.kind);if(!o?.hierarchy)continue;let a=n.get(i.id.toLowerCase());a&&(o.hierarchyDirection==="source_parent"?t.get(a).push(e.id):t.get(e.id).push(a))}}function od(e,t=hr()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((o,a)=>o.id.localeCompare(a.id))){let o=r.get(i.id),a=D$(i.parent,n);a&&o.push(a),P$(i,r,n,t)}for(let[i,o]of r)r.set(i,[...new Set(o)].sort());return r}function ad(e,t,n=hr()){let r=Hi(e,a=>t?_l(a,t):a==="closed"||a==="canceled",n),i=od(e,n),o=r.cycles.map(a=>a.item_ids);return{cycle_count:o.length,active_cycle_count:r.cycles.filter(a=>!a.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(a=>a.legacy_terminal).length,cycle_item_ids:[...new Set(o.flat())].sort(),cycle_sample_paths:o.map(a=>Xo(a,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(a=>!a.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(a=>a.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(a=>`${a.child_id}:${a.parent_ids.join(",")}:${a.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(a=>!a.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(a=>a.legacy_terminal).length,parent_divergence_rows:r.divergences.map(a=>`${a.child_id}:scalar=${a.scalar_parent_id}:dependencies=${a.dependency_parent_ids.join(",")}:${a.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2840c80-38f5-5563-b2c0-ef5596cf8f62")}catch{}})();function qt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function sd(e){return qt(e).replace(/\/+$/,"")}function Ve(e){let t=X(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function cd(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`: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]="458ca446-e2a2-59f1-b890-d00d718e0835")}catch{}})();var j$=["src","tests","docs"],F$=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],H$=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),U$=["resolution","expected_result","actual_result"],z$=["default","tracked-all","tracked-all-strict"],Uy=["core","strict","custom"],ea=["off","warn","error"],ud=["author","acceptance_criteria","estimated_minutes","close_reason"],qy=[...ud,"reviewer","risk","confidence","sprint","release"],md=Array.from(new Set(qy)),W$={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"},q$={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"},G$={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"},B$={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"},J$={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"},V$=32*1024*1024,K$=1e4,pd=40,Ke=5,Y$=4096,X$=255,Z$=M$(N$);function Gy(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?Gy(r):r);return t}function Q$(e){return{...e,checks:e.checks.map(t=>({...t,details:Gy(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 na(e,t){return yi(e,t)??e}function Qr(e,t){return t.terminal_statuses.has(na(e,t))}function Gt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Zo(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function eO(e){let t=Gt(jd),n={blocked_reason:Gt(si.blocked_reason),resolution:Gt(si.resolution),actual_result:Gt(si.actual_result)},r=Gt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:Gt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Gt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Gt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Zo(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Zo(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Zo(i.resolution,n.resolution)?"default":"settings",actual_result:Zo(i.actual_result,n.actual_result)?"default":"settings"}}}function By(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Uy.includes(t))return t;throw new _(`Unknown --metadata-profile value "${e}". Supported values: ${Uy.join(", ")}.`,g.USAGE)}function Jy(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ea.includes(t))return t;throw new _(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ea.join(", ")}.`,g.USAGE)}function Vy(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ea.includes(t))return t;throw new _(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ea.join(", ")}.`,g.USAGE)}function tO(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>W$[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function nO(e,t,n){let r=tO(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...ud],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...qy],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:[...ud],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var rO=new Set(["acceptance_criteria","estimated_minutes"]);function Ky(e,t,n,r){return!r&&rO.has(t)&&Qr(e.status,n)?!1:t==="author"?!X(e.author):t==="acceptance_criteria"?!X(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?na(e.status,n)===n.close_status&&!X(e.close_reason):t==="reviewer"?!X(e.reviewer):t==="risk"?!X(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!X(e.confidence):t==="sprint"?!X(e.sprint):!X(e.release)}function Yy(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 _(`Unknown --scan-mode value "${e}". Supported values: ${z$.join(", ")}.`,g.USAGE)}function Xy(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Ie.resolve(t);let n=Ie.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Ie.dirname(Ie.dirname(n));let r=Ie.resolve(process.cwd()),i=zy(n),o=zy(r),a=Ie.relative(i,o);return a.length===0||!a.startsWith("..")&&!Ie.isAbsolute(a)?n:r}function zy(e){try{return L$.native(e)}catch{return Ie.resolve(e)}}function iO(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function gd(e,t,n){let r=t.length>0?Ie.join(e,t):e,i;try{i=await _d.readdir(r,{withFileTypes:!0})}catch(o){if(j(o))return;throw o}for(let o of i){if(o.name.startsWith("."))continue;let a=t.length>0?Ie.join(t,o.name):o.name;if(o.isDirectory()){if(H$.has(o.name))continue;await gd(e,a,n);continue}o.isFile()&&n.push(qt(a))}}async function fd(e){let t=[];for(let n of j$)await gd(e,n,t);for(let n of F$){let r=Ie.join(e,n);try{(await _d.stat(r)).isFile()&&t.push(qt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function Zy(e){try{let{stdout:t}=await Z$("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:V$,windowsHide:!0,timeout:K$}),n=t.split("\0").map(r=>qt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function oO(e,t){let n=new Set,r=sd(Ld);r.length>0&&n.add(r);let i=sd(Ie.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((o,a)=>o.localeCompare(a))}function Wy(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function aO(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await Zy(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await fd(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await fd(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function te(e,t=Ke){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function on(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=te(e,pd);return{values:n.values,truncated:n.truncated,total:e.length}}var sO={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},cO={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function dO(e){let t=e.missing_fields.map(n=>`${sO[n]} "${cO[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Qy(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(a=>typeof a=="string"):Gp(t);if(i.length===0)return;let o=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...o?{fix_hints_truncated:!0}:{}}}function ew(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),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("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var lO="validate_metadata_duplicate_issue_codes";function tw(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Ke,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${lO}:${e.length}`]}}function uO(e,t,n){let r=Object.fromEntries(md.map(i=>[i,[]]));for(let i of e)for(let o of md)Ky(i,o,t,n)&&r[o].push(i.id);return r}function mO(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let o=t[i];o.length>0&&r.push(`${q$[i]}:${o.length}`)}return r.push(...n),r}function nw(e,t){let n={};for(let r of e.required_fields){let i=t[r],o=i?i.length:0,a=G$[r];n[a]=o}return n}function rw(e,t,n){let r=[];for(let i of e.required_fields){let o=t[i];if(o)for(let a of o){let s=n.get(a)?.type,c=typeof s=="string"&&s.length>0?s:"Unknown";r.push({item_type:c,field:i})}}return r}function pO(e,t,n,r){for(let i of t.required_fields){let o=n[i];if(!o||o.length===0)continue;let a=B$[i],s=J$[i];if(!a||!s)continue;let c=te(o,r?o.length:Ke);e[a]=c.values,e[s]=c.truncated}}function iw(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:X(n.get(i)?.resolution)})):[]}function ow(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:X(n.get(i)?.type)})):[]}function fO(e,t,n,r,i){let o=new Map(e.map(v=>[v.id,v])),a=t.profile==="strict",s=uO(e,n,a),c=ey(e,{configuredPrefixes:i}),d=tw(c,r),l=mO(t,s,d.warnings),u=nw(t,s),m=rw(t,s,o),f=ty(m),p={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:[...md],counts:u,missing_by_type:f,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(p.configured_custom_required_fields=[...t.configured_custom_fields]);let h=Mo(e,r);h!==void 0&&(p.deferred_fields=h.details,l.push(h.warning)),pO(p,t,s,r);let y=iw(t,s,o),w=ow(t,s,o);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:p},warnings:l,closeReasonBackfillRows:y,estimateBackfillRows:w}}function hO(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(na(m.status,t))),o=[],a=[];for(let m of i){let f=U$.filter(p=>!X(m[p]));f.length!==0&&(o.push({id:m.id,missing_fields:f}),a.push({id:m.id,missing_fields:f,close_reason:X(m.close_reason)}))}let s=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:Ke,d=te(o.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=o.map(m=>dO(m)),u=te(l,c);return{check:{name:"resolution",status:s.length===0?"ok":"warn",ok:s.length===0,details:{checked_closed_items:i.length,missing_resolution_items:o.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:s,resolutionBackfillRows:a}}function aw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sw(e,t="pm",n=Ud()){let r=new Set(e.map(o=>o.id)),i=[...e].sort((o,a)=>o.id.localeCompare(a.id));return new Map(i.map(o=>{let a=new Set,s=Ve(o.blocked_by);s&&r.has(s)&&a.add(s),(o.dependencies??[]).filter(d=>{let l=Ve(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ve(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>a.add(d));let c=Ve(o.definition_of_ready);return dw(c??"",t).filter(d=>r.has(d)).forEach(d=>a.add(d)),[o.id,[...a].sort((d,l)=>d.localeCompare(l))]}))}function cw(e,t,n){let r=Yu(e,n?l=>Qr(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),o=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),a=t?Number.POSITIVE_INFINITY:Ke,s=te(i,a),c=te(o,a),d=te(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),a);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+o.length,active_dangling_reference_count:i.length,dangling_reference_rows:s.values,dangling_reference_rows_truncated:s.truncated,legacy_terminal_dangling_reference_count:o.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function dw(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${aw(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,o)=>i.localeCompare(o))}function lw(e,t="pm"){let n=sw(e,t),r=id(n),i=[...new Set(r.flat())].sort((a,s)=>a.localeCompare(s)),o=r.map(a=>Xo(a,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:o}}function uw(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 ta(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function mw(e,t){let n=ta(e).split("/").filter(Boolean),r=ta(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function _O(e,t){let n=ta(t),r=ta(e),i=t.endsWith("/")?t:`${t}/`,o=e.startsWith(i),a=n.length>0&&n===r,s=mw(e,t);return!o&&!a&&s===0?null:o?{score:t.length+1e3,confidence:"path_prefix"}:a?{score:s+500,confidence:"same_directory"}:{score:s,confidence:"shared_directory"}}function gO(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function yO(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(o=>(r==="docs"?o.docs??[]:o.files??[]).map(a=>({item:o,link:a}))).forEach(({item:o,link:a})=>{if(a.scope!=="project")return;let s=qt(a.path);if(s.length===0||s===e)return;let c=_O(e,s);c!==null&&gO(i,o,c.score)&&(i={item:o,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 pw(e,t){return e.map(n=>{let r=uw(n),i=r==="docs_unowned"?"docs":"files",o=yO(n,r,t),a=o?.id??"<id>";return{path:n,classification:r,owner_candidate:o,remediation_hint:`pm ${i} ${a} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function fw(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function wO(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Ve(e[n]);return i?r.some(o=>i.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function vO(e,t,n,r,i){let o=Ve(t.parent),a=o?n.get(r.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:a?.id,grandparent_active:a!==void 0&&!Qr(a.status,i)}}function bO(e,t,n,r){let i=Ve(e.blocked_by),o=Ve(e.blocked_reason),a=o?.toLowerCase(),s=na(e.status,n),c=[];return t.has(s)?(!i&&!o&&c.push("blocked_status_missing_blocker_context"),a?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),a&&r.stale_blocker_reason_patterns.some(d=>a.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function kO(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),a=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),s={activeItems:e.filter(c=>!Qr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of s.activeItems){let d=wO(c,r);d.length>0&&s.closureLikeRows.push({id:c.id,fields:d});let l=Ve(c.parent),u=l?i.get(o.get(l.toLowerCase())??l):void 0;if(u&&Qr(u.status,n)&&(s.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),s.terminalParentFixRows.push(vO(c,u,i,o,n))),t){let m=bO(c,a,n,r);m.length>0&&s.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,p)=>f.localeCompare(p))})}}return s}function EO(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 Qo(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function dd(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function SO(e,t,n,r,i){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=Qo("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),s=Qo("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=Qo("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=Qo("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=dd("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=dd("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=dd("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...o,...a?[a]:[],...s?[s]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function hw(e){let t=qt(e);return t.length>Y$||t.split(/[\\/]/).some(n=>n.length>X$)}async function xO(e,t){let n=Ie.isAbsolute(t)?t:Ie.resolve(e,t);if(hw(n))return!1;try{let r=await _d.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return iO(r,["ENOENT","ENOTDIR"])}}async function IO(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(o=>({item:i,artifact:o,link_kind:"files"})),...(i.docs??[]).map(o=>({item:i,artifact:o,link_kind:"docs"}))]);for(let{item:i,artifact:o,link_kind:a}of r){if(o.scope!=="project")continue;if(Xr(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let s=qt(o.path);s.length!==0&&(n.linkedProjectPaths.add(s),await xO(t,o.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:i.id,path:s,link_kind:a})))}return n}function RO(e,t,n,r,i,o){let a=r==="tracked-all-strict",s=a&&!i,c=i||a,d=c?[]:oO(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>Wy(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Wy(f,d)),m={};if(l.length>0){let f=on(l,o);m.pm_internals={count:l.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:a,strictModeForcesPmInternals:s,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function _w(e,t,n,r,i,o,a,s="pm"){let c=kO(e,t,i,o);EO(c);let d=lw(c.activeItems,s),l=ad(e,i),u=to(i,e,a?Number.POSITIVE_INFINITY:Ke),m=[...SO(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...no(u)],f=a?Number.POSITIVE_INFINITY:Ke,p=te(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),f),h=te(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),f),y=te(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),f),w=te(d.cycle_item_ids,f),v=te(d.cycle_sample_paths,f),k=te(l.cycle_item_ids,f),E=te(l.cycle_sample_paths,f),x=te(l.cardinality_violation_rows,f),$=te(l.parent_divergence_rows,f),S=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:S?"error":m.length===0?"ok":"warn",ok:!S&&m.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:p.values,active_closure_like_metadata_rows_truncated:p.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:w.values,dependency_cycle_item_ids_truncated:w.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:E.values,parent_cycle_sample_paths_truncated:E.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:x.values,hierarchy_cardinality_violation_rows_truncated:x.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:$.values,hierarchy_parent_divergence_rows_truncated:$.truncated,stale_blocker_reason_patterns:[...o.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:o.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...o.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:o.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...o.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:o.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...o.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:o.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function gw(e,t,n,r,i,o,a=_e(Fd.schema)){let s=await IO(e,t),c=new Map(e.map(I=>[I.id,I])),d=[...new Set(s.missingLinkedPaths)].sort((I,G)=>I.localeCompare(G)),l=await aO(t,r),u=RO(l,n,t,r,i,o),m=u.candidateFiles.filter(I=>!s.linkedProjectPaths.has(I)),f=pw(m,e),p=ry(d,u.candidateFiles),h=new Map(p.map(I=>[I.path,I.classification])),y=p.filter(I=>I.classification==="moved").length,w=s.staleLinkRows.map(I=>({...I,classification:h.get(I.path)??"deleted"})).sort((I,G)=>I.item_id.localeCompare(G.item_id)||I.path.localeCompare(G.path)||I.link_kind.localeCompare(G.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),m.length>0&&v.push(`validate_files_orphaned_paths:${m.length}`);let k=[...s.remoteLinkedPaths].sort((I,G)=>I.localeCompare(G)),E=on(k,o),x=on(d,o),$=on(m,o),S=on(f.map(I=>`${I.path}:${I.classification}:owner_candidate=${I.owner_candidate?.id??"unowned"}`),o),b=o?f:on(fw(f),!1).values,D=on(iy(p),o),U=zg(w,p,I=>c.get(I),a,o?1/0:pd);return U.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${U.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:o?"full":"summary",file_list_summary_limit:pd,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:k.length,remote_linked_paths_total:E.total,remote_linked_paths:E.values,remote_linked_paths_truncated:E.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:x.total,missing_linked_paths:x.values,missing_linked_paths_truncated:x.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:p.filter(I=>I.classification==="deleted").length,missing_linked_paths_malformed_count:p.filter(I=>I.classification==="malformed").length,missing_linked_path_classifications:D.values,missing_linked_path_classifications_truncated:D.truncated,...U,orphaned_paths_count:m.length,orphaned_paths_total:$.total,orphaned_paths:$.values,orphaned_paths_truncated:$.truncated,orphaned_path_classifications:S.values,orphaned_path_classifications_truncated:S.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:b}},warnings:v,staleLinkPruneRows:w}}function AO(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},o)=>{let a=t[o];if(a.trusted)return;let s=cd(i.command??"");n.push(`${r.id}:${a.source_ref??"unknown"}->${a.current_source_ref??"unknown"}:${s}`)}),n}async function yw(e,t,n,r){let i=new Set(e.map(x=>x.id.toLowerCase())),o=0,a=0,s=new Set,c=[],d=e.flatMap(x=>(x.tests??[]).map($=>({item:x,linkedTest:$}))),l=await nd(rd()),u=await Hy(r,d.map(({linkedTest:x})=>x),l),m=AO(d,u);for(let{item:x,linkedTest:$}of d){if(typeof $.command!="string"||$.command.trim().length===0)continue;o+=1;let S=Cy($.command,t);if(S.length!==0){a+=S.length;for(let b of S)s.add(b),i.has(b.toLowerCase())||c.push(`${x.id}:${b}:${cd($.command)}`)}}let f=[...new Set(c)].sort((x,$)=>x.localeCompare($)),p=[...new Set(f.map(x=>x.split(":")[1]??""))].filter(x=>x.length>0).sort((x,$)=>x.localeCompare($)),h=[];f.length>0&&h.push(`validate_command_references_stale_pm_ids:${f.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let y=n?Number.POSITIVE_INFINITY:Ke,w=te(f,y),v=te(p,y),k=te([...s].sort((x,$)=>x.localeCompare($)),y),E=te(m,y);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:o,referenced_pm_ids_count:a,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:E.values,untrusted_linked_tests_truncated:E.truncated,stale_pm_id_references_count:f.length,stale_pm_ids_count:p.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:h}}function CO(e,t){let n=gi(e.map(c=>({ref:c.id,version:_i(c)})),cr,hi),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:Ke,o=te(n.outdated,i),a=te(n.ahead,i),s=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:s,ok:s==="ok",details:{checked_items:e.length,current_format_version:cr,outdated_items_count:n.outdated.length,outdated_items:o.values,outdated_items_truncated:o.truncated,ahead_items_count:n.ahead.length,ahead_items:a.values,ahead_items_truncated:a.truncated}},warnings:r}}var hd="pm validate auto-fix";async function ww(e,t,n){switch(e.kind){case"set_closed_at":await Fg(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:hd};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 _("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.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 ld(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function vw(e,t,n){let r=[],i=[],o=new Map;for(let a of e.filter(s=>ld(s)===null))try{await ww(a,t,n),r.push(a)}catch(s){i.push({fix:a,error:s})}for(let a of e.filter(s=>ld(s)!==null)){let s=ld(a),c=o.get(s);c?c.push(a):o.set(s,[a])}for(let a of o.values()){let s=a[0];if(!s)continue;let c=a.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{s.kind==="prune_file_link"?await xy(s.item_id,{remove:c,message:hd},t):await Ey(s.item_id,{remove:c,message:hd},t),r.push(...a)}catch(d){i.push(...a.map(l=>({fix:l,error:d})))}}return am(i.map(a=>a.error)),{applied:r,failed:i}}var NB={applyValidateFix:ww,applyValidateFixes:vw,attachValidateFixHints:Qy,buildCommandReferencesCheck:yw,buildDependencyReferencesCheck:cw,buildCloseReasonBackfillRows:iw,buildFilesCheck:gw,buildLifecycleCheck:_w,buildLifecycleDependencyGraph:sw,buildLifecycleParentGraph:od,buildEstimateBackfillRows:ow,buildMetadataCounts:nw,buildMissingFieldOccurrences:rw,buildOrphanedPathRows:pw,classifyOrphanedPath:uw,collectDefaultProjectFileCandidates:fd,collectTrackedGitFileCandidates:Zy,detectLifecycleDependencyCycles:lw,detectLifecycleParentCycles:ad,escapeRegExp:aw,extractItemIds:dw,findLifecycleDependencyCycleComponents:id,isMetadataFieldMissing:Ky,linkedArtifactPathExceedsFilesystemLimits:hw,listFilesRecursive:gd,resolveDependencyCycleSeverity:Jy,resolveParentCycleSeverity:Vy,resolveFileScanMode:Yy,resolveLifecycleDependencyCycleSamplePath:Xo,resolveRequestedChecks:ew,resolveValidateMetadataProfile:By,resolveWorkspaceRoot:Xy,sharedDirectoryPrefixLength:mw,summarizeOrphanedPathRows:fw,summarizeDuplicateIssueCodes:tw,toMeaningfulString:Ve};function TO(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function $O(e,t,n,r){let i=await qg(e,new Set(t.map(y=>y.id)),n,{schema:r.schema,extensionFieldNames:ln(F())}),o=[];i.unreadable_item_files.length>0&&o.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&o.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&o.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&o.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&o.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&o.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let a=o.length,s=await ko(e);s.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${s.tracked_path_count}`);let c=await Nt(e),d=await Tn(e,Cn(r),{gitWorkspaceRoot:c});d.status==="drift"&&o.push(`validate_merge_fence_drift:${d.missing_patterns.length+d.stale_patterns.length}`);let l=c===null?null:await $n(c);l!==null&&l.status!=="ok"&&o.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await St(c??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:f,lossless:p}=Yn(m);f.length>0&&o.push(`validate_merge_decisions_unreviewed:${f.length}`),TO(o,u.invalid_evidence_count);let h=a>0?"error":o.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...i,merge_fence:d,merge_driver_configuration:l,pending_merge_decision_count:f.length,pending_merge_decision_items:[...new Set(f.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),lossless_merge_receipt_count:p.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(p.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:s.tracker_relative_root,tracked_paths:s.tracked_paths,tracked_path_count:s.tracked_path_count,remediation_command:s.remediation_command}}},warnings:o}}function dt(e,t,n){n&&Qy(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function OO(e){let t={closureTimestampFixes:[],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("completeness")){let i=await Fm(e.pmRoot,e.items,r?1/0:Ke,e.sourceIncomplete);dt(t,i,n)}if(e.requestedChecks.has("metadata")){let i=fO(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let o=await jg(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,r?1/0:Ke);t.closureTimestampFixes=o.fixes,Object.assign(i.check.details,o.details),i.warnings.push(...o.warnings),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",dt(t,i,n)}if(e.requestedChecks.has("resolution")){let i=hO(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,dt(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=_w(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,dt(t,i,n),dt(t,cw(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await gw(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,dt(t,i,n)}return e.requestedChecks.has("command_references")&&dt(t,await yw(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&dt(t,await Yo(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&dt(t,CO(e.items,r),n),e.requestedChecks.has("storage_integrity")&&dt(t,await $O(e.pmRoot,e.items,z(e.settings,F()).type_to_folder,e.settings),n),t}function DO(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...Jg(t.closeReasonBackfillRows)),r.push(...Bg(t.resolutionBackfillRows)),r.push(...Vg(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Kg(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Yg(t.staleLinkPruneRows)),r}async function PO(e,t,n,r,i,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let a=DO(e,t,n),{applicable:s,gated:c}=Zg(a,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await vw(s,i,o);l.push(...m.applied.map(Yr)),u.push(...m.failed.map(({fix:f,error:p})=>({...Yr(f),error:p instanceof Error?p.message:String(p)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,f)=>m.localeCompare(f)),planned_count:a.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:a.map(Yr),applied_fixes:l,gated_fixes:c.map(m=>({...Yr(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function bw(e,t,n={}){eu(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new _("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new _("--fix-scope requires --auto-fix.",g.USAGE);let i=Xg(e.fixScope),o=M(process.cwd(),t.path);await re(o);let a=await T(o),s=_e(a.schema),c=z(a,F()),d=ew(e),l=[],u=await Ko({includeBody:["history_drift","metadata","completeness"].some(D=>d.has(D)),pmRoot:o,settings:a,typeToFolder:c.type_to_folder,warnings:l}),m=l.length>0;if(d.has("history_drift")){let D=await Er(o);D.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${D.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=By(typeof e.metadataProfile=="string"?e.metadataProfile:a.validation.metadata_profile),h=nO(p,f,a.validation.metadata_required_fields),y=eO(a),w=Jy(e.dependencyCycleSeverity),v=Vy(e.parentCycleSeverity),k=Yy(e.scanMode),E=Xy(o),x=await OO({requestedChecks:d,options:e,global:t,pmRoot:o,workspaceRoot:E,settings:a,items:u,statusRegistry:s,metadataPolicy:h,lifecyclePatternPolicy:y,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:k,initialWarnings:[...new Set(l)],sourceIncomplete:m}),$=r?await PO(e,x,a,i,t,n):void 0,S=[...new Set(x.warnings)].sort((D,U)=>D.localeCompare(U)),b={ok:!x.checks.some(D=>D.status==="error"),has_warnings:S.length>0,checks:x.checks,warnings:S,...$!==void 0?{fixes:$}:{},generated_at:C(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...Q$(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as LO}from"node:child_process";import{promisify as NO}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]="d50f9868-5c11-51dc-967e-61ce41225ef1")}catch{}})();var MO=NO(LO),jO=16,FO=3e4;function HO(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(r=>typeof r=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function UO(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let o of Object.entries(i).filter(([,a])=>a.required===!0).map(([a])=>a))if(!Object.hasOwn(r,o))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${o}`);for(let[o,a]of Object.entries(r)){let s=i[o];if(!s)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${o}`);if(a===null||typeof a!==s.type)throw new TypeError(`assurance provider ${e.id} parameter ${o} must be ${s.type}`)}return{...r}}async function zO(e,t,n,r){let i=UO(e,t),o=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Zl(n)}));o.catch(()=>{});let a;try{let s=await Promise.race([o,new Promise((c,d)=>{a=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??FO),a.unref?.()})]);return HO(e,t.key,s)}finally{clearTimeout(a)}}function Ew(e,t,n,r){let i=e;for(let o of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new rt(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[o]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(o=>typeof o=="string"))return i;throw new rt(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function kw(e,t,n,r){let i=e.checks.find(o=>o.name===t);if(!i)throw new rt(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:Ew(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function WO(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await MO("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function qO(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(jO,t.length)},async()=>{for(;r<t.length;){let o=r;r+=1;let a=t[o],s=await He(ut(e,a.id),a.id);n[o]=s.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function ei(e,t={}){let n=await T(e),r=z(n),i=_e(n.schema),o=(t.strict_read===!0?(await Zu(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await ht(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(m=>({...m,id:m.id,status:m.status,type:m.type})),a={path:e},s=F(),c=Object.fromEntries((s?.assurance_providers??[]).map(m=>[m.definition.id,{cost_class:m.runtime_definition.cost_class,network:m.runtime_definition.network}])),d=new Map,l,u;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await WO(e,t.tree_id),items:o,history:t.include_history===!1?[]:await qO(e,o),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...c,...t.provider_capabilities},external:async m=>{if(m.kind==="graph"){let h=A({operation:m.operation,parameters:m.parameters??{}}),y=d.get(h);y===void 0&&(y=rm(m.operation,void 0,void 0,{...m.parameters,full:!0},a),d.set(h,y));let w=await y;return{value:Ew(w,m.field,m.kind),population_size:o.length,cost:o.length}}if(m.kind==="validate"){l??=bw({counts:!0},a);let h=await l;return kw(h,m.check,m.field,m.kind)}if(m.kind==="health"){u??=Lg(a,{checkOnly:!0,full:!0});let h=await u;return kw(h,m.check,m.field,m.kind)}let f=t.providers?.[m.provider];if(f)return f(m);let p=mu(s,m.provider);if(!p)throw new TypeError(`assurance provider ${m.provider} is not registered`);return zO(p.runtime_definition,m,e,t.trigger??"sdk")}}}import{createHash as GO}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c72d246d-a7ff-5c9d-8c36-4ebd45b8a69f")}catch{}})();function Sw(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:i}=Ti({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function BO(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let r=n;if(r.fingerprint!==t||typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return r.offset}function JO(e,t,n,r,i,o){let a=Object.fromEntries(Aa.map(f=>[f,0])),s=0,c=0,d=0,l=0,u=[],m=GO("sha256").update(i);for(let f of r){let p=e.membership.get(f),h=n.has(f),y=p.family_ids.length>0;y&&h&&(s+=1),y||(c+=1),h||(d+=1);let w=t.get(f)?.escape_class;w!==void 0&&Aa.includes(w)&&(a[w]+=1,l+=1),m.update(A([f,h,t.get(f)??null,p.id,p.family_ids])),(!o||!y||!h)&&u.push(f)}return{classCounts:a,coveredCount:s,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:m.digest("hex")}}function xw(e,t,n={}){au(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let i=new Set,o=new Map;for(let E of t){if(i.has(E.id))throw new TypeError(`Duplicate recurrence item ${E.id}`);i.add(E.id);let x=Ci(E);x!==void 0&&o.set(E.id,x)}let a=nu(e.families,o),s=[...a.membership.keys()].sort(),c=A({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:m,classifiedCount:f,selected:p,fingerprint:h}=JO(a,o,i,s,c,n.uncoveredOnly===!0),y=BO(n.cursor,h);if(y>p.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=p.slice(y,y+r).map(E=>{let x=a.membership.get(E),$=i.has(E);return{item_id:E,lineage_id:x.id,lineage_item_count:x.item_ids.length,family_ids:x.family_ids,present:$,...$?x.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=y+w.length,k=s.length===0?null:d.production_defect/s.length;return{ok:u===0&&m===0,fingerprint:h,items:w,total:p.length,has_more:v<p.length,...v<p.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:s.length,lineage_count:a.lineages.length,edge_count:a.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:m,classified_item_count:f,unclassified_item_count:s.length-f,class_counts:d,escape_rate:f===s.length?k:null,escape_rate_lower_bound:k},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:a.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as VO}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c8cf307d-334c-5b70-93c7-991ff702e4ca")}catch{}})();var yd,Iw=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],wd=["measurement","assertion","gate"];function KO(e){if(Iw.includes(e))return e;throw Di({command_path:"assurance",token:e,allowed:Iw,display_name:"assurance action"})}function rr(e,t,n){throw new _(t,g.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function YO(e){if(!e)return rr("kind",`Assurance declaration kind is required. Expected: ${wd.join(", ")}`,"pm assurance list measurement");if(wd.includes(e))return e;throw new _(`Assurance declaration kind is required. Expected: ${wd.join(", ")}`,g.USAGE)}function Rw(e){if(!e)return rr("preset",`Assurance preset is required. Expected: ${Sr.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(Sr.includes(e))return e;throw new _(`Assurance preset is required. Expected: ${Sr.join(", ")}`,g.USAGE)}function vd(e){return e.owner?.trim()?e.owner.trim():rr("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function XO(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new _("assurance definition must be valid JSON",g.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new _("assurance put requires a JSON object definition",g.USAGE);return n}async function ZO(e){let[t,n,r]=await Promise.all([wr(e,"measurement"),wr(e,"assertion"),wr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Aw(e,t){return t===!0?{id:e.id}:e}async function QO(e,t){let n=t.authorization_decision;if(!n)return[];let r=await ei(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(a=>a.id===n),o=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!o.has(i.status))throw new _(`Assurance authorization ${n} must name a terminal Decision item`,g.USAGE);return[i.id]}async function eD(e,t){let n=ja(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>Dn))throw new _(`assurance verdict limit must be an integer from 1 through ${Dn}`,g.USAGE);let r=await Em(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Cw(e,t,n){try{return await Ua(()=>vm(e,t,n))}catch(r){if(!(r instanceof _)||r.context.reason!=="assurance_evaluation_refused")throw r;let i=["--pm-path",e,"assurance","list",t,"--output-budget","2000","--json"],o=K(i);throw Object.assign(r.context,{changed:!1,value:n,required:`Choose a configured ${t} declaration ID using the bounded discovery command.`,why:`The requested ${t} declaration does not exist. The registry and history were not changed.`,examples:[o],recovery:{next_best_command:o,suggested_retry:o,suggested_retry_args:i}}),r}}async function tD(e,t,n){if(e==="presets"){if(t.preset??t.id)return Qi(Rw(t.preset??t.id),vd(t));let i=Sr.map(o=>{let a=Qi(o,"pm-owner");return{id:o,title:a.title,description:a.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return On(()=>tp(n,Rw(t.preset??t.id),vd(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await np(await ei(n,{resolve_tree:!1,trigger:"derive"}),vd(t)),o=t.apply?await On(()=>rp(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...o?{applied:o}:{}}}if(!t.id)return rr("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new _("assurance promote requires --enforcement warn|block",g.USAGE);let r=await Cw(n,"assertion",t.id);return On(()=>ip(n,r,t.enforcement,{author:t.author,message:t.message}))}async function nD(e,t,n){if(!e.id)return rr("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new _("assurance run requires a trigger",g.USAGE);if(!Yt.includes(e.trigger))throw new _(`Unknown assurance trigger ${e.trigger}. Expected: ${Yt.join(", ")}`,g.USAGE);let i=e.trigger,[o,a]=await Promise.all([ZO(t),ei(t,{...n.workspace,tree_id:e.tree,trigger:i})]),s=await Ua(()=>ym(r,o,a,{trigger:i,dry_run:e.dry_run===!0}));return s.dry_run||await km(t,s,{author:e.author,message:e.message}),s}function Tw(e){throw e instanceof _?e:new _(e instanceof Error?e.message:"assurance risk request is invalid",g.USAGE)}function rD(e){if(e.limit!==void 0)throw new _(`assurance ${e.action} does not accept --limit; set limit inside the definition`,g.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new _(`assurance ${e.action} definition must be valid JSON`,g.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?Sw(t):Ti(t)}catch(n){if(e.action==="risk"&&n instanceof ou)throw new _(n.message,g.USAGE,{required:"Supply definition.policy with the project's declared recurrence policy and definition.change with the proposed change; no policy is inferred.",recovery:{suggested_retry:`pm assurance ${e.action} --help`,suggested_retry_args:["assurance",e.action,"--help"]}});return Tw(n)}}function iD(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function oD(e,t,n){let r=A(t.policy),i=yd?.pm_root===e?yd:void 0,o=new Map(n.map(d=>[d.id,VO("sha256").update(A([tu(d),Ci(d)])).digest("hex")])),a=i?.policy_serialized===r?i:void 0,s=a?iD(a,o):new Set,c=ru(t.policy,a?n.filter(d=>s.has(d.id)):n,a?{previous_index:a.index,changed_item_ids:[...s]}:{});return yd={pm_root:e,policy_serialized:r,item_fingerprints:o,index:c},c}async function aD(e,t){let n=rD(e),r=await ei(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?iu(oD(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):xw(n.policy,r.items,n)}catch(i){return Tw(i)}}async function sD(e,t={},n={}){let r=KO(e.action),i=M(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return tD(r,e,i);if(r==="verdicts")return eD(e,i);if(r==="run")return nD(e,i,n);if(["risk","lineages"].includes(r))return aD(e,i);let o=YO(e.kind);if(r==="list")return wr(i,o);if(!e.id)return rr("id",`assurance ${r} requires an id`,`pm assurance ${r} ${o} <id>`);let a=e.id;if(r==="show")return Cw(i,o,a);if(r==="remove"){let l=await On(()=>bm(i,o,a,{author:e.author,message:e.message}));return Aw(l,e.idOnly)}let s=XO(o,e.definition);if(s.id!==a)throw new _(`Assurance definition id ${s.id} does not match requested id ${a}`,g.USAGE);let c={author:e.author,message:e.message,...o==="assertion"?{authorized_decision_ids:await QO(i,s)}:{}},d=await On(()=>Ji(i,o,s,c));return Aw(d,e.idOnly)}function w5(e,t,n){let r={...e,...t};return sD({action:ee(r,"subcommand")??ee(r,"assuranceAction")??ee(r,"operation")??"",kind:ee(r,"kind"),id:ee(r,"id"),definition:r.definition,trigger:ee(r,"trigger"),tree:ee(r,"treeId")??ee(r,"tree"),gate:ee(r,"gate"),limit:ja(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:ee(r,"author"),message:ee(r,"message"),preset:ee(r,"preset"),owner:ee(r,"owner"),apply:r.apply===!0,enforcement:ee(r,"enforcement")},n)}import an from"node:fs/promises";import ni from"node:path";import ra from"node:fs/promises";import bd 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]="4fe37a62-2d0f-55f6-bb98-7162e7e8b8fe")}catch{}})();var cD=864e5;function dD(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function lD(e,t){let n;try{n=await ra.readdir(e,{withFileTypes:!0})}catch(i){if(j(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let o=bd.join(e,i.name),a;try{a=await ra.readdir(o)}catch(s){j(s)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let s of a)s.endsWith(".json")&&r.push(`${i.name}/${s}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function $w(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*cD,a=bd.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await lD(a,s.warnings);for(let d of c){let l=bd.join(a,d),u=`checkpoints/${d}`;s.scanned+=1,r?.onRead&&s.warnings.push(...await r.onRead(l));let m;try{m=await ra.readFile(l,"utf8")}catch(w){if(j(w)){s.scanned-=1;continue}s.warnings.push(`checkpoint_unreadable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=dD(m),p=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(p)){s.warnings.push(`checkpoint_unparseable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=i-p,y={file:u,created_at:f,age_seconds:Math.floor(h/1e3),stale:h>o,reason:h>o?"expired":"active"};if(!y.stale){s.retained.push(u),s.entries.push(y);continue}if(!n){try{await ra.unlink(l)}catch(w){if(!j(w)){s.warnings.push(`checkpoint_remove_failed:${d}`),s.retained.push(u),s.entries.push(y);continue}}r?.onWrite&&s.warnings.push(...await r.onWrite(l))}s.removed.push(u),s.entries.push(y)}return s}import kd from"node:fs/promises";import Ow 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]="ff5e2370-3b70-5f71-9492-72906f642c85")}catch{}})();var uD=1440*60*1e3,mD=new Set(["committed","compensated"]);function pD(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:n.abandonment!==void 0?"abandoned":typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function fD(e,t,n,r,i){let o=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(o))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let a=r-o;return mD.has(t)?a>i?{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"active"},remove:!1}}async function hD(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],o=pD(await kd.readFile(e,"utf8")),a=fD(t,o.status,o.updatedAt,r.nowMs,r.retentionMs);return a.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),a.remove&&!r.dryRun&&(await kd.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:a,warnings:i}}async function Dw(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*uD,a=Ow.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await kd.readdir(a)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(j(d))return s;throw d}for(let d of c){let l=Ow.join(a,d),u=`transactions/sdk/${d}`,m=await hD(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:o});s.warnings.push(...m.warnings),s.scanned+=1;let{decision:f}=m;if(!f.remove){s.retained.push(u),s.entries.push(f.entry);continue}s.removed.push(u),s.entries.push(f.entry)}return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6803646e-4b97-5f28-aeda-78f54377a185")}catch{}})();var ti=["index","embeddings","runtime","locks","checkpoints","transactions"],_D=1440*60*1e3,Pw=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"},{scope:"runtime",relativePath:"runtime/history-stream-summary.json",kind:"file"}];async function gD(e,t,n){let r=t.relativePath,i=ni.join(e,r),o=await We({path:i,scope:"project"});if(t.scope==="runtime"&&await Lw(e))return{removed:!1,redirected:!0,warnings:o};try{let a=await an.lstat(i);if(t.kind==="file"&&!a.isFile())return{removed:!1,warnings:[...o,`not_a_file:${r}`]};if(t.kind==="directory"&&!a.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await an.unlink(i):await an.rm(i,{recursive:!0,force:!0});let s=await Y({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...s]}}catch(a){if(j(a))return{removed:!1,warnings:o};throw a}}async function yD(e,t,n){let r=[],i=[],o=[],a=!1;for(let s of Pw.filter(c=>t.includes(c.scope))){if(s.scope==="runtime"&&a){i.push(s.relativePath);continue}let c=await gD(e,s,n);a||=c.redirected===!0,(c.removed?r:i).push(s.relativePath),o.push(...c.warnings)}if(t.includes("runtime")&&!a&&(a=await Lw(e)),a)o.push("redirected_runtime_directory:runtime");else if(t.includes("runtime")){let s=await wD(e,n);r.push(...s.removed),i.push(...s.retained),o.push(...s.warnings)}return{removed:r,retained:i,warnings:o}}async function Lw(e){try{return!(await an.lstat(ni.join(e,"runtime"))).isDirectory()}catch(t){if(j(t))return!1;throw t}}async function wD(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],o=[],a=Date.now()-_D;for(let s of n){let c=ni.join(e,s.relativePath);if(!await O(c))continue;let d=(await an.readdir(c)).filter(l=>l.startsWith(s.prefix)).sort();for(let l of d){let u=ni.posix.join(s.relativePath,l),m=ni.join(c,l);o.push(...await We({path:m,scope:"project"}));let f=await an.stat(m).catch(p=>{if(!j(p))throw p});if(f){if(f.mtimeMs>a){i.push(u);continue}r.push(u),!t&&(await an.rm(m,{recursive:!0,force:!0}),o.push(...await Y({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:o}}function vD(e){if(!e||e.length===0)return[...ti];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new _(`--scope requires at least one value (${ti.join(",")})`,g.USAGE);let n=new Set;for(let r of t){if(!ti.includes(r))throw new _(`Invalid --scope value "${r}". Expected one or more of: ${ti.join(", ")}`,g.USAGE);n.add(r)}return ti.filter(r=>n.has(r))}function bD(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),e.removed.includes("runtime/history-stream-summary.json")&&t.push('History stream summary was removed; the next "pm activity" or "pm context" read parses every history stream once to rebuild it.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function z5(e,t={}){let n=M(process.cwd(),e.path);await re(n);let r=await T(n),i=t.dryRun===!0,o=vD(t.scope),{removed:a,retained:s,warnings:c}=await yD(n,o,i),d;if(o.includes("locks")){let f=await qp(n,{dryRun:i,hooks:{onRead:p=>We({path:p,scope:"project"}),onWrite:p=>Y({path:p,scope:"project",op:"gc:lock_remove"})}});a.push(...f.removed),s.push(...f.retained),c.push(...f.warnings),d={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length}}let l;if(o.includes("transactions")){let f=r.checkpoints.retention_days,p=await Dw(n,{dryRun:i,retentionDays:f,hooks:{onRead:h=>We({path:h,scope:"project"}),onWrite:h=>Y({path:h,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...p.removed),s.push(...p.retained),c.push(...p.warnings),l={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length,retention_days:f}}let u;if(o.includes("checkpoints")){let f=r.checkpoints.retention_days,p=await $w(n,{dryRun:i,retentionDays:f,hooks:{onRead:h=>We({path:h,scope:"project"}),onWrite:h=>Y({path:h,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...p.removed),s.push(...p.retained),c.push(...p.warnings),u={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length,retention_days:f}}c.push(...await Ri({mode:i?"gc:dry-run":"gc",total_items:Pw.filter(f=>o.includes(f.scope)).length}));let m=bD({dryRun:i,scopes:o,removed:a});return{ok:c.length===0,dry_run:i,scope:o,removed:a,retained:s,warnings:c,...d?{locks:d}:{},...u?{checkpoints:u}:{},...l?{transactions:l}:{},guidance:m,generated_at:C()}}import{execFile as kD}from"node:child_process";import ED from"node:path";import{promisify as SD}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]="7fe99df0-8454-5667-9205-0b861ba212d1")}catch{}})();var xD=SD(kD),Mw="@unbrained/pm-cli",ID="latest",RD={global:["--global"],project:[]};function Nw(e){let t=e.project===!0||e.local===!0||e.scope==="project",n=e.global===!0||e.scope==="global";if(t&&n)throw new _('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"}function oa(e){return e.trim().toLowerCase()}function jw(e,t){let n=oa(t);return[e.name,e.directory,e.source.input,e.source.location,e.source.package,e.source.repository,e.source.owner&&e.source.repo?`${e.source.owner}/${e.source.repo}`:void 0].some(r=>typeof r=="string"&&oa(r)===n)}function AD(e,t){let n=M(process.cwd(),t.path),r=mn(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function CD(e,t,n){try{let r=await xD(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:r.stdout,stderr:r.stderr}}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr??""):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new _(`Command failed: ${e} ${t.join(" ")}
71
+ ${o}`,g.GENERIC_FAILURE)}}function aa(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():ID}function ia(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():Mw}async function TD(e,t){let n=e.commandRunner??CD,r=ia(e),i=aa(e),o=`${r}@${i}`,a=["npm","install","-g",o];e.repair===!0&&a.push("--force");let s=zd(import.meta.url,["../../.."]),c={requested:!0,status:"planned",package:r,target:o,command:a,before_version:s,...r===Mw?{migration_guidance:["Calendar scheduling commands are package-owned. If calendar is absent, run pm package install calendar --project; use pm calendar meet, pm calendar event, or pm calendar remind."]}:{},repair:e.repair===!0};if(t)return c;try{await n(a[0],a.slice(1));let d=await n("pm",["--version"]);return{...c,status:"updated",after_version:d.stdout.trim()||void 0}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function $D(e){return ED.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function OD(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!$D(n)&&e.package&&e.package.trim().length>0?`npm:${e.package.trim()}@${t}`:e.input.startsWith("npm:")?e.input:`npm:${e.input}`}return e.input}async function DD(e,t){let n=OD(e,t);return e.kind!=="local"||await O(n)?n:await O(e.location)?e.location:n}function PD(e,t,n,r){let i=["pm","package","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&r&&r.trim().length>0&&i.push("--ref",r.trim()),i}async function Fw(e,t){let n=AD(e,t);return(await be(n.selected_root)).state.entries.filter(r=>r.scope===e)}async function LD(e,t,n){let r=await Fw(e,t);return r.find(i=>jw(i,n.name))??r.find(i=>oa(i.directory)===oa(n.directory))}async function ND(e,t,n,r,i){let o=aa(t),a=await DD(e.source,o),s=PD(e.source,a,r,e.source.ref),c={name:e.name,directory:e.directory,scope:r,source:e.source,status:"planned",command:s,previous_version:e.manifest_version};if(i)return c;try{await Zs(a,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await LD(r,n,e);return{...c,status:"updated",installed_version:d?.manifest_version}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function MD(e,t,n,r){let i=[n?e.status:void 0,...t.map(o=>o.status)].filter(o=>typeof o=="string");return{requested_cli:n,requested_packages:r,planned:i.filter(o=>o==="planned").length,updated:i.filter(o=>o==="updated").length,skipped:i.filter(o=>o==="skipped").length,failed:i.filter(o=>o==="failed").length}}async function Y5(e,t,n){let r=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&t.packagesOnly===!0){let m=["package","upgrade",...r?[r]:[],"--packages-only","--dry-run",...RD[Nw(t)]];throw new _('Options "--cli-only" and "--packages-only" are mutually exclusive.',g.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:K(m),suggested_retry_args:m}})}let i=Nw(t),o=t.dryRun===!0;if(t.cliOnly===!0&&r)throw new _('A package target cannot be used with "--cli-only".',g.USAGE);let a=!(t.packagesOnly===!0||r),s=t.cliOnly!==!0,c=a?await TD(t,o):{requested:!1,status:"skipped",package:ia(t),target:`${ia(t)}@${aa(t)}`,command:["npm","install","-g",`${ia(t)}@${aa(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await Fw(i,n):[];if(r&&(d=d.filter(m=>jw(m,r)),d.length===0))throw new _(`Managed package "${r}" was not found in ${i} scope.`,g.NOT_FOUND);let l=[];for(let m of d)l.push(await ND(m,t,n,i,o));let u=MD(c,l,a,s);return{ok:u.failed===0,action:"upgrade",dry_run:o,scope:i,target:r,cli:c,packages:l,summary:u}}import{createHash as jD}from"node:crypto";import{isUtf8 as FD}from"node:buffer";import ri from"node:fs/promises";import Ed 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]="a049f799-3807-59b5-96de-51e900798779")}catch{}})();async function Hw(e){try{return(await ri.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(j(t))return[];throw t}}function HD(e,t,n,r){let i=t.at(-1),o;for(let c=t.length-1;c>=0;c-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[c].op)){o=t[c];break}let a=t[0]?.context?.history_compaction,s=typeof a=="object"&&a!==null&&"pruned_stream_digest"in a&&typeof a.pruned_stream_digest=="string"?a.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:n,stream_digest:r,latest_after_hash:i?.after_hash??null,latest_record_hash:i?.record_hash??null,latest_hash_algorithm:i?we(i.hash_algorithm):null,rewrite_count:t.reduce((c,d)=>c+(d.reanchor_evidence?.length??0),0),checkpoint_digest:s,last_maintenance:o?{op:o.op,ts:o.ts,record_hash:o.record_hash??null}:null}}function UD(e,t,n){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!FD(t))return null;let r=[];for(let i of t.toString("utf8").split(/\r?\n/u)){if(!i.trim())continue;let o=JSON.parse(i);if(typeof o!="object"||o===null||Array.isArray(o))return null;let a=o;if(![a.op,a.author,a.ts,a.before_hash,a.after_hash].every(s=>typeof s=="string")||!Array.isArray(a.patch))return null;r.push(a)}return dr(r).ok?HD(e,r,t.length,n):null}catch{return null}}async function Sd(e,t){if(!(await ri.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let n=Ed.join(e,"history"),r=await Hw(n),i=new Map,o=[];for(let a of r){let s=a.slice(0,-6),c={id:s,digest:null,stream:null};o.push(c);let d=Ed.join(n,a);try{let l=await ri.lstat(d);if(i.set(a,A([l.ino,l.size,l.mtimeMs,l.ctimeMs])),!l.isFile())continue;let u=await ri.readFile(d);c.digest=jD(t).update(u).digest("hex"),c.stream=UD(s,u,c.digest)}catch{}}if(A(r)!==A(await Hw(n)))throw new TypeError("attestation history inventory changed during read; retry");for(let[a,s]of i){let c=await ri.lstat(Ed.join(n,a));if(s!==A([c.ino,c.size,c.mtimeMs,c.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54d3c0f4-e663-5e31-aa4e-45ea2f6aaf75")}catch{}})();function xd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Id(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function ir(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function zD(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:ir(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||ir(e.latest_record_hash,e.latest_hash_algorithm))}function WD(e){return e===null?!0:!xd(e)||!Id(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&Ot(e.ts)&&(e.record_hash===null||ir(e.record_hash,"sha256")||ir(e.record_hash,"sha512"))}function qD(e,t){return!xd(e)||!Id(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)&&ir(e.stream_digest,t)&&zD(e)&&(e.checkpoint_digest===null||ir(e.checkpoint_digest,"sha256"))&&WD(e.last_maintenance)}function Uw(e){if(!xd(e)||!Id(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==Ma.format||e.version!==1||typeof e.generated_at!="string"||!Ot(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,n;for(let o of e.streams){if(!qD(o,t))throw new TypeError("Invalid history attestation stream");let a=o.id;if(n!==void 0&&a<=n)throw new TypeError("Invalid history attestation stream order");n=a}let{workspace_digest:r,...i}=e;if(ka(A(i),t)!==r)throw new TypeError("History attestation rollup mismatch");return e}async function zw(e={}){let t=we(e.hashAlgorithm),n=e.generatedAt??C();if(!Ot(n))throw new TypeError("Invalid history attestation timestamp");let r=await Sd(M(e.cwd??process.cwd(),e.pmRoot),t),i=r.filter(a=>a.stream===null);if(i.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${i.map(a=>a.id).join(", ")}`);let o={format:Ma.format,version:1,hash_algorithm:t,generated_at:n,streams:r.map(a=>a.stream)};return Uw({...o,workspace_digest:ka(A(o),t)})}async function Ww(e,t={}){let n=Uw(e),r=await Sd(M(t.cwd??process.cwd(),t.pmRoot),n.hash_algorithm),i=new Map(r.map(l=>[l.id,l])),o=new Map(n.streams.map(l=>[l.id,l])),a=n.streams.filter(l=>!i.has(l.id)).map(l=>l.id),s=r.filter(l=>!o.has(l.id)).map(l=>l.id),c=r.filter(l=>l.stream===null).map(l=>l.id),d=[];for(let l of n.streams){let u=i.get(l.id);u&&(u.digest!==l.stream_digest||A(u.stream)!==A(l))&&d.push({id:l.id,before_digest:l.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:a.length+s.length+c.length+d.length===0,workspace_digest:n.workspace_digest,streams_checked:r.length,changed_streams:d.map(l=>l.id),missing_streams:a,added_streams:s,invalid_streams:c,transitions:d}}import qw from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bca4afb-f1cc-5627-a377-b30e8005a284")}catch{}})();async function vJ(e,t){for(let r of["verify","output","hashAlgorithm"]){let i=e[r];if(!(r==="verify"&&typeof i=="object"&&i!==null)&&i!==void 0&&(typeof i!="string"||i.trim().length===0))throw new _(`history attest ${r} requires a nonempty string.`,g.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new _("history attest --verify cannot be combined with --output or --hash-algorithm",g.USAGE);let r;try{r=typeof e.verify=="string"?JSON.parse(await qw.readFile(e.verify,"utf8")):e.verify}catch{throw new _("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",g.USAGE)}return Ww(r,{pmRoot:t.path})}let n=await zw({pmRoot:t.path,hashAlgorithm:we(e.hashAlgorithm)});if(e.output===void 0)return n;try{await qw.writeFile(e.output,`${JSON.stringify(n,null,2)}
72
+ `,{flag:"wx",mode:384})}catch{throw new _("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",g.USAGE)}return{output:e.output,workspace_digest:n.workspace_digest,streams:n.streams.length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a19731b3-577b-5705-b105-4626b90f3ff4")}catch{}})();function Gw(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function Bw(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?K([...r,"merge","report"],n):e==="history_evidence_invalid"?K([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?K([...r,"merge","reconcile"],n):e==="history_repair_required"?K([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?K([...r,"merge","install"],n):null}function Jw(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(n=>typeof n=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(n=>typeof n=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function DJ(e){let t=M(process.cwd(),e.path);await re(t);let n=await T(t),r=z(n,F()),i=[],o=await Ko({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),a=await Nt(t),[s,c,d,l]=await Promise.all([Tn(t,Cn(n),{gitWorkspaceRoot:a}),a===null?Promise.resolve(null):$n(a),St(a??t,{includeLossless:!0,pmRoot:t}),Yo(t,o,!1)]),{pendingDecisions:u,lossless:m}=Yn(d.receipts),f=[...new Set(u.map(w=>w.item_id))].sort((w,v)=>w.localeCompare(v)),p=l.check.details,h=Jw(p),y=Gw({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:m.length,historyEvidenceValid:h.evidence_valid,driftedItemCount:h.drifted_item_count,fence:s,drivers:c});return{ok:y==="ready",state:y,merge_fence:{committed:s,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:f.slice(0,25),pending_item_ids_truncated:f.length>25,lossless_count:m.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:h,next_action:{command:Bw(y,t),reason:y},warnings:[...new Set(i)].sort((w,v)=>w.localeCompare(v)),generated_at:C()}}function PJ(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
73
+ `)}var LJ={commandForWorkspacePositionState:Bw,normalizeWorkspaceHistoryDrift:Jw,selectWorkspacePositionState:Gw};import GD from"node:fs/promises";import ii 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]="f02db25d-bedb-5411-b50a-de0fea51a117")}catch{}})();var Rd="index/manifest.json",Ad="search/embeddings.jsonl",BD="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function JD(e){return e.progress===!0||process.stderr.isTTY===!0}function ce(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
74
+ `)}catch{}}function VD(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new _("Reindex mode must be one of keyword|semantic|hybrid",g.USAGE)}async function KD(e,t,n,r){let i=[];return{candidates:await Cu(e,t,n,i,r),warnings:i}}async function Td(e,t,n,r,i){let o=ln(F()),a=[];for(let s of t)if(!(i&&!i.has(s.metadata.id))){if(typeof s.body=="string"){a.push({metadata:s.metadata,body:s.body});continue}try{let c=await GD.readFile(s.item_path,"utf8"),d=Dt(c,{format:s.item_format,schema:n,extensionFieldNames:o,onWarning:l=>r.push(l)});a.push({metadata:s.metadata,body:d.body})}catch{r.push(`item_list_item_read_failed:${ii.relative(e,s.item_path)}`),a.push({metadata:s.metadata,body:""})}}return a}function YD(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:Ou(e,{fields:n})}}var or=X;function XD(e){let t=F(),n=or(e.search?.provider);if(!n)return null;let r=pu(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=or(i.name)??or(r.definition.name);if(!o)return null;let a=i.embedBatch,s=i.embed_batch,c=i.embed,d=typeof a=="function"?a:typeof s=="function"?s:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:o,embedBatch:d,embed:l}}function ZD(e){let t=F(),n=or(e.vector_store?.adapter);if(!n)return null;let r=fu(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=or(i.name)??or(r.definition.name);if(!o)return null;let a=i.upsert,s=i.delete;return{adapterName:o,...typeof a=="function"?{upsert:a}:{},...typeof s=="function"?{delete:s}:{}}}function Cd(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new _(`Invalid vector returned by ${t}`,g.GENERIC_FAILURE);return e}async function QD(e,t,n){let r=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let o=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:r}));if(!Array.isArray(o))throw new _(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,g.GENERIC_FAILURE);return o.map((a,s)=>Cd(a,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new _(`Extension search provider "${e.name}" does not implement embed/embedBatch`,g.GENERIC_FAILURE);let i=[];for(let[o,a]of n.entries()){let s=await Promise.resolve(e.embed({input:a,settings:t,model:r}));i.push(Cd(s,`extension search provider "${e.name}" embed output at index ${o}`))}return i}function Vw(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function Kw(e,t,n){let r=n?Kt(n.name,Vw(e)):t?Kt(t.name,t.model):null;if(!r)throw new _("No embedding identity available for semantic reindex mode",g.USAGE);return r}function eP(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function Yw(e,t,n,r,i,o,a,s){let c=r?.name??n?.name,d=Du(c,e.search.embedding_corpus_max_characters).maxCharacters,l=$a(e),u=i.map(p=>Pu(p,{providerName:c,maxCharacters:d,fields:l})),m=[],f=null;if(r)try{m=await QD(r,e,u),f=Kt(r.name,Vw(e))}catch(p){if(!n)throw new _(`Extension search provider "${r.name}" failed to generate embeddings: ${p instanceof Error?p.message:String(p)}`,g.GENERIC_FAILURE);o.push(`Extension search provider "${r.name}" failed; falling back to built-in provider (${p instanceof Error?p.message:String(p)})`)}if(m.length===0){if(!n)throw new _(`No embedding executor available for reindex mode '${t}'`,g.USAGE);let p=await Lu(n,e,u,{onProgress:h=>{h.phase==="complete"&&(a.batches_completed=h.batch_index),ce(s,`embedding_batch_${h.phase} batch=${h.batch_index}/${h.batch_total} size=${h.batch_size} completed_inputs=${h.completed_inputs}/${h.total_inputs}`)}});o.push(...p.warnings),a.batching=p.receipt,m=p.vectors,f=Kt(n.name,n.model)}if(ce(s,`embedding_complete vectors=${m.length}`),m.length!==i.length)throw new _(`Embedding output size mismatch (expected ${i.length}, received ${m.length})`,g.GENERIC_FAILURE);if(!f)throw new _(`No embedding identity available for reindex mode '${t}'`,g.USAGE);return{vectors:m,embeddingIdentity:f}}async function tP(e,t,n,r,i,o){let a=Object.keys(n);if(t){if(a.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:a.sort((s,c)=>s.localeCompare(c)),settings:r}))}catch(s){throw new _(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,g.GENERIC_FAILURE)}else a.length>0&&i.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${a.length}`);if(!e)return}e&&await ju(e,a,{},o)}async function Xw(e,t,n,r,i){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:r}))}catch(o){throw new _(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${o instanceof Error?o.message:String(o)}`,g.GENERIC_FAILURE)}else i.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Mu(e,n)}}function nP(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function rP(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(r=>({id:r.metadata.id,type:r.metadata.type,status:r.metadata.status,priority:r.metadata.priority,updated_at:r.metadata.updated_at}))}}function iP(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=fr(e.settings);if(!t.active&&!e.extensionEmbedding)throw new _(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,g.USAGE);let n=Fi(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new _(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,g.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function oP(e){let t=z(e.settings,F()),n=await KD(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(r=>({metadata:r.metadata,body:typeof r.body=="string"?r.body:""}))}}async function aP(e){let t=await Rn(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return Kw(e.settings,fr(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&In(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(BD))}async function sP(e){let t=await Rn(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=Kw(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(d=>d.metadata.id)),i=eP(t.entries,r),o=In(t.embedding,n);e.forceFullSemantic&&!o&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let a=e.forceFullSemantic||o?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),s=new Set(a.map(d=>d.metadata.id)),c=s.size>0?await Td(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:i,resetRequired:o,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function cP(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await Td(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,ce(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await Yw(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:Oa(r.vectors,"Reindex embeddings")}}async function dP(e){let t=await Yw(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=Oa(n,"Reindex embeddings");if(!(!e.resetRequired&&(In(e.ledgerEmbedding,r)||Hu(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let o=await cP(e);return n=o.vectors,r=o.embeddingIdentity,i=o.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:o.staleDocuments,vectorDimension:i,resetRequired:!0}}async function lP(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(ce(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new _(`Extension vector adapter "${t}" does not support upserting vectors.`,g.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,ce(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof _)throw t;if(!e.activeVectorStore)throw new _(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,g.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),ce(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){ce(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Nu(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,ce(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new _(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,g.USAGE)}function uP(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:Cd(t[r],`reindex embeddings output at index ${r}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function mP(e){ce(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await dP({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(ce(e.progressEnabled,"vector_reset_start"),await tP(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),ce(e.progressEnabled,"vector_reset_complete")):await Xw(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=uP(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await lP({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:Fu(t.embeddingIdentity,t.vectorDimension)}}async function pP(e){let t=await sP(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(o=>[o.metadata.id,o.metadata.updated_at]));if(ce(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return ce(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await Xw(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await mP({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let i=new Map(r.staleDocuments.map(o=>[o.metadata.id,o]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(o=>i.get(o.metadata.id)??o),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:r.embeddingMetadata}}async function fP(e){let t=ii.join(e.pmRoot,Rd),n=ii.join(e.pmRoot,Ad),r=$a(e.settings),i=e.documentsForKeywordArtifacts.map(a=>JSON.stringify(YD(a,e.mode,r))).join(`
75
+ `);ce(e.progressEnabled,"writing keyword artifacts"),await Q(t,`${JSON.stringify(e.manifest,null,2)}
76
+ `),await Q(n,`${i}
77
+ `);let o=[];if(e.mode!=="keyword")try{ce(e.progressEnabled,"writing vectorization status ledger"),await Uu(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(a){o.push(`search_vectorization_status_ledger_write_failed:${a instanceof Error?a.message:String(a)}`)}return o}async function UJ(e,t){let n=VD(e.mode),r=JD(e),i=e.full===!0;ce(r,`start mode=${n}`);let o=M(process.cwd(),t.path);await re(o);let a=Ni(await T(o)).settings,s=null;try{s=await oe(o,vu,a.locks.ttl_seconds,W(void 0,"pm-reindex"),!1,a.governance.force_required_for_stale_lock,a.locks.wait_ms)}catch(c){throw c instanceof _&&c.exitCode===g.CONFLICT?new _("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",g.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=XD(a),d=ZD(a),l=iP({requestedMode:n,pmRoot:o,settings:a,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;ce(r,"loading item corpus");let m=await oP({pmRoot:o,settings:a}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;ce(r,`loaded_items=${h.length}`);let y=C(),w=rP(u,y,h),v=ii.join(o,Rd),k=ii.join(o,Ad),E=u==="keyword"?await Td(o,p,a.schema,f):h,x=[],$={},S=null,b=nP(u);if(u==="keyword"&&await aP({pmRoot:o,settings:a,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let I=await pP({pmRoot:o,settings:a,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:p,metadataDocuments:h,documentsForKeywordArtifacts:E,forceFullSemantic:i,reindexWarnings:f,semanticWarnings:x,semanticSummary:b,progressEnabled:r});E=I.documentsForKeywordArtifacts,$=I.vectorizationLedgerEntries,S=I.vectorizationEmbeddingMetadata}let D=await fP({pmRoot:o,mode:u,manifest:w,documentsForKeywordArtifacts:E,settings:a,vectorizationLedgerEntries:$,vectorizationEmbeddingMetadata:S,progressEnabled:r}),U=[...await Y({path:v,scope:"project",op:"reindex:manifest"}),...await Y({path:k,scope:"project",op:"reindex:embeddings"}),...await Ri({mode:u,total_items:h.length})];return ce(r,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:Rd,embeddings:Ad},warnings:[...f,...x,...D,...U],generated_at:y}}finally{await s?.()}}export{P as a,Se as b,rt as c,On as d,Ua as e,cm as f,Yt as g,za as h,cv as i,Ga as j,Ba as k,mm as l,Pn as m,yr as n,Va as o,Rv as p,ym as q,wr as r,vm as s,Ji as t,Ka as u,bm as v,km as w,Em as x,TP as y,ns as z,Nm as A,WP as B,zv as C,qP as D,qv as E,JP as F,Hm as G,Jv as H,pL as I,Yk as J,qN as K,JN as L,VN as M,$r as N,KN as O,YN as P,XN as Q,ZN as R,QN as S,eM as T,tM as U,nM as V,rM as W,iM as X,oM as Y,bh as Z,Zs as _,E1 as $,$p as aa,Xv as ba,Bm as ca,xL as da,Er as ea,IL as fa,ib as ga,ob as ha,RL as ia,ab as ja,AT as ka,wy as la,VT as ma,Ey as na,OL as oa,Qm as pa,xy as qa,Xq as ra,Zq as sa,Sr as ta,Qi as ua,tp as va,np as wa,rp as xa,ip as ya,cp as za,cs as Aa,lp as Ba,pp as Ca,fp as Da,xb as Ea,_p as Fa,Ht as Ga,lU as Ha,uU as Ia,mU as Ja,pU as Ka,bU as La,$_ as Ma,Po as Na,GU as Oa,St as Pa,H_ as Qa,BU as Ra,JU as Sa,RR as Ta,$R as Ua,G_ as Va,Rb as Wa,ls as Xa,Kr as Ya,yW as Za,wW as _a,to as $a,no as ab,Lg as bb,T2 as cb,Ng as db,jg as eb,Fg as fb,zg as gb,qg as hb,p$ as ib,f$ as jb,iG as kb,oG as lb,aG as mb,sG as nb,Ay as ob,_$ as pb,Ty as qb,Vo as rb,Oy as sb,Dy as tb,Py as ub,y$ as vb,v$ as wb,k$ as xb,cG as yb,E$ as zb,nd as Ab,rd as Bb,wG as Cb,vG as Db,bG as Eb,Q$ as Fb,NB as Gb,bw as Hb,ei as Ib,Sw as Jb,xw as Kb,Iw as Lb,wd as Mb,sD as Nb,w5 as Ob,z5 as Pb,Y5 as Qb,Uw as Rb,zw as Sb,Ww as Tb,vJ as Ub,DJ as Vb,PJ as Wb,LJ as Xb,UJ as Yb};
78
+ //# sourceMappingURL=chunk-5C5TK3ET.js.map