scip-query 0.19.6 → 0.19.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (304) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +28 -15
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/chunk-2465DLHK.js +3 -0
  5. package/dist/{chunk-2CVXCGL4.js → chunk-24GTWJ3N.js} +2 -2
  6. package/dist/{chunk-XVJ3V7LM.js → chunk-2SNGN6U4.js} +2 -2
  7. package/dist/{chunk-FKGN4A4E.js → chunk-2U3OLUNJ.js} +2 -2
  8. package/dist/{chunk-UUJBLG6J.js → chunk-33KUO7CG.js} +2 -2
  9. package/dist/{chunk-N3SE646F.js → chunk-33XTHFKR.js} +2 -2
  10. package/dist/{chunk-WXAAURU7.js → chunk-3EDFLQ6A.js} +2 -2
  11. package/dist/chunk-3ZSJ3PWF.js +16 -0
  12. package/dist/{chunk-G4UQL4CP.js → chunk-43KC6EQZ.js} +2 -2
  13. package/dist/{chunk-NQLSSVOB.js → chunk-464PLI5O.js} +2 -2
  14. package/dist/chunk-46XGSFNI.js +2 -0
  15. package/dist/{chunk-NN4ZIRPK.js → chunk-47BU5Z4T.js} +2 -2
  16. package/dist/chunk-4BV4QAZJ.js +5 -0
  17. package/dist/chunk-4YTUWQ6M.js +18 -0
  18. package/dist/{chunk-LMFVTUW2.js → chunk-5ML2BNRH.js} +2 -2
  19. package/dist/{chunk-OP3MTFJR.js → chunk-5YLUDDAF.js} +2 -2
  20. package/dist/chunk-67QRR5YC.js +6 -0
  21. package/dist/{chunk-273W2U4Y.js → chunk-6GXYN7YA.js} +2 -2
  22. package/dist/{chunk-JELJLXEE.js → chunk-6M7RONVB.js} +2 -2
  23. package/dist/{chunk-MLGTCX56.js → chunk-7FT5Y65S.js} +2 -2
  24. package/dist/{chunk-F42A3AKG.js → chunk-7KYNAMMH.js} +2 -2
  25. package/dist/{chunk-VP542C25.js → chunk-7LSVMFX7.js} +2 -2
  26. package/dist/{chunk-YWB2EBNB.js → chunk-7QHY3H7P.js} +2 -2
  27. package/dist/{chunk-UQK5CRUK.js → chunk-7RAG65VK.js} +2 -2
  28. package/dist/{chunk-CYJM7CYF.js → chunk-7SWJEWJF.js} +2 -2
  29. package/dist/{chunk-47X75ZKH.js → chunk-7VCOXZH3.js} +2 -2
  30. package/dist/chunk-A2TNXAXO.js +8 -0
  31. package/dist/{chunk-TYQ76QHQ.js → chunk-A3QXWFBK.js} +2 -2
  32. package/dist/{chunk-S2GP3CU3.js → chunk-AA4UWRNL.js} +2 -2
  33. package/dist/{chunk-OBKDTVZ3.js → chunk-ACAM6O5R.js} +2 -2
  34. package/dist/chunk-AQOFWNQJ.js +1 -0
  35. package/dist/chunk-AZFUMCQB.js +2 -0
  36. package/dist/{chunk-IYAOX36F.js → chunk-BDOIKGDI.js} +2 -2
  37. package/dist/{chunk-7E3TH5ZN.js → chunk-BNXICU42.js} +2 -2
  38. package/dist/chunk-C5Q44Q5D.js +3 -0
  39. package/dist/{chunk-OQ2A4G2G.js → chunk-CTF2GDEX.js} +2 -2
  40. package/dist/chunk-DHEQMPLW.js +2 -0
  41. package/dist/{chunk-EVOC5I5I.js → chunk-DQBCO2UY.js} +2 -2
  42. package/dist/{chunk-YLVE3SXZ.js → chunk-DQGSM7RZ.js} +2 -2
  43. package/dist/chunk-E2LAW7SL.js +30 -0
  44. package/dist/chunk-E3HYEQO7.js +2 -0
  45. package/dist/chunk-E4NFOAD4.js +6 -0
  46. package/dist/chunk-E5HNT4X2.js +3 -0
  47. package/dist/{chunk-6XHTISLI.js → chunk-ELLMY7XJ.js} +2 -2
  48. package/dist/chunk-FD3HFKXR.js +5 -0
  49. package/dist/{chunk-RJHCPSZ7.js → chunk-FIJCV235.js} +2 -2
  50. package/dist/{chunk-KLVJABXA.js → chunk-FJ5UDTQF.js} +2 -2
  51. package/dist/{chunk-SHKZ7OVJ.js → chunk-GHKEJTCE.js} +2 -2
  52. package/dist/{chunk-JERWGHQT.js → chunk-GLZTVKAB.js} +3 -3
  53. package/dist/{chunk-A43URCQ3.js → chunk-GNC4JVAN.js} +2 -2
  54. package/dist/chunk-HIB452NU.js +949 -0
  55. package/dist/{chunk-U5CNPPTZ.js → chunk-HZYDQPNY.js} +2 -2
  56. package/dist/chunk-IF6FP6B2.js +66 -0
  57. package/dist/{chunk-CSTYYXKC.js → chunk-JAY7YWS3.js} +2 -2
  58. package/dist/{chunk-6XFC7PQ5.js → chunk-JHF3E4YM.js} +2 -2
  59. package/dist/chunk-JORHF5AL.js +108 -0
  60. package/dist/{chunk-QBYYWGAT.js → chunk-K2WO7XY7.js} +2 -2
  61. package/dist/chunk-KFZNKUNT.js +2 -0
  62. package/dist/{chunk-J7VT2CRB.js → chunk-KJ2IIBZN.js} +2 -2
  63. package/dist/{chunk-336DC5NJ.js → chunk-KKME5ZAI.js} +2 -2
  64. package/dist/chunk-KSGTULOS.js +9 -0
  65. package/dist/{chunk-E2ZXPB7J.js → chunk-KXDJAG4N.js} +3 -3
  66. package/dist/{chunk-Z2LHPIOM.js → chunk-L4S2A7BV.js} +2 -2
  67. package/dist/chunk-LP3ARJKF.js +8 -0
  68. package/dist/chunk-LSOR3LQG.js +3 -0
  69. package/dist/{chunk-FHCTEANE.js → chunk-MLFZP76A.js} +2 -2
  70. package/dist/{chunk-RBFFD4V2.js → chunk-MNSTUIDD.js} +2 -2
  71. package/dist/{chunk-3OIKRYU5.js → chunk-MSBDMFER.js} +2 -2
  72. package/dist/{chunk-7LABSJSR.js → chunk-MZZBAITE.js} +5 -5
  73. package/dist/{chunk-QQWOFXNW.js → chunk-NE3TZUCI.js} +2 -2
  74. package/dist/{chunk-JZNLMHWY.js → chunk-NTUMF2X3.js} +2 -2
  75. package/dist/{chunk-DD5BOU5I.js → chunk-O23I56NA.js} +2 -2
  76. package/dist/{chunk-YHXBD52M.js → chunk-O3O4XXO6.js} +2 -2
  77. package/dist/{chunk-FQTPPXNA.js → chunk-OUBAF226.js} +2 -2
  78. package/dist/chunk-P3UO3EH3.js +2 -0
  79. package/dist/{chunk-5OC3HWP5.js → chunk-QGGLL3UH.js} +2 -2
  80. package/dist/chunk-QIQ63BHW.js +16 -0
  81. package/dist/{chunk-RWRLUZ6U.js → chunk-QJIVBYEK.js} +2 -2
  82. package/dist/chunk-QOXBSI6G.js +20 -0
  83. package/dist/{chunk-7Q6VYYCH.js → chunk-QXK6UUSM.js} +2 -2
  84. package/dist/{chunk-ZTTISZ7J.js → chunk-RA3AYNWP.js} +2 -2
  85. package/dist/chunk-RJMDJR3A.js +2 -0
  86. package/dist/{chunk-TFUU5MQQ.js → chunk-RLH5VUMG.js} +2 -2
  87. package/dist/{chunk-OHWZKLVA.js → chunk-S4S2WOIX.js} +2 -2
  88. package/dist/{chunk-YTUD45PU.js → chunk-SERUIGV5.js} +2 -2
  89. package/dist/{chunk-2OXVAGGT.js → chunk-SMQWE25B.js} +2 -2
  90. package/dist/{chunk-K42M2KWT.js → chunk-TAVELHYR.js} +2 -2
  91. package/dist/{chunk-MGBJHRFB.js → chunk-TWMJ3Y3G.js} +2 -2
  92. package/dist/chunk-VAXNI5NE.js +146 -0
  93. package/dist/chunk-VVY2G5ET.js +2 -0
  94. package/dist/{chunk-XF3KLXN3.js → chunk-W3DBTGL4.js} +2 -2
  95. package/dist/{chunk-26X7KCJR.js → chunk-WANA4KAQ.js} +2 -2
  96. package/dist/chunk-WJL2L6MV.js +60 -0
  97. package/dist/chunk-WUW7YUAH.js +11 -0
  98. package/dist/{chunk-PC44K7RF.js → chunk-WWKWUPSU.js} +2 -2
  99. package/dist/{chunk-2EZSOTSY.js → chunk-WY45BHKQ.js} +2 -2
  100. package/dist/chunk-X4FR5BZF.js +9 -0
  101. package/dist/chunk-X6RKPDY7.js +2 -0
  102. package/dist/{chunk-GK3GRUJX.js → chunk-YLFORA5G.js} +2 -2
  103. package/dist/{chunk-NBRUH7OE.js → chunk-YTVWB7YJ.js} +2 -2
  104. package/dist/{chunk-YGQN3XGZ.js → chunk-ZCEJ63SP.js} +2 -2
  105. package/dist/{chunk-2GSQR6YA.js → chunk-ZJ5CBXK3.js} +2 -2
  106. package/dist/chunk-ZL2OGDCD.js +2 -0
  107. package/dist/cli.js +8 -3
  108. package/dist/command-descriptors-ZW5J4ZEM.js +631 -0
  109. package/dist/{config-types-BWQ5xPGI.d.ts → config-types-B6MEoRNy.d.ts} +4 -0
  110. package/dist/{db-B0r1o7Vt.d.ts → db-DYLKr9Wn.d.ts} +1 -1
  111. package/dist/direct-navigation-42YHQPOI.js +3 -0
  112. package/dist/{health-CFnlCiTz.d.ts → health-DgxIDXJC.d.ts} +1 -1
  113. package/dist/index.d.ts +2 -2
  114. package/dist/index.js +1 -1
  115. package/dist/postinstall.js +1 -1
  116. package/dist/queries/affected.d.ts +2 -2
  117. package/dist/queries/affected.js +1 -1
  118. package/dist/queries/architecture.d.ts +2 -2
  119. package/dist/queries/architecture.js +1 -1
  120. package/dist/queries/bottlenecks.d.ts +2 -2
  121. package/dist/queries/bottlenecks.js +1 -1
  122. package/dist/queries/by-kind.d.ts +2 -2
  123. package/dist/queries/by-kind.js +1 -1
  124. package/dist/queries/call-graph.d.ts +2 -2
  125. package/dist/queries/call-graph.js +1 -1
  126. package/dist/queries/change-surface.d.ts +2 -2
  127. package/dist/queries/change-surface.js +1 -1
  128. package/dist/queries/cleanup-plan.d.ts +2 -2
  129. package/dist/queries/cleanup-plan.js +1 -1
  130. package/dist/queries/co-change.d.ts +2 -2
  131. package/dist/queries/co-change.js +1 -1
  132. package/dist/queries/code.d.ts +2 -2
  133. package/dist/queries/code.js +1 -1
  134. package/dist/queries/complexity-hotspots.d.ts +2 -2
  135. package/dist/queries/complexity-hotspots.js +1 -1
  136. package/dist/queries/complexity.d.ts +2 -2
  137. package/dist/queries/complexity.js +1 -1
  138. package/dist/queries/convergence.d.ts +2 -2
  139. package/dist/queries/convergence.js +1 -1
  140. package/dist/queries/coupling.d.ts +2 -2
  141. package/dist/queries/coupling.js +1 -1
  142. package/dist/queries/cycles.d.ts +2 -2
  143. package/dist/queries/cycles.js +1 -1
  144. package/dist/queries/dataflow.d.ts +2 -2
  145. package/dist/queries/dataflow.js +1 -1
  146. package/dist/queries/dead.d.ts +2 -2
  147. package/dist/queries/dead.js +1 -1
  148. package/dist/queries/decorative-checkers.d.ts +2 -2
  149. package/dist/queries/decorative-checkers.js +1 -1
  150. package/dist/queries/deep-chains.d.ts +2 -2
  151. package/dist/queries/deep-chains.js +1 -1
  152. package/dist/queries/deps.d.ts +2 -2
  153. package/dist/queries/deps.js +1 -1
  154. package/dist/queries/diff-gate.d.ts +2 -2
  155. package/dist/queries/diff-gate.js +1 -1
  156. package/dist/queries/diff-impact.d.ts +2 -2
  157. package/dist/queries/diff-impact.js +1 -1
  158. package/dist/queries/doc-drift.d.ts +2 -2
  159. package/dist/queries/doc-drift.js +1 -1
  160. package/dist/queries/drift.d.ts +2 -2
  161. package/dist/queries/drift.js +1 -1
  162. package/dist/queries/duplicate-bodies.d.ts +2 -2
  163. package/dist/queries/duplicate-bodies.js +1 -1
  164. package/dist/queries/extract-candidates.d.ts +2 -2
  165. package/dist/queries/extract-candidates.js +1 -1
  166. package/dist/queries/fan.d.ts +2 -2
  167. package/dist/queries/fan.js +1 -1
  168. package/dist/queries/files.d.ts +2 -2
  169. package/dist/queries/health.d.ts +3 -3
  170. package/dist/queries/health.js +1 -1
  171. package/dist/queries/hierarchy.d.ts +2 -2
  172. package/dist/queries/hierarchy.js +1 -1
  173. package/dist/queries/hotspots.d.ts +2 -2
  174. package/dist/queries/hotspots.js +1 -1
  175. package/dist/queries/imports.d.ts +2 -2
  176. package/dist/queries/imports.js +1 -1
  177. package/dist/queries/incomplete-migration.d.ts +2 -2
  178. package/dist/queries/incomplete-migration.js +1 -1
  179. package/dist/queries/index.d.ts +3 -3
  180. package/dist/queries/index.js +1 -1
  181. package/dist/queries/isolated.d.ts +2 -2
  182. package/dist/queries/isolated.js +1 -1
  183. package/dist/queries/locality-candidates.d.ts +2 -2
  184. package/dist/queries/locality-candidates.js +1 -1
  185. package/dist/queries/members.d.ts +2 -2
  186. package/dist/queries/members.js +1 -1
  187. package/dist/queries/methods.d.ts +2 -2
  188. package/dist/queries/methods.js +1 -1
  189. package/dist/queries/not-implemented.d.ts +2 -2
  190. package/dist/queries/not-implemented.js +1 -1
  191. package/dist/queries/outline.d.ts +2 -2
  192. package/dist/queries/outline.js +1 -1
  193. package/dist/queries/passthrough-candidates.d.ts +2 -2
  194. package/dist/queries/passthrough-candidates.js +1 -1
  195. package/dist/queries/plan-context.d.ts +2 -2
  196. package/dist/queries/plan-context.js +1 -1
  197. package/dist/queries/react-component-duplicates.d.ts +2 -2
  198. package/dist/queries/react-component-duplicates.js +1 -1
  199. package/dist/queries/react-hook-candidates.d.ts +2 -2
  200. package/dist/queries/react-hook-candidates.js +1 -1
  201. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  202. package/dist/queries/react-large-component-pressure.js +1 -1
  203. package/dist/queries/recent-duplicates.d.ts +2 -2
  204. package/dist/queries/recent-duplicates.js +1 -1
  205. package/dist/queries/redundant-reexports.d.ts +2 -2
  206. package/dist/queries/redundant-reexports.js +1 -1
  207. package/dist/queries/refs.d.ts +2 -2
  208. package/dist/queries/refs.js +1 -1
  209. package/dist/queries/self-audit.d.ts +2 -2
  210. package/dist/queries/self-audit.js +1 -1
  211. package/dist/queries/similar-chains.d.ts +2 -2
  212. package/dist/queries/similar-chains.js +1 -1
  213. package/dist/queries/similar-files.d.ts +2 -2
  214. package/dist/queries/similar-files.js +1 -1
  215. package/dist/queries/similar-signatures.d.ts +2 -2
  216. package/dist/queries/similar-signatures.js +1 -1
  217. package/dist/queries/similar.d.ts +2 -2
  218. package/dist/queries/similar.js +1 -1
  219. package/dist/queries/slice.d.ts +2 -2
  220. package/dist/queries/slice.js +1 -1
  221. package/dist/queries/stale-abstractions.d.ts +2 -2
  222. package/dist/queries/stale-abstractions.js +1 -1
  223. package/dist/queries/stats.d.ts +2 -2
  224. package/dist/queries/surface.d.ts +2 -2
  225. package/dist/queries/surface.js +1 -1
  226. package/dist/queries/symbols.d.ts +2 -2
  227. package/dist/queries/symbols.js +1 -1
  228. package/dist/queries/system.d.ts +2 -2
  229. package/dist/queries/system.js +1 -1
  230. package/dist/queries/test-quality.d.ts +2 -2
  231. package/dist/queries/test-quality.js +1 -1
  232. package/dist/queries/trace.d.ts +2 -2
  233. package/dist/queries/trace.js +1 -1
  234. package/dist/queries/twin-ab.d.ts +2 -2
  235. package/dist/queries/twin-ab.js +1 -1
  236. package/dist/queries/twin-drift.d.ts +2 -2
  237. package/dist/queries/twin-drift.js +1 -1
  238. package/dist/queries/unused-imports.d.ts +2 -2
  239. package/dist/queries/unused-imports.js +1 -1
  240. package/dist/queries/unused-params.d.ts +2 -2
  241. package/dist/queries/unused-params.js +1 -1
  242. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  243. package/dist/queries/vue-component-duplicates.js +1 -1
  244. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  245. package/dist/queries/vue-composable-candidates.js +1 -1
  246. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  247. package/dist/queries/vue-large-view-pressure.js +1 -1
  248. package/dist/queries/wrapper-candidates.d.ts +2 -2
  249. package/dist/queries/wrapper-candidates.js +1 -1
  250. package/dist/reindex-worker.js +26 -25
  251. package/dist/reindex.d.ts +7 -3
  252. package/dist/reindex.js +34 -33
  253. package/dist/runtime.d.ts +3 -10
  254. package/dist/runtime.js +3 -3
  255. package/dist/rust-semantic-session-server.js +1 -1
  256. package/dist/rust-semantic-session-worker.js +1 -1
  257. package/dist/rust-semantic-worker.js +1 -1
  258. package/dist/{scip-cli-DCvnlZCu.d.ts → scip-cli-Cc6c00-a.d.ts} +2 -2
  259. package/dist/watch-server.js +5 -5
  260. package/docs/AGENT_GUIDE.md +19 -3
  261. package/docs/CLI_JSON_OUTPUT.md +86 -1
  262. package/docs/COMMAND_REFERENCE.md +5 -3
  263. package/docs/SECURITY_MODEL.md +129 -0
  264. package/docs/TELEMETRY_RETENTION.md +5 -0
  265. package/docs/schemas/cli-output-page.schema.json +104 -0
  266. package/package.json +8 -7
  267. package/skills/_shared/SKILL.md +4 -2
  268. package/skills/scip-audit/SKILL.md +3 -2
  269. package/skills/scip-explore/SKILL.md +1 -1
  270. package/skills/scip-improve/SKILL.md +1 -1
  271. package/skills/scip-plan/SKILL.md +1 -1
  272. package/skills/scip-verify/SKILL.md +7 -2
  273. package/dist/chunk-24QNP7MN.js +0 -2
  274. package/dist/chunk-2ZOCHAL2.js +0 -8
  275. package/dist/chunk-35SQLYCQ.js +0 -2
  276. package/dist/chunk-4CGVLUDP.js +0 -18
  277. package/dist/chunk-4RI4BJGT.js +0 -8
  278. package/dist/chunk-52HQTTPB.js +0 -2
  279. package/dist/chunk-A63U2W3P.js +0 -3
  280. package/dist/chunk-ADFSIJP2.js +0 -16
  281. package/dist/chunk-AOLE4DYM.js +0 -6
  282. package/dist/chunk-B5MHCHP3.js +0 -107
  283. package/dist/chunk-DGAGY7RJ.js +0 -60
  284. package/dist/chunk-DGMCFMPG.js +0 -11
  285. package/dist/chunk-GA64UPMI.js +0 -6
  286. package/dist/chunk-HEBAY673.js +0 -2
  287. package/dist/chunk-HELS7KFF.js +0 -2
  288. package/dist/chunk-IPDCSB6N.js +0 -6
  289. package/dist/chunk-JJJCO4QC.js +0 -945
  290. package/dist/chunk-KP4KBDVF.js +0 -3
  291. package/dist/chunk-LRTP3DKL.js +0 -3
  292. package/dist/chunk-P6HBYNBE.js +0 -5
  293. package/dist/chunk-QHKUY4FW.js +0 -2
  294. package/dist/chunk-QHRL4LKM.js +0 -2
  295. package/dist/chunk-UXP636P5.js +0 -144
  296. package/dist/chunk-VEVBIAOJ.js +0 -16
  297. package/dist/chunk-VKRQDBW5.js +0 -9
  298. package/dist/chunk-VOQFGC2W.js +0 -67
  299. package/dist/chunk-WMXRRBII.js +0 -8
  300. package/dist/chunk-X3NLZHPA.js +0 -20
  301. package/dist/chunk-Z5QQPJ3U.js +0 -30
  302. package/dist/chunk-ZLJLE6LK.js +0 -2
  303. package/dist/command-descriptors-SJDZ7QGR.js +0 -617
  304. package/dist/direct-navigation-HTKOZEOM.js +0 -3
@@ -1,617 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a as Sl,d as vl,e as Ri,f as tr,g as Rl,h as xl,i as kl,k as wl}from"./chunk-KP4KBDVF.js";import{a as ut,b as x,c as He,d as Se,e as It,f as p,g as cl,h as vi,i as ll,j as I,k as $,l as k,m as ce,n as le,o as we,p as sn,q as bl}from"./chunk-AOLE4DYM.js";import{$ as Es,$a as oa,$b as Ze,$c as lt,$d as Zn,A as Me,Aa as Wn,Ab as Ea,Ac as xc,Ad as el,Ae as E,B as ys,Ba as pi,Bb as ja,Bc as kc,Bd as yi,Be as yl,C as On,Cb as Aa,Cc as wc,Ce as z,D as bs,Da as Ws,Db as La,Dc as $c,Dd as te,E as ai,Ea as at,Eb as Oa,Ec as Cc,F as Ss,Fb as Da,Fc as Pc,Fd as qe,G as vs,Gb as Fa,Gd as Tt,H as Rs,Ha as Zt,Hb as Ma,Hc as Tc,Hd as tl,I as xs,Ia as Hs,Ib as Na,Ic,J as Dn,Ja as Us,Jb as _a,Jc as Ec,Jd as pe,K as ee,Ka as Gs,Kb as Ba,L as ks,La as Js,Lb as mi,Ld as Ve,M as Fn,Ma as en,Mb as qa,Md as bi,N as ws,Na as zs,Nb as Va,Nc as _e,Nd as nl,O as $s,Oa as Ks,Ob as Wa,Oc as Be,Od as Qn,P as Mn,Pa as Hn,Pb as Ha,Pc as Ct,Pd as Xn,Qa as Qs,Qb as Ua,Qd as Si,R as Xt,Ra as Xs,Rb as Ga,Rc as Jn,Rd as We,S as Cs,Sa as Ys,Sb as Ja,Sc as gi,Sd as ae,T as Ps,Ta as wt,Tb as za,Tc as jc,Td as V,U as Ts,Ua as Zs,Ub as Ka,Uc as ct,Ud as Yn,V as Ne,Va as ea,Vb as Qa,Vc as be,Vd as A,W as Ye,Wb as Xa,Wc as Pt,Wd as rn,X as Is,Xa as ta,Xb as Ya,Xc as Ee,Xd as on,Y as Rt,Ya as na,Yb as Za,Yc as Ac,Yd as Ae,Z as Nn,Za as ra,Zb as ec,Zc as Lc,Zd as rl,_ as _n,_a as ia,_b as tc,_c as Oc,_d as il,a as ms,aa as js,ab as sa,ac as nc,ad as Dc,ae as ol,b as fs,ba as As,bb as aa,bc as rc,bd as Fc,be as sl,c as jn,ca as Bn,cb as ca,cc as ic,cd as Mc,ce as al,d as ii,da as Ls,db as la,dc as oc,dd as dt,ea as xt,eb as da,ec as sc,ed as je,f as gs,fa as Os,fc as ac,fd as ue,fe as me,g as Jt,ga as Yt,gb as ua,gc as fi,ge as Z,h as vt,ha as kt,hb as pa,hc as $t,hd as Nc,he as dl,i as oi,ia as B,ib as ma,ic as Un,id as _c,ie as ul,j as hs,ja as Ds,jb as fa,jc as Gn,jd as Bc,je as pl,k as si,ka as ci,kb as ga,kc as cc,kd as qc,ke as et,lb as ha,lc,ld as Vc,le as ml,ma as Fs,mb as ya,mc as dc,md as Wc,me as ke,n as An,na as Ms,nb as ba,nc as uc,nd as Hc,ne as fl,o as he,oa as li,ob as Sa,oc as pc,od as Uc,oe as fe,p as Ln,pa as Ns,pb as va,pc as mc,pd as Gc,pe as er,q as W,qa as di,qb as Ra,qc as fc,qd as Jc,qe as gl,r as X,ra as ui,rb as xa,rc as gc,rd as zc,re as O,sa as _s,sb as ka,sc as hc,sd as Kc,se as H,ta as Bs,tb as wa,tc as yc,td as Qc,te as w,ua as qn,ub as $a,uc as bc,ud as zn,ue as Q,va as qs,vb as tn,vc as ye,vd as Xc,ve as S,wa as Vn,wb as Ca,wc as Sc,wd as Yc,we as Et,x as zt,xb as Pa,xc as nn,xd as Kn,xe as P,y as Kt,yb as Ta,yc as vc,yd as Zc,ye as F,z as Qt,za as Vs,zb as Ia,zc as Rc,zd as hi,ze as hl}from"./chunk-JJJCO4QC.js";import{execFileSync as ud,spawn as dy}from"child_process";import{createHash as uy}from"crypto";import{existsSync as ft,mkdirSync as py,readFileSync as my,rmSync as fy,writeFileSync as gy}from"fs";import{homedir as hy}from"os";import{dirname as pd,isAbsolute as yy,join as Ot,resolve as by}from"path";import{execFileSync as Lh}from"child_process";import{existsSync as $l,readdirSync as Kg}from"fs";import{isAbsolute as Qg,join as xi,resolve as Xg}from"path";var Yg={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:Rt.language,indexerBinary:Rt.indexerBinary,checkCommand:`${Rt.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Rt.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:Rt.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",Qg(r)?r:Xg(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Cl(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Cl(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=xi(e,"vendor","bin","scip-php"),r=xi(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",$l(r)?r:$l(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function pt(e){return Yg[e]}function Cl(e,t){let n;try{n=Kg(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return xi(e,i);return null}import{createRequire as Zg}from"module";var eh=Zg(import.meta.url);function Pl(e,t=[]){let n=th(),r=Ks(e,t),i=r[0];return n?r.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r}:{available:!1,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r,reason:"ts-morph is not installed"}}function th(){try{return eh.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as jt,spawnSync as nh}from"child_process";import{existsSync as $e,mkdtempSync as jl,readFileSync as rh,readdirSync as ih,rmSync as Al,symlinkSync as oh,writeFileSync as sh}from"fs";import{tmpdir as Ll}from"os";import{join as de}from"path";var ah=3e5,ch=12;function $i(e,t,n={}){let r=Ci(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:ki(e),batches:[]};let i=ph(t,r),o=n.timeoutMs??ah,s=yh(e,t),a=ki(e),c=jl(de(Ll(),"scip-cleanup-verify-")),l=[],d=new Map;try{jt("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),bh(e,c);for(let u of r)d.set(u.label,Il(u,c,o).rawErrors);for(let u of t.batches){Dl(c,u);let m=null;for(let g of r){let f=Il(g,c,o),h=lh(f,d.get(g.label)??[],f.rawErrors);if(h.status==="failed"){let b=h.errors.length>0?h.errors:f.outputTail;m={depth:u.depth,status:"failed",reason:`${g.label}: ${h.reason}`,errors:b.slice(0,ch)};break}}if(!m)l.push({depth:u.depth,status:"verified"});else{l.push(m);break}}}finally{try{jt("git",["-C",e,"worktree","remove","--force",c],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"})}catch{Al(c,{recursive:!0,force:!0})}}return{checkers:r.map(u=>u.label),uncoveredFiles:i,baselineErrors:[...d.values()].reduce((u,m)=>u+m.length,0),dirtyOverlap:s,dirtyWorkingTree:a,batches:l}}function lh(e,t,n){let r=dh(t,n);return r.length>0?{status:"failed",reason:"checker reported new errors",errors:r}:e.ok?{status:"verified",reason:"checker passed",errors:[]}:{status:"failed",reason:`checker exited ${e.exitCode===null?"unknown":String(e.exitCode)} with unparsed output`,errors:[...e.outputTail??[]]}}function dh(e,t){let n=uh(e),r=new Map,i=[];for(let o of t){let s=Ol(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function uh(e){let t=new Map;for(let n of e){let r=Ol(n);t.set(r,(t.get(r)??0)+1)}return t}function ph(e,t){let n=new Set(t.flatMap(i=>i.coversExtensions));return[...new Set(e.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>{let o=i.slice(i.lastIndexOf("."));return!n.has(o)}).sort()}function Ol(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Tl=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],mh=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Ci(e){let t=[];if($e(de(e,"tsconfig.json"))){let n=de(e,"node_modules",".bin","tsc");t.push($e(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Tl,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Tl,strength:"reference-aware"})}if($e(de(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"],strength:"reference-aware"}),["pyproject.toml","setup.py","requirements.txt"].some(n=>$e(de(e,n)))){let n=fh();n&&t.push(n)}if(mh.some(n=>$e(de(e,n)))){let n=gh(e);n&&t.push(n)}for(let n of hh(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--message-format","json","--manifest-path",n],coversExtensions:[".rs"],strength:"reference-aware",env:{...process.env,CARGO_TARGET_DIR:de(e,n,"..","target")}});return t}function fh(){return Ne("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--output-format","json","--select","E9,F821,F822","."],coversExtensions:[".py"],strength:"reference-aware"}:Ne("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function gh(e){let t=de(e,"node_modules",".bin","clj-kondo");return $e(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Ln],strength:"reference-aware"}:Ne("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Ln],strength:"reference-aware"}:Ne("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Ln],strength:"reference-aware"}:null}function hh(e){let t=[];if($e(de(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=ih(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||$e(de(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function yh(e,t){let n=new Set(ki(e));return[...new Set(t.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function ki(e){let t;try{t=jt("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",timeout:3e4,killSignal:"SIGKILL"})}catch{return[]}return t.split(`
3
- `).map(n=>n.slice(3).trim()).filter(n=>n!=="").sort()}function bh(e,t){for(let n of["node_modules"]){let r=de(e,n),i=de(t,n);if($e(r)&&!$e(i))try{oh(r,i,"junction")}catch{}}}function Dl(e,t){let n=new Map;for(let r of t.entries){let i=n.get(r.file)??[];i.push({start:r.startLine,end:r.endLine}),n.set(r.file,i)}for(let[r,i]of n){let o=de(e,r);$e(o)&&sh(o,Sh(rh(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function Pi(e,t){for(let n of t)Dl(e,n)}function Fl(e,t){let n=jl(de(Ll(),"scip-cleanup-patch-"));try{return jt("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),Pi(n,t),jt("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024,timeout:3e4,killSignal:"SIGKILL"})}finally{try{jt("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"})}catch{Al(n,{recursive:!0,force:!0})}}}function Ti(e,t={}){if(t.all)return[...e.batches];if(t.batch!==void 0){let n=e.batches.find(r=>r.depth===t.batch);return n?[n]:[]}return[...e.batches]}function Ii(e,t,n={}){let r=[];e.checkers.length===0&&r.push("No project checker was detected, so no deletion patch is compiler-verified."),e.uncoveredFiles.length>0&&r.push(`No detected checker covers: ${e.uncoveredFiles.join(", ")}.`),!n.allowDirty&&e.dirtyOverlap.length>0&&r.push(`Plan files are dirty in the working tree: ${e.dirtyOverlap.join(", ")}.`);let i=new Set(e.batches.filter(o=>o.status==="verified").map(o=>o.depth));for(let o of t)i.has(o.depth)||r.push(`Batch ${o.depth} is not verified by the detected checker(s).`);return r}function Sh(e,t,n={}){let r=e.split(`
4
- `),i=(n.rust===!0?vh(e):ys(e)).split(`
5
- `),o=new Set;for(let s of t){let a=Rh(r,s.start),c=kh(i,a,Math.min(s.end,r.length-1));for(let l=a;l<=c&&l<r.length;l++)o.add(l)}return r.filter((s,a)=>!o.has(a)).join(`
6
- `)}function vh(e){return e.replace(/\/\/.*$/gm,t=>t.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\r\n]/g," ")).replace(/"(?:\\.|[^"\\\r\n])*"/g,t=>t.replace(/[^\r\n]/g," "))}function Rh(e,t){let n=t;for(;n>0;){let r=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(r))n-=1;else break}return n}var xh=200;function kh(e,t,n){let r=0;for(let i=t;i<e.length;i++){for(let o of e[i]??"")o==="("||o==="["||o==="{"?r+=1:(o===")"||o==="]"||o==="}")&&(r-=1);if(i>=n&&r<=0)return i;if(i-n>xh)break}return n}function Il(e,t,n){let r=nh(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,killSignal:"SIGKILL",env:e.env??process.env,maxBuffer:33554432}),i=`${r.stdout??""}
7
- ${r.stderr??""}`;if(r.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:El(i)};let o=wh(e.label,i),s=o.diagnostics.length>0?o.diagnostics:r.error?[{file:"",message:String(r.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:r.status,rawErrors:s.map(Ah),diagnostics:s,parseBasis:o.parseBasis,outputTail:El(i)}}function wh(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:$h(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:Ch(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=Ph(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:Th(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:Ih(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:Eh(t),parseBasis:"clj-kondo-json"}:{diagnostics:jh(t),parseBasis:"heuristic"}}function $h(e){let t=[],n=/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"tsc"});return t}function Ch(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),message:r[4]??"",parseBasis:"go"});return t}function Ph(e){let t=Ml(e);if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let i=r,o=i.location,s=o&&typeof o=="object"?o:{},a=typeof i.filename=="string"?i.filename:"",c=typeof i.message=="string"?i.message:"";!a&&!c||n.push({file:a,line:typeof s.row=="number"?s.row:void 0,column:typeof s.column=="number"?s.column:void 0,code:typeof i.code=="string"?i.code:void 0,message:c,parseBasis:"ruff-json"})}return n}function Th(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+([A-Z]\d{3})\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"ruff-text"});return t}function Ih(e){let t=[];for(let n of e.split(`
8
- `)){if(!n.trim().startsWith("{"))continue;let r=wi(n);if(!r||typeof r!="object")continue;let i=r;if(i.reason!=="compiler-message")continue;let o=i.message;if(!o||typeof o!="object")continue;let s=o;if(s.level!=="error")continue;let l=(Array.isArray(s.spans)?s.spans:[]).find(u=>!!u&&typeof u=="object"&&u.is_primary===!0),d=s.code;t.push({file:typeof l?.file_name=="string"?l.file_name:"",line:typeof l?.line_start=="number"?l.line_start:void 0,column:typeof l?.column_start=="number"?l.column_start:void 0,code:d&&typeof d=="object"&&typeof d.code=="string"?String(d.code):void 0,message:typeof s.message=="string"?s.message:"",parseBasis:"cargo-json"})}return t}function Eh(e){let t=Ml(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let r=[];for(let i of n){if(!i||typeof i!="object")continue;let o=i;o.level==="error"&&r.push({file:typeof o.filename=="string"?o.filename:"",line:typeof o.row=="number"?o.row:void 0,column:typeof o.col=="number"?o.col:void 0,code:typeof o.type=="string"?o.type:void 0,message:typeof o.message=="string"?o.message:"",parseBasis:"clj-kondo-json"})}return r}function jh(e){return e.split(`
9
- `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function Ah(e){let t=e.file.length>0?`${e.file}${e.line?`:${e.line}`:""}${e.column?`:${e.column}`:""}: `:"",n=e.code?`${e.code} `:"";return`${t}${n}${e.message}`.trim()}function Ml(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return wi(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?wi(t.slice(n)):null}function wi(e){try{return JSON.parse(e)}catch{return null}}function El(e,t=10){return e.split(`
10
- `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Bl={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".vue"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]},Oh={typescript:"typescript",javascript:"javascript",java:"java",scala:"scala",kotlin:"kotlin",rust:"rust",python:"python",ruby:"ruby",cpp:"cpp",c:"c",csharp:"csharp",vb:"vb",php:"php",clojure:"clojure"},Dh={typescript:"javascript",javascript:"javascript",java:"jvm",scala:"jvm",kotlin:"jvm",rust:"rust",python:"python",ruby:"ruby",cpp:"c/cpp",c:"c/cpp",csharp:"dotnet",vb:"dotnet",dart:"dart",php:"php",clojure:"clojure"};function ve(e,t){let n=t.languages??lt(e),r=n.map(a=>{let c=Bn(pt(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=Wh(e,n,t),o=Ei({semantics:i},"typescript"),s=Ci(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:Gh(e)}}function tt(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,r=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",i=r!=="unavailable",o=e.languages.map(c=>Bh(e,c,{hasIndexedGraph:qh(c,t),runtimeProbe:t.runtimeProbe})),s=o.map(c=>c.cleanupVerification.status),a=s.length===0||s.every(c=>c==="unavailable")?"unavailable":s.every(c=>c==="available")?"available":"partial";return{languages:e.languages,matrix:o,capabilities:[{id:"indexing",label:"SCIP indexing",status:r,evidence:"graph-fact",reason:r==="available"?"All detected/configured language indexers are runnable.":t.hasIndexedGraph?`An indexed graph is present; ${n}/${e.indexers.length} detected/configured language indexers are runnable for refresh.`:`${n}/${e.indexers.length} detected/configured language indexers are runnable.`},...Fh(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:i?"available":"unavailable",evidence:"heuristic",reason:i?"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index.":"Heuristic detectors need an indexed code graph."},{id:"cleanup-verification",label:"Project cleanup verification",status:a,evidence:"checker",reason:a!=="unavailable"?o.map(c=>`${c.language}: ${c.cleanupVerification.status} (${c.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&i?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-file gates.":"Git is unavailable or the project root is not a git worktree."}]}}function Fh(e){return Mh(e).map(t=>{let n=Ei(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${Nh(t)} semantic provider`,status:r,evidence:"semantic",reason:_h(t,n)}})}function Mh(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of Vl(e))t.add(n.language);return[...t].sort((n,r)=>Nl(n)-Nl(r))}function Nl(e){return e==="typescript"?0:1}function Nh(e){return e==="typescript"?"TypeScript":"Rust"}function _h(e,t){return t?.available?e==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":t?t.reason??(e==="typescript"?"TypeScript semantic checks will fall back to SCIP/source evidence.":"Rust semantic checks will fall back to SCIP/source evidence."):e==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}function Bh(e,t,n){let r=e.indexers.find(d=>d.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=Vh(t,n.runtimeProbe),a=Hh(e,t),c=Uh(e,t),l=c.length===0?"unavailable":c.every(d=>d.strength!=="syntax-only")?"available":"partial";return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="available"?`${r?.binaryLabel??t} is runnable${r?.resolvedBinary?` at ${r.resolvedBinary}`:""}.`:i==="partial"?`An indexed ${t} graph is present, but ${r?.binaryLabel??t} is not currently runnable for refresh.`:r?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:o?s.status:"unavailable",evidence:"heuristic",reason:o?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above.":"Cleanup detectors need an indexed graph for this language."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:l,evidence:"checker",reason:c.length>0?c.map(d=>d.label).join(", "):`No detected checker covers ${Bl[t].join(", ")} files.`}}}function qh(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function Vh(e,t){if(e==="go")return{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."};if(e==="clojure")return(t?.(e)??_l(e))==="unavailable"?{status:"unavailable",reason:"Clojure built-in reader is not available in this environment; no source-fallback evidence can be produced."}:{status:"available",reason:"Clojure source fallback uses the built-in reader for namespace imports plus callable, callsite, and protocol/record member evidence for .clj, .cljs, and .cljc files."};let n=ql(e);if(n==="regex-only")return{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`};if(!n)return{status:"unavailable",reason:`No source-fallback adapter is registered for ${e}.`};let r=t?.(e)??_l(e);return r==="unavailable"?{status:"partial",reason:"tree-sitter native module not loadable \u2014 regex/import-only evidence remains available where registered."}:r==="regex"?{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`}:r==="reader"?{status:"available",reason:`${e} source fallback is reader-backed.`}:{status:"available",reason:n==="ast-dispatch-with-regex-fallback"?`AST-dispatched source fallback covers ${e} imports.`:`AST/source fallback covers ${e} imports and source-backed evidence.`}}function _l(e){let t=Oh[e];return t?On(t):ql(e)==="regex-only"?"regex":"unavailable"}function ql(e){let t=Dh[e],n=t?xs(t):null;return n?.imports??n?.exports??n?.reExports??null}function Wh(e,t,n){let r=[];return t.includes("typescript")&&r.push({language:"typescript",...Pl(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&r.push({language:"rust",...Ls(e)}),r}function Vl(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Ei(e,t){return Vl(e).find(n=>n.language===t)}function Hh(e,t){if(t!=="typescript"&&t!=="rust")return{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:`No semantic provider is registered for ${t}; commands use graph and source evidence instead.`};let n=Ei(e,t);return n?{id:"semantic",label:"Semantic provider",status:n.available?"available":n.dependencyAvailable?"partial":"unavailable",evidence:"semantic",reason:n.available?t==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":n.reason??`${t} semantic checks fall back to SCIP/source evidence.`}:{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:t==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}}function Uh(e,t){let n=new Set(Bl[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function Gh(e){try{return Lh("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{existsSync as ji,readFileSync as Ai}from"fs";import{join as an}from"path";var Ue="<!-- scip-query:agent-setup:begin -->",At="<!-- scip-query:agent-setup:end -->",nr="# scip-query:agent-setup";function Lt(){if(process.stdin.isTTY)return"";try{return Ai(0,"utf-8")}catch{return""}}function rr(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function cn(e){let t=Gn(e.findings),n=e.findings.length-t.length,r=e.rootCauseGroups?.length??e.findings.length,i=[`scip-query diff-gate found ${t.length} issue(s) in ${r} root-cause group(s) in this diff`+(n>0?` (+${n} advisory, non-blocking)`:"")+" \u2014 fix or knowingly accept them before finishing:"],o=e.rootCauseGroups?.filter(s=>s.count>1)??[];for(let s of o)i.push(`- group [${s.check}] ${s.count} finding(s): ${s.message}`),i.push(` -> ${s.remediation}`);for(let s of e.findings)i.push(`- [${s.check}]${s.advisory?" (advisory)":""} ${s.message}`),i.push(` -> ${s.remediation}`);return i.join(`
11
- `)}function ir(e,t={}){let n={written:[],unchanged:[],skipped:[]};return Jh(e,n),t.gitHook&&Kh(e,n),n}function Gl(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Hl(e,"AGENTS.md",t,n),Hl(e,"CLAUDE.md",t,n),Qh(e,t,n),n}function Jh(e,t){let n=[Ue,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Use native search and file reads for literal text and source. Use scip-query when a claim depends on compiler-resolved identity, references, callers, dependencies, consumers, public surface, transitive impact, architecture, historical co-change, or a scip detector/gate.","- Unsure how to explore, plan, verify, or clean up here: invoke the `scip-query` skill \u2014 it routes to the right specialist skill.","- Each specialist skill carries its own command shortlist \u2014 prefer it over the full `_shared` catalog.","- For a non-trivial change: establish the current entry-to-effect flow, the affected consumers, and the reuse options before editing (`scip-plan` skill, anchored by `scip-query plan-context <target>`).","- Before claiming a complete relationship set, inspect the command coverage. If it is bounded or unknown, use `--full`, a narrower scope, or command pagination before making the claim.","- After the change, run the postchecks matching what you actually edited \u2014 the table is in the `scip-verify` skill \u2014 then `scip-query diff-gate`. Fix findings or state why each is accepted.","- For `refs`, `trace`, `system`, `plan-context`, and `diff-gate`, do not pipe output through `head`, `tail`, or line-range `sed`; use `--json --compact`, and use `refs --limit` plus its continuation cursor when pagination is needed.","- Repository records: commit `.scipquery/suppressions/*.json` and `.scipquery/events/*.json` with the code or docs change that produced them; do not ignore or drop these shared records.","- Checkout preferences: `.codex/hooks.json` and `.claude/settings.local.json` are local agent-tool settings and must not be committed.",At].join(`
12
- `);Wl(e,"AGENTS.md",n,t);let r=[Ue,"@AGENTS.md",At].join(`
13
- `);Wl(e,"CLAUDE.md",r,t,i=>i.includes("@AGENTS.md")&&!i.includes(Ue))}function Wl(e,t,n,r,i){let o=an(e,t),s=!1,a=or(o,t,r,c=>{if(i?.(c.text))return s=!0,{kind:"unchanged"};let l=zh(c.text,n);return l===c.text?{kind:"unchanged"}:{kind:"write",text:l,...c.revision.exists?{}:{mode:420}}});a&&(!a.changed||s?r.unchanged.push(t):r.written.push(t))}function Hl(e,t,n,r){let i=an(e,t);if(n.dryRun){if(!ji(i)){r.unchanged.push(t);return}try{let s=Ai(i,"utf-8");s.includes(Ue)?(Ul(s),r.removed.push(t)):r.unchanged.push(t)}catch(s){r.skipped.push({target:t,reason:s instanceof Error?s.message:String(s)})}return}let o=or(i,t,r,s=>{if(!s.revision.exists||!s.text.includes(Ue))return{kind:"unchanged"};let a=Ul(s.text);return a.length===0?{kind:"delete"}:{kind:"write",text:a}});o&&(o.changed?r.removed.push(t):r.unchanged.push(t))}function zh(e,t){if(Jl(e)==="present"){let r=new RegExp(`${Ue}[\\s\\S]*?${At}`);return e.replace(r,t)}return e.length>0?`${e.replace(/\n*$/,`
14
-
15
- `)}${t}
16
- `:`${t}
17
- `}function Ul(e){Jl(e);let t=new RegExp(`${Ue}[\\s\\S]*?${At}`),n=e.replace(t,"").replace(/\n{3,}/g,`
18
-
19
- `).trim();return n.length===0?"":`${n}
20
- `}function Jl(e){let t=e.split(Ue).length-1,n=e.split(At).length-1;if(t===0&&n===0)return"absent";if(t===1&&n===1&&e.indexOf(Ue)<e.indexOf(At))return"present";throw new Error("managed scip-query markers are incomplete, duplicated, or out of order")}function or(e,t,n,r){try{return ct(e,r,{maxRetries:0})}catch(i){n.skipped.push({target:t,reason:i instanceof Error?i.message:String(i)});return}}function Kh(e,t){let n=an(e,".git","hooks");if(!ji(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=an(n,"pre-commit"),i=["#!/bin/sh",nr,"scip-query diff-gate || {",' echo "scip-query diff-gate failed \u2014 fix findings or commit with --no-verify to knowingly accept." >&2'," exit 1","}",""].join(`
21
- `),o=!1,s=or(r,".git/hooks/pre-commit",t,a=>a.revision.exists&&!a.text.includes(nr)?(o=!0,{kind:"unchanged"}):a.text===i?{kind:"unchanged"}:{kind:"write",text:i,mode:493});s&&(o?t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"}):s.changed?t.written.push(".git/hooks/pre-commit"):t.unchanged.push(".git/hooks/pre-commit"))}function Qh(e,t,n){let r=an(e,".git","hooks","pre-commit");if(t.dryRun){ji(r)?Ai(r,"utf-8").includes(nr)?n.removed.push(".git/hooks/pre-commit"):n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"}):n.unchanged.push(".git/hooks/pre-commit");return}let i=!1,o=or(r,".git/hooks/pre-commit",n,s=>s.revision.exists?s.text.includes(nr)?{kind:"delete"}:(i=!0,{kind:"unchanged"}):{kind:"unchanged"});o&&(i?n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"}):o.changed?n.removed.push(".git/hooks/pre-commit"):n.unchanged.push(".git/hooks/pre-commit"))}import{randomUUID as oy}from"crypto";import{createHash as Yh}from"crypto";import{existsSync as lr,mkdirSync as Zh,readFileSync as dr,readdirSync as ey,rmSync as Xl,writeFileSync as Yl}from"fs";import{join as Ge}from"path";var Li="scip-query-outcome-event",sr=1;function ar(e){return JSON.stringify([e.check,e.findingId,e.event,e.commit])}function Kl(e,t){if(t.trim()==="")throw new Error("outcome event writer requires a non-empty tool version");return{...e,kind:Li,schemaVersion:sr,eventIdentity:ar(e),writer:{tool:"scip-query",version:t}}}function Ql(e){if(!ii(e))return{state:"malformed",error:"not an outcome event object"};let t=e,n=t.schemaVersion;if(n===void 0){if(t.kind!==void 0||t.eventIdentity!==void 0||t.writer!==void 0)return{state:"malformed",error:"outcome event envelope metadata requires schemaVersion"};let o=zl(t);return o?{state:"legacy",event:o,record:o,schemaVersion:0}:{state:"malformed",error:"invalid legacy outcome event fields"}}if(!Number.isSafeInteger(n)||n<1)return Number.isSafeInteger(n)?{state:"unsupported-older",error:`unsupported schemaVersion ${String(n)}`}:{state:"malformed",error:"schemaVersion must be a positive safe integer"};if(n!==sr)return{state:n>sr?"unsupported-future":"unsupported-older",error:`unsupported schemaVersion ${String(n)}`};if(t.kind!==Li)return{state:"malformed",error:`kind must be ${Li}`};let r=zl(t);if(!r)return{state:"malformed",error:"invalid current outcome event fields"};if(t.eventIdentity!==ar(r))return{state:"malformed",error:"eventIdentity does not match the outcome event"};let i=t.writer;return!ii(i)||i.tool!=="scip-query"||typeof i.version!="string"||i.version.trim()===""?{state:"malformed",error:"missing valid writer metadata"}:{state:"current",event:r,record:t,schemaVersion:sr}}var Xh=["caught","resolved","suppressed","reopened"];function zl(e){if(!(typeof e.ts!="number"||!Number.isFinite(e.ts)||typeof e.check!="string"||e.check.trim()===""||typeof e.findingId!="string"||e.findingId.trim()===""||!Xh.includes(e.event)||e.commit!==null&&typeof e.commit!="string"||e.comparisonBaseCommit!==void 0&&typeof e.comparisonBaseCommit!="string"||e.verifiedAgainstCommit!==void 0&&(e.event!=="resolved"||typeof e.verifiedAgainstCommit!="string")||e.symbol!==void 0&&typeof e.symbol!="string"))return{ts:e.ts,check:e.check,findingId:e.findingId,event:e.event,commit:e.commit,...typeof e.comparisonBaseCommit=="string"?{comparisonBaseCommit:e.comparisonBaseCommit}:{},...typeof e.verifiedAgainstCommit=="string"?{verifiedAgainstCommit:e.verifiedAgainstCommit}:{},...typeof e.symbol=="string"?{symbol:e.symbol}:{}}}var ln=Ge(".scipquery","events"),Zl=Ge(".scipquery","ledger"),Oi="events.jsonl";function ed(e){return Ge(e,Zl)}function Di(e){return Ge(ed(e),Oi)}function td(e,t,n){let r=Di(e),i=lr(r),o=i?nd(r):iy(),s=[...o.events,...t];if(s.length>0){let a=Ge(e,ln);Zh(a,{recursive:!0});for(let c of s)ty(a,c,n.toolVersion)}if(i&&o.compatibility.complete)ny(e);else if(i)return{warning:`legacy outcome ledger preserved because ${o.compatibility.omitted} of ${o.compatibility.total} non-empty record(s) are incompatible: ${o.warnings.join("; ")}`};return{}}function ty(e,t,n){let r=`${JSON.stringify(Kl(t,n),null,2)}
22
- `,i=Yh("sha256").update(r).digest("hex").slice(0,16).toUpperCase(),o=Ge(e,`${t.ts}-${i}.json`);try{Yl(o,r,{flag:"wx"})}catch(s){if(s.code!=="EEXIST")throw s;if(dr(o,"utf-8")!==r)throw new Error(`outcome event filename collision: ${o}`,{cause:s})}}function ny(e){Xl(Di(e));let t=Ge(ed(e),".gitattributes");if(!lr(t))return;let n=dr(t,"utf-8").split(`
23
- `).filter(r=>r.trim()!==`${Oi} merge=union`).join(`
24
- `).replace(/^\n+|\n+$/g,"");n===""?Xl(t):Yl(t,`${n}
25
- `)}function ur(e){let t=[],n=[],r=Ge(e,ln);if(lr(r))for(let o of ey(r).sort()){if(!o.endsWith(".json"))continue;let s=`${ln}/${o}`,a=rd(dr(Ge(r,o),"utf-8"));n.push({path:s,state:a.state,..."error"in a?{reason:a.error}:{}}),"event"in a&&t.push(a.event)}let i=Di(e);if(lr(i)){let o=nd(i);t.push(...o.events),n.push(...o.observations)}return Fi(t,n)}function nd(e){let t=[],n=[],r=`${Zl}/${Oi}`;for(let[i,o]of dr(e,"utf-8").split(`
26
- `).entries()){if(o.trim()==="")continue;let s=rd(o);n.push({path:`${r}:${i+1}`,state:s.state,..."error"in s?{reason:s.error}:{}}),"event"in s&&t.push(s.event)}return{...Fi(t,n),observations:n}}function rd(e){if(e.trim()==="")return{state:"malformed",error:"empty record"};let t;try{t=JSON.parse(e)}catch{return{state:"malformed",error:"malformed JSON"}}return Ql(t)}function ry(e){let t=new Map;for(let n of e){let r=ar(n),i=t.get(r);(!i||cr(n)>cr(i)||cr(n)===cr(i)&&n.ts<i.ts)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.ts-r.ts)}function cr(e){return+(e.comparisonBaseCommit!==void 0)+ +(e.verifiedAgainstCommit!==void 0)*2}function Fi(e,t){let n=tc(t);return{events:ry(e),compatibility:n,warnings:n.issues.map(r=>`${r.path}: ${r.reason} \u2014 ignored`)}}function iy(){return{...Fi([],[]),observations:[]}}function pr(e,t,n={}){let r=(n.now??Date.now)(),i=n.observationId??oy(),o=cy(t),s=xc(e),a=e.config.projectRoot,c=n.headCommit?n.headCommit(a):at(a)?.headCommit??null,l=n.resolveCommit?n.resolveCommit(a,t.base):ay(a,t.base),d=sy({previous:s,observed:o,result:t,projectRoot:a,commit:c,comparisonBaseCommit:l,runtime:n}),u=kc(e,d.ledgerObserved,d.checksRun,r,d.retainedKeys,i),m=u.current,g=u.status==="busy"?"finding outcome ledger not updated: evidence database remained busy":u.status==="unavailable"?"finding outcome ledger not updated: evidence database unavailable":u.status==="conflict"?`finding outcome ledger not updated: observation id ${i} names different evidence`:void 0;try{let f=new Map;for(let y of t.findings)y.symbol&&f.set(y.id,y.symbol);for(let y of t.suppressed)y.finding.symbol&&f.set(y.finding.id,y.finding.symbol);for(let[y,v]of d.replaySymbols)f.set(y,v);let h=Sc(u.previous,m,f,c,r,{...l?{comparisonBaseCommit:l}:{},verifiedAgainstByFinding:d.verifiedAgainstByFinding}),b;return n.appendEvents?n.appendEvents(a,h):b=td(a,h,{toolVersion:ue}).warning,{ledger:m,observed:o,now:r,...id(d.warning,g,b)}}catch(f){return{ledger:m,observed:o,now:r,...id(d.warning,g,`outcome event ledger not updated: ${f instanceof Error?f.message:String(f)}`)}}}function id(...e){let t=e.filter(n=>!!n).join("; ");return t?{warning:t}:{}}function sy(e){let t=[...e.observed],n=new Set(e.result.checksRun),r=new Set,i=new Map,o=new Map,s=new Set(e.observed.map(b=>ye(b.check,b.findingId))),a=new Set(e.result.checksRun),c=e.result.changedFiles.length===0&&!Un(e.result)&&e.commit!==null&&e.comparisonBaseCommit!==null,l=e.previous.filter(b=>b.outcome!=="resolved"&&(a.has(b.check)||c)&&!s.has(ye(b.check,b.findingId)));if(mt(`primary base=${String(e.comparisonBaseCommit)} head=${String(e.commit)} checks=${e.result.checksRun.join(",")} missing=${l.length}`),l.length===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let d;try{d=(e.runtime.readEvents??ur)(e.projectRoot)}catch(b){for(let y of l)r.add(ye(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${b instanceof Error?b.message:String(b)}`}}if(!d.compatibility.complete){for(let b of l)r.add(ye(b.check,b.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${Ze("committed outcome history",d.compatibility)}`}}let u=d.events,m=new Map;for(let b of u){let y=ye(b.check,b.findingId),v=m.get(y)??[];v.push(b),m.set(y,v)}let g=new Map;for(let b of l){let y=ye(b.check,b.findingId),v=nn(m.get(y)??[]),R=v?.comparisonBaseCommit??v?.commit;if(mt(`candidate ${y} anchor=${String(R)} current=${String(e.comparisonBaseCommit)}`),!v?.comparisonBaseCommit&&v?.commit&&v.commit===e.commit){n.add(b.check);continue}if(!R||!e.commit||!e.comparisonBaseCommit){r.add(y);continue}if(R===e.comparisonBaseCommit){n.add(b.check);continue}let T=g.get(R)??[];T.push(b),g.set(R,T)}if(g.size===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let f=e.runtime.worktreeIsClean?.(e.projectRoot)??at(e.projectRoot)?.clean??!1;if(mt(`replay groups=${g.size} clean=${f} callback=${!!e.runtime.replayGate}`),!f||!e.runtime.replayGate){for(let b of g.values())for(let y of b)r.add(ye(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o}}let h=[];for(let[b,y]of g){let v;try{v=e.runtime.replayGate(b),mt(`replay base=${b} checks=${v.checksRun.join(",")} findings=${v.findings.length} suppressed=${v.suppressed.length}`)}catch(D){for(let C of y)r.add(ye(C.check,C.findingId));h.push(`cross-HEAD outcome verification deferred for ${b.slice(0,12)}: ${D instanceof Error?D.message:String(D)}`);continue}let R=new Set(v.checksRun),T=ly(v);for(let D of y){let C=ye(D.check,D.findingId);if(!R.has(D.check)){r.add(C);continue}n.add(D.check);let U=T.find(K=>K.key===C);if(U){mt(`replay retained exact ${C}`),t.push(U.observed),U.symbol&&o.set(U.observed.findingId,U.symbol);continue}let j=nn(m.get(C)??[]),M=j?.symbol?T.find(K=>K.check===D.check&&K.symbol===j.symbol):void 0;if(M){mt(`replay moved ${C} -> ${M.key}`),t.push(M.observed),M.symbol&&o.set(M.observed.findingId,M.symbol);continue}i.set(C,b),mt(`replay verified ${C} against ${b}`)}}return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,...h.length>0?{warning:h.join("; ")}:{}}}function ay(e,t){let n=Zt(e,["rev-parse","--verify",`${t}^{commit}`]);return n&&/^[0-9a-f]{40}$/.test(n)?n:null}function mt(e){process.env.SCIP_QUERY_DEBUG&&console.error(`outcome-verification: ${e}`)}function cy(e){return[...e.findings.map(t=>({check:t.check,findingId:t.id,suppressed:!1})),...e.suppressed.map(t=>({check:t.finding.check,findingId:t.finding.id,suppressed:!0}))]}function ly(e){return[...e.findings.map(t=>({key:ye(t.check,t.id),check:t.check,observed:{check:t.check,findingId:t.id,suppressed:!1},...t.symbol?{symbol:t.symbol}:{}})),...e.suppressed.map(t=>({key:ye(t.finding.check,t.finding.id),check:t.finding.check,observed:{check:t.finding.check,findingId:t.finding.id,suppressed:!0},...t.finding.symbol?{symbol:t.finding.symbol}:{}}))]}var md="SCIP_QUERY_SKIP_HOOK_INSTALL",Mi="SCIP_QUERY_STOP_HOOK_MODE",Sy="scip-query hook-",vy="scip-query diff-gate --hook",od="# scip-query:local-hooks:begin",sd="# scip-query:local-hooks:end",dn=[{relativePath:".codex/hooks.json",label:".codex/hooks.json"},{relativePath:".claude/settings.local.json",label:".claude/settings.local.json"}];function Dt(e,t={}){let n=fd(),r=t.env??process.env;if(wy(r))return n.skipped.push({target:"project agent hooks",reason:`${md}=1`}),n;let i=Ly(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),xy(e,n,t.dryRun),t.remove?(cd(e,dn[0],n,{dryRun:t.dryRun}),cd(e,dn[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(ad(e,dn[0],n,{provider:"codex",commandPrefix:i,force:t.force}),ad(e,dn[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&Ry({homeDir:t.homeDir,result:n}),n)}function Ry(e={}){let t=e.result??fd(),n=e.homeDir??hy();return Ni({configPath:Ot(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),Ni({configPath:Ot(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function fd(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function ad(e,t,n,r){if(_i(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook setup will not modify it"});return}let i=Ot(e,t.relativePath);Cy({provider:r.provider,rootDir:pd(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function cd(e,t,n,r){if(_i(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}Py({configPath:Ot(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function xy(e,t,n=!1){let r=ky(e);if(!r){t.warnings.push("Could not locate .git/info/exclude; local hook files may appear as untracked.");return}let i=dn.filter(a=>!_i(e,a.relativePath));if(i.length===0)return;let o=[od,...i.map(a=>`/${a.relativePath}`),sd].join(`
27
- `),s=new RegExp(`${Me(od)}[\\s\\S]*?${Me(sd)}\\n?`,"g");if(!n)try{ct(r,a=>{let c=a.text.replace(s,"").replace(/\n*$/,""),l=`${c}${c?`
28
-
29
- `:""}${o}
30
- `;return l===a.text?{kind:"unchanged"}:{kind:"write",text:l,...a.revision.exists?{}:{mode:420}}})}catch(a){t.warnings.push(a instanceof Error?a.message:String(a));return}t.gitExcluded.push(...i.map(a=>a.label))}function ky(e){try{let t=ud("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).trim();return t?yy(t)?t:by(e,t):null}catch{return null}}function _i(e,t){try{return ud("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),!0}catch{return!1}}function wy(e=process.env){let t=e[md];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function $y(e=process.env){let t=e[Mi]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function Cy(e){if(!e.createRoot&&!ft(e.rootDir))return;let t=!1,n=gd(e.configPath,e.label,e.result,r=>{if(r.scipQueryHooks==="declined"&&!e.force)return t=!0,{kind:"unchanged"};let i=Ey(r,e.provider,e.commandPrefix);return JSON.stringify(i)===JSON.stringify(r)?{kind:"unchanged"}:{kind:"write",text:hd(i)}});if(n){if(t){e.result.skipped.push({target:e.label,reason:"scip-query hooks were previously removed; rerun with --force"});return}if(!n.changed){e.result.unchanged.push(e.label);return}e.result[n.previous.revision.exists?"updated":"installed"].push(e.label)}}function Ni(e){if(!ft(e.configPath)&&!e.writeDeclinedTombstone)return;let t=r=>{let i=Ty(r,e.writeDeclinedTombstone);return JSON.stringify(i)===JSON.stringify(r)?{kind:"unchanged"}:Object.keys(i).length===0?{kind:"delete"}:{kind:"write",text:hd(i)}};if(e.dryRun){let r=yd(e.configPath,e.label,e.result);if(!r)return;t(r).kind!=="unchanged"&&e.result.removed.push(e.label);return}gd(e.configPath,e.label,e.result,t)?.changed&&e.result.removed.push(e.label)}function Py(e){let t=e.result.removed.length;Ni(e),e.writeDeclinedTombstone&&e.result.removed.length===t&&yd(e.configPath,e.label,e.result)?.scipQueryHooks==="declined"&&e.result.removed.push(`${e.label} (declined)`)}function Ty(e,t=!1){let n=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},r={...n};for(let o of["SessionStart","UserPromptSubmit","PostCompact","PreToolUse","Stop"]){if(!Array.isArray(n[o]))continue;let s=n[o],a=bd(s);a.length>0?r[o]=a:delete r[o]}let i={...e};return Object.keys(r).length>0?i.hooks=r:delete i.hooks,t&&(i.scipQueryHooks="declined"),i}function gd(e,t,n,r){try{return ct(e,i=>{let o=Iy(i);return r(o,i)})}catch(i){n.skipped.push({target:t,reason:i instanceof Error?i.message:String(i)});return}}function Iy(e){if(!e.revision.exists)return{};try{let t=JSON.parse(e.text);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("top-level value is not an object");return t}catch(t){throw new Error(`Cannot update ${e.path}: the latest hook config is invalid JSON (${t instanceof Error?t.message:String(t)}).`,{cause:t})}}function hd(e){return`${JSON.stringify(e,null,2)}
31
- `}function yd(e,t,n){if(!ft(e))return{};try{let r=JSON.parse(my(e,"utf-8"));if(!r||typeof r!="object"||Array.isArray(r)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return r}catch(r){n.skipped.push({target:t,reason:`could not parse existing hook config: ${r instanceof Error?r.message:String(r)}`});return}}function Ey(e,t,n="scip-query"){let r=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},i={...e,hooks:{...r}};i.scipQueryHooks==="declined"&&delete i.scipQueryHooks;let o=t==="claude"?["SessionStart","UserPromptSubmit","PostCompact","PreToolUse","Stop"]:["SessionStart","UserPromptSubmit","Stop"];for(let s of o){let a=Array.isArray(r[s])?r[s]:[];i.hooks[s]=[...bd(a),Ay(t,s,n)]}return i}function bd(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!jy(n)):[]})).filter(t=>t.hooks.length>0)}function jy(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(Sy)||t===vy)}function Ay(e,t,n){return t==="SessionStart"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Refreshing scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Checking scip-query freshness"}]}:t==="PostCompact"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:10,statusMessage:"Resetting scip-query context reminder"}]}:t==="PreToolUse"?{matcher:"Bash|Grep|Glob",hooks:[{type:"command",command:`${n} hook-pretool`,timeout:10,statusMessage:"Checking scip-query evidence integrity"}]}:{hooks:[{type:"command",command:`${n} hook-stop`,timeout:30,statusMessage:"Running scip-query diff gate"}]}}function Ly(e){let t=Ot(e,"node_modules",".bin","scip-query");return ft(t)?t:"scip-query"}async function Sd(){let e=await qy(Lt());e&&console.log(JSON.stringify(e))}function vd(){let e=qi(Lt()),t=Vi(e);if(!t||!ft(t.paths.dbPath))return;let n=Rd(t.paths.cacheDir,e),r=Dy(e,n?ft(n):!0);if(r.kind==="allow")return;r.kind==="reconsider"&&n&&(py(pd(n),{recursive:!0}),gy(n,`shown
32
- `));let i={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:r.reason}};console.log(JSON.stringify(i))}var Oy=["refs","trace","system","plan-context","diff-gate"];function Dy(e,t){let n=typeof e.tool_name=="string"?e.tool_name:"",r=e.tool_input&&typeof e.tool_input=="object"?e.tool_input:{},i=n==="Bash"&&typeof r.command=="string"?r.command:"";return i&&Fy(i)?{kind:"deny",reason:"Do not pipe scip-query output through head, tail, or a line-range sed selector: that hides whether evidence was omitted. Re-run with --json --compact; for refs, use --limit and the returned coverage.continuation.cursor."}:!(n==="Grep"||n==="Glob"||n==="Bash"&&/(?:^|[;&|]\s*)(?:rg|grep)(?:\s|$)/.test(i))||t?{kind:"allow"}:{kind:"reconsider",reason:"Pause once before native search in this indexed repository. If you need compiler-resolved identity or a complete set of definitions, references, callers, consumers, dependencies, or affected units, use scip-query. If you only need literal text, filenames, or local source, retry the same search unchanged; it will be allowed for the rest of this context window."}}function Fy(e){let t=Oy.join("|");return new RegExp(`(?:^|[;&(]\\s*|\\s)(?:\\S*/)?scip-query\\s+(?:${t})(?:\\s|$)`).test(e)?/\|\s*(?:head|tail)(?:\s|$)/.test(e)||/\|\s*sed\s+(?:-[A-Za-z]+\s+)*(?:['"])?\d+\s*,\s*\d+\s*p/.test(e):!1}function Rd(e,t){let n=typeof t.session_id=="string"?t.session_id:null;if(!n)return null;let r=uy("sha256").update(n).digest("hex").slice(0,24);return Ot(e,"agent-hooks",`native-search-${r}`)}function My(e,t){let n=Rd(e.paths.cacheDir,t);n&&fy(n,{force:!0})}function Ny(e){if(rr(e))return;let t=qi(e),n=Vi(t);if(!(!n||!ft(n.paths.dbPath)))return Qy(n,r=>{let i={minTogether:6,skip:[]},o=$t(r,i),s=pr(r,o,{replayGate:a=>$t(r,{...i,base:a})});return s.warning&&console.error(`note: ${s.warning}`),o})}function xd(){let e=Ny(Lt());!e||e.findings.length===0&&!Bi(e)||console.log(JSON.stringify(_y(e,$y())))}function _y(e,t="feedback"){let n=Bi(e),r=e.findings.length>0?cn(e):void 0,i=[n,r].filter(s=>!!s).join(`
33
-
34
- `),o=By(e);return t==="block"&&e.findings.length>0?{decision:"block",reason:i}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${o}
35
-
36
- This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${o}
37
-
38
- Stop hook allowed this turn to finish. Review these findings when relevant. Set ${Mi}=feedback to ask the agent to continue without a hook error, or ${Mi}=block to enforce the gate.`}}function By(e){let t=e.findings.length>0?cn(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:"):void 0;return[Bi(e),t].filter(n=>!!n).join(`
39
-
40
- `)}function Bi(e){return e.recordCompatibility?Ze("Committed suppression",e.recordCompatibility.suppressions):void 0}async function qy(e){let t=qi(e),n=Ky(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit"&&n!=="PostCompact")return;let r=Vi(t);if(!r||((n==="SessionStart"||n==="PostCompact")&&My(r,t),n==="PostCompact"))return;let i=await Wy(r,n),o=n==="SessionStart"?Uy(r.projectRoot,r.config,r.paths):Gy(String(t.prompt??""),r.config),s=[i,o].filter(a=>!!a?.trim()).join(`
41
- `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}var Vy={prepare:tl,ensureService:vl,freshness:je,requestRefresh:xl,startOneShot(e){dy("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function Wy(e,t,n=Vy){let r=Ee(e.config);if(r.autoRefresh===!1)return;n.prepare?.(e.projectRoot,e.config,e.paths);let i=n.freshness(e.projectRoot,e.config,e.paths);if(r.enabled){let o=n.ensureService({commandName:`agent-${t}`,projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:ue,config:e.config});return o.kind==="failed"?`scip-query watch service did not start: ${o.message}. Run 'scip-query watch --daemon' to repair it.`:o.kind==="skipped"?i.state==="fresh"?void 0:`scip-query index is ${i.state}; automatic watch service wake was skipped (${o.reason}).`:(Hy(o,i.state,e.paths.cacheDir,n),i.state!=="fresh"?`scip-query index is ${i.state}; ${o.kind==="started"?"started":"woke"} the watch service and requested refresh.`:o.kind==="started"?"scip-query watch service started for this project.":void 0)}if(i.state!=="fresh"){if(t==="UserPromptSubmit")return`scip-query index is ${i.state}; evidence commands will note staleness. Run 'scip-query reindex' to refresh.`;try{return n.startOneShot(e.projectRoot),`scip-query index is ${i.state}; started background refresh with auto-install disabled.`}catch(o){let s=o instanceof Error?o.message:String(o);return`scip-query auto-refresh skipped: index is ${i.state}, but background refresh failed to start: ${s}`}}}function Hy(e,t,n,r){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||r.requestRefresh(Wn(n).activityPath,`agent hook observed ${t} index while service was idle`)}function Uy(e,t,n){let r=je(e,t,n),i=ve(e,t),s=tt(i).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=i.languages.length>0?i.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${r.state} (${r.reason})`,r.lastRefresh?`Last refresh: ${r.lastRefresh.result} by ${r.lastRefresh.trigger.kind} at ${r.lastRefresh.completedAt}.`:void 0,`Detected languages: ${a}.`,s.length>0?`Unavailable or partial capabilities: ${s.join(", ")}.`:"Core capabilities are available.","Use the scip-query router skill when exploring, planning, verifying, debugging, diagramming, or cleaning up code.","Before a non-trivial edit, establish the current entry-to-effect flow, affected consumers, and reuse options with scip-plan; then verify the finished diff with scip-verify."].filter(c=>c!==void 0).join(`
42
- `)}function Gy(e,t={},n=process.env){if(zy(t,n)==="off")return"";let r=Jy(e);return r?`scip-query routing reminder:
43
- ${r.message}`:""}var ld=[{id:"setup",skillNames:["scip-setup"],keywords:["setup","adopt","install","bootstrap"],message:"Setup request: use scip-setup; keep CI setup out of the default path."},{id:"debug",skillNames:["scip-diagnose"],keywords:["debug","bug","regression","failing","fails","error","wrong","broken","doesn't work","not working","crash"],message:"Debug, root-cause, or issue-triage request: use scip-diagnose."},{id:"review",skillNames:["scip-audit","scip-plan","scip-verify"],keywords:["review","maintainability","architecture","boundary"],message:"Review request: use scip-audit for current structure, scip-plan for prospective API impact, or scip-verify for a finished change."},{id:"implementation",skillNames:["scip-plan","scip-verify"],keywords:["implement","build","change","refactor","fix","add","update"],message:"Before editing: use scip-plan and `scip-query plan-context <target>` to establish the current flow, affected consumers, and reuse options. After editing: use scip-verify."},{id:"exploration",skillNames:["scip-explore"],keywords:["explain","how does","walk me through","trace","understand"],message:"Exploration request: use scip-explore before answering behavioral questions."},{id:"diagram",skillNames:["scip-explore"],keywords:["diagram","visualize","visualise","flow map","architecture map"],message:"Diagram request: use scip-explore and back every node and edge with scip-query evidence."},{id:"health",skillNames:["scip-audit","scip-improve"],keywords:["health","score","dossier","cleanup","dead code","duplicate","debloat","as high as","maximize","maximise"],message:"Health or cleanup request: use scip-audit before editing; use scip-improve when the user wants confirmed issues fixed autonomously."}];function Jy(e){let t=ld.find(i=>i.skillNames.some(o=>dd(e,o)));if(t)return t;let n=0,r=[];for(let i of ld){let o=i.keywords.filter(s=>dd(e,s)).length;n+=o,o>0&&r.push(i)}return n<2||r.length===0?null:r[0]}function zy(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function dd(e,t){let n=t.trim().split(/\s+/).map(r=>Me(r)).join("\\s+");return new RegExp(`(?<![A-Za-z0-9_-])${n}(?![A-Za-z0-9_-])`,"i").test(e)}function qi(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Ky(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function Vi(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=Ws(t);if(n)try{let r=be(n),i=_e(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}function Qy(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,sharedEvidenceDbPath:Yc(e.projectRoot,e.config),entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality,architecture:e.config.architecture,coverageContracts:e.config.coverageContracts,docs:e.config.docs},r=new Be(n,Ct(e.projectRoot));try{return t(r)}finally{r.close()}}import{existsSync as fr,mkdirSync as nb,symlinkSync as rb,readlinkSync as Ui,unlinkSync as Gi,readdirSync as Td}from"fs";import{join as Le,dirname as mn,resolve as nt,relative as ib,isAbsolute as ob}from"path";import{homedir as gr,platform as sb}from"os";import{fileURLToPath as Id}from"url";import{execFileSync as kd}from"child_process";import{createRequire as Xy}from"module";import{existsSync as Yy}from"fs";import{platform as un,arch as wd}from"os";var $d="v0.8.1",Wi="https://github.com/sourcegraph/scip",Cd="SCIP_QUERY_SCIP_BIN";function Zy(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[Cd];if(t&&e.fileExists(t))return{source:"env",path:t};if(e.platform==="win32"){let n=e.resolveSidecar(e.arch);if(n&&e.fileExists(n))return{source:"sidecar",path:n}}return null}function eb(e){let t=Xy(import.meta.url);for(let n of e==="arm64"?["arm64","x64"]:[e])try{return t.resolve(`scip-query-scip-windows/scip-win32-${n}.exe`)}catch{}return null}function mr(e=process.env){return Zy({platform:un(),arch:wd(),env:e,isOnPath:Ye,fileExists:Yy,resolveSidecar:eb})?.path??null}function pn(){return mr()!==null}function tb(){let e=un(),t=wd(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`${Wi}/releases/download/${$d}/${o}`,filename:o}}function Hi(){let e=tb();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),un()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
44
- `),console.log("Or download manually:")):un()==="win32"?(console.log("On Windows the scip binary ships via the npm sidecar package scip-query-scip-windows,"),console.log("installed automatically with scip-query. If it is missing:"),console.log(" npm install -g scip-query-scip-windows"),console.log(`Or set ${Cd} to a local scip.exe path.
45
- `),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
46
- `:` ${Wi}/releases/tag/${$d}
47
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Pd(e){if(un()==="darwin"&&Ye("brew")){e("Installing scip CLI via Homebrew...");try{if(kd("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),Ye("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`Homebrew install failed: ${n}`)}}if(Ye("go")){e("Installing scip CLI via go install...");try{if(kd("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),Ye("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${Wi}/releases`),!1}var ab=sb()==="win32",hr=["_shared","scip-query","scip-setup","scip-explore","scip-plan","scip-diagnose","scip-audit","scip-improve","scip-verify"];function yr(e={}){let t=e.quiet?()=>{}:console.log,n=Id(import.meta.url),r=nt(mn(n),"..","skills"),i=[Le(gr(),".claude","skills"),Le(gr(),".codex","skills"),Le(gr(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=mn(s);if(!fr(a))continue;nb(s,{recursive:!0});let c=Ad(s);cb(s,r,c,o,t);for(let l of hr){let d=Le(r,l),u=Le(s,l);if(!fr(d)){o.skipped.push(`${c}/${l}`);continue}if(fr(u)){try{let m=Ui(u);if(nt(m)===nt(d)){o.alreadyLinked.push(`${c}/${l}`),t(` ok: ${l} \u2192 ${c} (already linked)`);continue}}catch{o.skipped.push(`${c}/${l}`),t(` skip: ${l} \u2192 ${c} (exists, not a symlink)`);continue}Gi(u)}rb(d,u,ab?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function cb(e,t,n,r,i){let o=new Set(hr);for(let s of Td(e)){if(o.has(s))continue;let a=Le(e,s),c;try{c=nt(mn(a),Ui(a))}catch{continue}jd(c,t)&&(Gi(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function Ed(e={}){let t=Id(import.meta.url),n=nt(mn(t),"..","skills"),r=e.homeDir??gr(),i=[Le(r,".claude","skills"),Le(r,".codex","skills"),Le(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!fr(s))continue;let a=Ad(s);for(let c of Td(s)){let l=Le(s,c),d;try{let u=Ui(l);d=nt(mn(l),u)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!jd(d,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{Gi(l)}catch(u){o.skipped.push(`${a}/${c} (${u instanceof Error?u.message:String(u)})`)}}}return o}function jd(e,t){let n=ib(nt(t),nt(e));return n===""||!n.startsWith("..")&&!ob(n)}function Ad(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as fm}from"child_process";import{performance as ot}from"perf_hooks";import{existsSync as Pe,readFileSync as ww,renameSync as $w,rmSync as Cw,unlinkSync as Pw,writeFileSync as Tw}from"fs";import{dirname as Br,extname as Iw,join as ht,resolve as Ew}from"path";import{execFileSync as XR}from"child_process";import{createHash as YR}from"crypto";import{copyFileSync as jr,existsSync as Ce,mkdirSync as Ir,mkdtempSync as ZR,readdirSync as lp,readFileSync as Co,renameSync as dp,rmSync as Nt,statSync as ex}from"fs";import{basename as Tr,dirname as q,extname as tx,join as re,resolve as tp}from"path";import{platform as nx}from"os";import lb from"better-sqlite3";import{execFileSync as db}from"child_process";import{existsSync as ub,readdirSync as pb,readFileSync as mb}from"fs";import{extname as br,join as Ld}from"path";function gt(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Sr({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Sr(e){let t=new Set((e.extensions??vs).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!ub(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Ct(e.projectRoot),r=fb(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new lb(e.dbPath);try{let o=hb(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
48
- VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let u=0;for(let m of d){if(o.has(m))continue;let g=mb(Ld(e.projectRoot,m),"utf-8"),f=s.run(yb(m),m,g);u+=Number(f.changes)}return u})(r),l={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${l.existing} already present).`),l}finally{i.close()}}function fb(e,t){let n=gb(e,t);if(n)return n;let r=[],i=o=>{let s=o?Ld(e,o):e,a;try{a=pb(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Rs.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(br(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function gb(e,t){try{return db("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split(`
49
- `).filter(r=>r&&t.has(br(r).toLowerCase())).sort()}catch{return null}}function hb(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.add(a.relative_path)}return n}function yb(e){return br(e).toLowerCase()===".vue"?"vue":br(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Ob}from"crypto";import{existsSync as Db,readFileSync as Fb}from"fs";import{dirname as Mb,join as Dd}from"path";function Ji(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function vr(e,t,n){let r=e.changes.map(a=>a.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=Ji(e),s=new Set(o.reasons);return r.some(a=>!i.has(a))&&s.add("changed-file-outside-project"),t===null?(s.add("dependency-graph-unavailable"),Od(r,i,s)):s.size>0?Od(r,i,s):{mode:"closure",changedFiles:r,affectedFiles:bb(r,t,i),reasons:[]}}function Od(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function bb(e,t,n){let r=new Map;for(let[s,a]of t)if(n.has(s))for(let c of a){if(!n.has(c))continue;let l=r.get(c)??new Set;l.add(s),r.set(c,l)}let i=new Set(e),o=[...e];for(let s=0;s<o.length;s+=1){let a=o[s];if(a!==void 0)for(let c of r.get(a)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}import{appendFileSync as Sb,existsSync as vb,mkdirSync as Rb,readFileSync as xb,renameSync as kb,rmSync as wb,statSync as $b,truncateSync as Cb}from"fs";import{basename as Pb,dirname as Tb}from"path";var fn=".previous",Ib=".rotation.lock",Eb=2e3,zi=class extends Error{constructor(n,r){super(`Timed out after ${r}ms waiting for rotating JSONL lock: ${n}`);this.lockPath=n;this.timeoutMs=r;this.name="RotatingJsonlLockTimeoutError"}lockPath;timeoutMs;code="ROTATING_JSONL_LOCK_TIMEOUT"},Ki=class extends Error{constructor(n){super(`Rotating JSONL lock ownership changed before release: ${n}`);this.lockPath=n;this.name="RotatingJsonlLockReleaseError"}lockPath;code="ROTATING_JSONL_LOCK_RELEASE_FAILED"},jb=Object.freeze({monotonicNow:B,wait(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},tryAcquireLock(e,t){let n=Jn(e,{kind:"rotating-jsonl",detail:{target:Pb(t)}});return n.kind==="acquired"?{kind:"acquired",lock:n.lock}:{kind:"contended"}},makeDirectory(e){Rb(e,{recursive:!0})},exists:vb,readBytes(e){return xb(e)},size(e){return $b(e).size},truncate:Cb,remove(e){wb(e,{force:!0})},rename:kb,append:Sb});function Rr(e,t,n){let r=n.runtime??jb,i=JSON.stringify(t);if(i===void 0)throw new TypeError("Rotating JSONL records must be JSON-serializable values.");let o=Buffer.from(`${i}
50
- `),s=Math.max(1,Math.floor(n.maxSegmentBytes),o.length);return Ab(e,n.lockTimeoutMs,r,()=>{r.makeDirectory(Tb(e));let a=Lb(e,r);n.onPhase?.("tail-repaired");let c=`${e}${n.previousSuffix??fn}`,l=!1,d=!1;return r.exists(e)&&r.size(e)+o.length>s&&(r.exists(c)&&(r.remove(c),d=!0),n.onPhase?.("previous-pruned"),r.rename(e,c),l=!0,n.onPhase?.("current-rotated")),r.append(e,o),n.onPhase?.("record-appended"),{lineBytes:o.length,segmentLimitBytes:s,repairedTailBytes:a,rotated:l,prunedPrevious:d}})}function Ab(e,t,n,r){let i=`${e}${Ib}`,o=Math.max(0,t??Eb),s=n.monotonicNow()+o,a;for(;;){let m=n.tryAcquireLock(i,e);if(m.kind==="acquired"){a=m.lock;break}let g=s-n.monotonicNow();if(g<=0)throw new zi(i,o);n.wait(Math.min(5,g))}let c=!1,l,d;try{d=r()}catch(m){c=!0,l=m}let u=!1;try{u=a.release()}catch(m){if(!c)throw m}if(c)throw l;if(!u)throw new Ki(i);return d}function Lb(e,t){if(!t.exists(e))return 0;let n=t.readBytes(e);if(n.length===0||n[n.length-1]===10)return 0;let r=n.lastIndexOf(10),i=r<0?0:r+1;return t.truncate(e,i),n.length-i}var Nb="<global-symbols>";function _b(e){let t=[];for(let n of e.all(`
51
- SELECT relative_path, language, position_encoding, text
52
- FROM documents
53
- `))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
54
- SELECT d.relative_path,
55
- c.chunk_index,
56
- c.start_line,
57
- c.end_line,
58
- hex(c.occurrences) AS occurrences_hex
59
- FROM chunks c
60
- JOIN documents d ON d.id = c.document_id
61
- `))t.push({relativePath:n.relative_path,kind:"chunk",values:[n.chunk_index,n.start_line,n.end_line,n.occurrences_hex]});for(let n of e.all(`
62
- SELECT d.relative_path,
63
- r.start_line,
64
- r.start_char,
65
- r.end_line,
66
- r.end_char,
67
- g.symbol,
68
- g.display_name,
69
- g.kind,
70
- g.documentation,
71
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
72
- g.enclosing_symbol,
73
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
74
- FROM defn_enclosing_ranges r
75
- JOIN documents d ON d.id = r.document_id
76
- JOIN global_symbols g ON g.id = r.symbol_id
77
- `))t.push({relativePath:n.relative_path,kind:"definition",values:Qi(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
78
- SELECT d.relative_path,
79
- c.chunk_index,
80
- m.role,
81
- g.symbol,
82
- g.display_name,
83
- g.kind,
84
- g.documentation,
85
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
86
- g.enclosing_symbol,
87
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
88
- FROM mentions m
89
- JOIN chunks c ON c.id = m.chunk_id
90
- JOIN documents d ON d.id = c.document_id
91
- JOIN global_symbols g ON g.id = m.symbol_id
92
- `))t.push({relativePath:n.relative_path,kind:"mention",values:Qi(n,[n.chunk_index,n.role])});for(let n of e.all(`
93
- SELECT g.symbol,
94
- g.display_name,
95
- g.kind,
96
- g.documentation,
97
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
98
- g.enclosing_symbol,
99
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
100
- FROM global_symbols g
101
- WHERE NOT EXISTS (
102
- SELECT 1 FROM defn_enclosing_ranges r WHERE r.symbol_id = g.id
103
- ) AND NOT EXISTS (
104
- SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
105
- )
106
- `))t.push({relativePath:Nb,kind:"global-symbol",values:Qi(n)});return Bb(t)}function Bb(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),o=t.get(r.relativePath)??[];o.push(i),t.set(r.relativePath,o)}let n=new Map;for(let[r,i]of[...t].sort(([o],[s])=>o.localeCompare(s))){let o=Ob("sha256");for(let s of i.sort())o.update(String(Buffer.byteLength(s))),o.update(":"),o.update(s),o.update(`
107
- `);n.set(r,o.digest("hex"))}return n}function qb(e,t){let n=[],r=[],i=[],o=[],s=new Set([...e.keys(),...t.keys()]);for(let a of[...s].sort()){let c=e.get(a),l=t.get(a);c===void 0?n.push(a):l===void 0?i.push(a):c!==l?r.push(a):o.push(a)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function Xi(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),s=e.affectedFiles.filter(c=>!i.has(c)).sort(),a=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:a/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:s}}function Yi(e,t=Gb){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),s=(l,d)=>{let u=r();return Hd(e.refreshResult,l,n?u:i(),Math.max(0,u-o),d)};if(!t.databaseExists(e.previousDbPath))return s("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return s("candidate-index-unavailable");let a=null,c=null;try{a=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let l=[...new Set([...t.indexedPaths(a),...t.indexedPaths(c)])].sort(),d=jn(e.previousSnapshot,e.currentSnapshot),u=new Set(l),m=d.changes.length>0&&!Ji(d).fullProject&&d.changes.every(b=>u.has(b.path)),g=vr(d,m?t.dependencyGraph(a):new Map,l),f=qb(t.factDigests(a),t.factDigests(c)),h=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?h:i()).toISOString(),durationMs:Math.max(0,h-o),manifest:d,plan:g,comparison:f,evaluation:Xi(g,f,l.length)}}catch(l){return s("oracle-error",l instanceof Error?l.message:String(l))}finally{Fd(a),Fd(c)}}function _d(e,t,n,r=Date.now()){return Hd(e,t,r,0,n)}function Bd(e){let t=Mb(e);return{latestPath:Dd(t,"affected-shadow-latest.json"),historyPath:Dd(t,"affected-shadow.jsonl")}}function qd(e,t=n=>Fb(n,"utf-8")){let n=Bd(e),r;try{r=JSON.parse(t(n.latestPath))}catch(y){let v=Xb(y),R=v?"telemetry-missing":Qb(y);return rt(n,R,v?void 0:y instanceof Error?y.message:String(y))}if(W(r)&&typeof r.version=="number"&&r.version!==1)return rt(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!zb(r))return rt(n,"telemetry-malformed");if(r.status==="unavailable")return Kb(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:rt(n,"telemetry-malformed");if(r.status!=="evaluated")return rt(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!W(r.manifest)||!W(i)||!W(o)||!W(s))return rt(n,"telemetry-malformed");let a=i.mode,c=X(i.affectedFiles),l=X(i.reasons),d=X(o.changedFiles),u=X(s.predictedFiles),m=X(s.actualFiles),g=X(s.missingFiles),f=s.recall,h=s.affectedRatio;if(a!=="none"&&a!=="closure"&&a!=="full-project"||c===null||l===null||d===null||u===null||m===null||g===null||typeof s.passed!="boolean"||!Md(f)||!Md(h))return rt(n,"telemetry-malformed");let b=m.length===0?1:(m.length-g.length)/m.length;return!Nd(c,u)||!Nd(d,m)||s.passed!==(g.length===0)||Math.abs(f-b)>Number.EPSILON||g.some(y=>!m.includes(y)||u.includes(y))?rt(n,"telemetry-malformed"):{state:s.passed?"passing":"failing",...n,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,mode:a,recall:f,affectedRatio:h,predictedFiles:u,actualFiles:m,missingFiles:g,fallbackReasons:l}}function Vd(e){if(e.state==="unavailable")return`unavailable (${e.reason})`;let t=e.missingFiles.length>0?`, ${e.missingFiles.length} missed`:"",n=e.fallbackReasons.length>0?`; fallback: ${e.fallbackReasons.join(", ")}`:"";return`${e.state}, ${(e.recall*100).toFixed(1)}% recall, ${e.predictedFiles.length} predicted / ${e.actualFiles.length} changed, ${(e.affectedRatio*100).toFixed(1)}% of project${t}${n}`}function Wd(e,t,n=Jb){let r=Bd(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var Vb=8*1024*1024,Wb=fn;function Hb(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function Ub(e,t,n=Vb){Rr(e,Hb(t),{maxSegmentBytes:n,previousSuffix:Wb})}function Qi(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var Gb={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:B,databaseExists:e=>Db(e),openDatabase:(e,t,n)=>new Be({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>An(e),dependencyGraph:e=>Dn(e),factDigests:e=>_b(e)},Jb={appendHistory:Ub,writeLatest:(e,t)=>Fs(e,t,{spacing:2,trailingNewline:!0})};function Hd(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(n).toISOString(),durationMs:r,reason:t,...i?{error:i}:{}}}function Fd(e){try{e?.close()}catch{}}function zb(e){return W(e)&&e.version===1&&typeof e.recordedAt=="string"&&(e.refreshResult==="rebuilt"||e.refreshResult==="reused")&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0}function Kb(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function Md(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function Nd(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function rt(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function Qb(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function Xb(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as Yb}from"crypto";import{copyFileSync as Zb,existsSync as Ud,rmSync as Gd}from"fs";import{resolve as eS}from"path";import Kd from"better-sqlite3";var tS={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},nS={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Qd(e){let t=B(),n=rS(e.affectedFiles);if(iS(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Gd(e.candidateDbPath,{force:!0}),!Ud(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Ud(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");Jd(e.previousDbPath,"previous SQLite generation",!1),Jd(e.miniDbPath,"incremental SQLite mini database"),Zb(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new Kd(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Zi(r,"main","candidate SQLite generation"),Zi(r,"incremental","incremental SQLite mini database"),oS(r,n),sS(r,n.length);let i=eo(r,"main",!0),o=it(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{aS(r),cS(r),lS(r),e.onStage?.("after-delete"),dS(r),e.onStage?.("after-symbol-reconciliation"),uS(r),e.onStage?.("after-insert"),pS(r),mS(r,n.length,o),e.onStage?.("before-commit")}).immediate(),Xd(r,"main","candidate SQLite generation");let c=[...fS(r)].filter(([l,d])=>i.get(l)!==d).map(([l])=>l).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:B()-t}}catch(i){try{r?.close()}finally{Gd(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function rS(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function iS(e,t,n){let r=[e,t,n].map(i=>eS(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Jd(e,t,n=!0){let r=new Kd(e,{readonly:!0,fileMustExist:!0});try{Zi(r,"main",t),n&&Xd(r,"main",t)}finally{r.close()}}function Zi(e,t,n){for(let[r,i]of Object.entries(tS)){let s=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:a,type:c,notnull:l,pk:d})=>({name:a,type:c.toUpperCase(),notnull:l,pk:d}));if(JSON.stringify(s)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(nS)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),s=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(a=>a.name);if(o?.tbl_name!==i.table||JSON.stringify(s)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}zd(e,t,"documents",["relative_path"],n),zd(e,t,"global_symbols",["symbol"],n)}function zd(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(a=>{if(a.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${a.name}')`).all().map(l=>l.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function Xd(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function oS(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function sS(e,t){let n=it(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=it(e,`SELECT COUNT(*) AS value
108
- FROM main.documents d
109
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
110
- FROM temp.incremental_affected_paths p
111
- LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
112
- WHERE d.id IS NULL
113
- LIMIT 1`).pluck().get(),o=e.prepare(`SELECT d.relative_path
114
- FROM incremental.documents d
115
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
116
- WHERE p.relative_path IS NULL
117
- LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function aS(e){e.exec(`
118
- CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
119
- INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
120
- SELECT g.symbol
121
- FROM main.defn_enclosing_ranges r
122
- JOIN main.documents d ON d.id = r.document_id
123
- JOIN main.global_symbols g ON g.id = r.symbol_id
124
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path;
125
- INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
126
- SELECT g.symbol
127
- FROM main.mentions m
128
- JOIN main.chunks c ON c.id = m.chunk_id
129
- JOIN main.documents d ON d.id = c.document_id
130
- JOIN main.global_symbols g ON g.id = m.symbol_id
131
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
132
- WHERE m.role = 1;
133
-
134
- CREATE TEMP TABLE incremental_new_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
135
- INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
136
- SELECT g.symbol
137
- FROM incremental.defn_enclosing_ranges r
138
- JOIN incremental.global_symbols g ON g.id = r.symbol_id;
139
- INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
140
- SELECT g.symbol
141
- FROM incremental.mentions m
142
- JOIN incremental.global_symbols g ON g.id = m.symbol_id
143
- WHERE m.role = 1;
144
- `)}function cS(e){let t=e.prepare(`WITH changed_symbols AS (
145
- SELECT symbol FROM temp.incremental_old_defined_symbols
146
- UNION
147
- SELECT symbol FROM temp.incremental_new_defined_symbols
148
- ), unaffected_definitions AS (
149
- SELECT g.symbol
150
- FROM main.defn_enclosing_ranges r
151
- JOIN main.documents d ON d.id = r.document_id
152
- JOIN main.global_symbols g ON g.id = r.symbol_id
153
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
154
- WHERE p.relative_path IS NULL
155
- UNION
156
- SELECT g.symbol
157
- FROM main.mentions m
158
- JOIN main.chunks c ON c.id = m.chunk_id
159
- JOIN main.documents d ON d.id = c.document_id
160
- JOIN main.global_symbols g ON g.id = m.symbol_id
161
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
162
- WHERE m.role = 1 AND p.relative_path IS NULL
163
- )
164
- SELECT u.symbol
165
- FROM unaffected_definitions u
166
- JOIN changed_symbols c ON c.symbol = u.symbol
167
- LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function lS(e){e.exec(`
168
- DELETE FROM main.mentions
169
- WHERE chunk_id IN (
170
- SELECT c.id
171
- FROM main.chunks c
172
- JOIN main.documents d ON d.id = c.document_id
173
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
174
- );
175
- DELETE FROM main.chunks
176
- WHERE document_id IN (
177
- SELECT d.id
178
- FROM main.documents d
179
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
180
- );
181
- DELETE FROM main.defn_enclosing_ranges
182
- WHERE document_id IN (
183
- SELECT d.id
184
- FROM main.documents d
185
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
186
- );
187
- DELETE FROM main.documents
188
- WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
189
- `)}function dS(e){e.exec(`
190
- UPDATE main.global_symbols
191
- SET display_name = NULL,
192
- kind = NULL,
193
- documentation = NULL,
194
- signature = NULL,
195
- enclosing_symbol = NULL,
196
- relationships = NULL
197
- WHERE symbol IN (SELECT symbol FROM temp.incremental_old_defined_symbols);
198
-
199
- INSERT OR IGNORE INTO main.global_symbols(
200
- symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
201
- )
202
- SELECT symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
203
- FROM incremental.global_symbols;
204
-
205
- UPDATE main.global_symbols
206
- SET display_name = (
207
- SELECT source.display_name FROM incremental.global_symbols source
208
- WHERE source.symbol = main.global_symbols.symbol
209
- ),
210
- kind = (
211
- SELECT source.kind FROM incremental.global_symbols source
212
- WHERE source.symbol = main.global_symbols.symbol
213
- ),
214
- documentation = (
215
- SELECT source.documentation FROM incremental.global_symbols source
216
- WHERE source.symbol = main.global_symbols.symbol
217
- ),
218
- signature = (
219
- SELECT source.signature FROM incremental.global_symbols source
220
- WHERE source.symbol = main.global_symbols.symbol
221
- ),
222
- enclosing_symbol = (
223
- SELECT source.enclosing_symbol FROM incremental.global_symbols source
224
- WHERE source.symbol = main.global_symbols.symbol
225
- ),
226
- relationships = (
227
- SELECT source.relationships FROM incremental.global_symbols source
228
- WHERE source.symbol = main.global_symbols.symbol
229
- )
230
- WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
231
- `)}function uS(e){let t=it(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=it(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=it(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
232
- SELECT id + ?, language, relative_path, position_encoding, text
233
- FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
234
- SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
235
- FROM incremental.chunks`).run(n,t),e.prepare(`INSERT INTO main.mentions(chunk_id, symbol_id, role)
236
- SELECT m.chunk_id + ?, target.id, m.role
237
- FROM incremental.mentions m
238
- JOIN incremental.global_symbols source ON source.id = m.symbol_id
239
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(n),e.prepare(`INSERT INTO main.defn_enclosing_ranges(
240
- id, document_id, symbol_id, start_line, start_char, end_line, end_char
241
- )
242
- SELECT r.id + ?, r.document_id + ?, target.id,
243
- r.start_line, r.start_char, r.end_line, r.end_char
244
- FROM incremental.defn_enclosing_ranges r
245
- JOIN incremental.global_symbols source ON source.id = r.symbol_id
246
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function pS(e){e.exec(`
247
- DELETE FROM main.global_symbols
248
- WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
249
- AND NOT EXISTS (
250
- SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
251
- );
252
- `)}function mS(e,t,n){let r=it(e,"SELECT COUNT(*) AS value FROM main.documents"),i=it(e,`SELECT COUNT(*) AS value
253
- FROM main.documents d
254
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),s=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||s!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function fS(e){let t=eo(e,"main",!0),n=eo(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function eo(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
255
- FROM ${t}.documents d
256
- ${r}
257
- ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
258
- FROM ${t}.chunks c
259
- JOIN ${t}.documents d ON d.id = c.document_id
260
- ${r}
261
- ORDER BY d.relative_path, c.chunk_index, c.start_line, c.end_line, c.id`).all(),s=e.prepare(`SELECT d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char,
262
- g.symbol, g.display_name, g.kind, g.documentation,
263
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature,
264
- g.enclosing_symbol,
265
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships
266
- FROM ${t}.defn_enclosing_ranges r
267
- JOIN ${t}.documents d ON d.id = r.document_id
268
- JOIN ${t}.global_symbols g ON g.id = r.symbol_id
269
- ${r}
270
- ORDER BY d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char, g.symbol`).all(),a=e.prepare(`SELECT d.relative_path, c.chunk_index, m.role, g.symbol
271
- FROM ${t}.mentions m
272
- JOIN ${t}.chunks c ON c.id = m.chunk_id
273
- JOIN ${t}.documents d ON d.id = c.document_id
274
- JOIN ${t}.global_symbols g ON g.id = m.symbol_id
275
- ${r}
276
- ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,u]of Object.entries({documents:i,chunks:o,definitions:s,mentions:a}))for(let m of u){let g=JSON.stringify([d,m]),f=c.get(m.relative_path)??[];f.push(g),c.set(m.relative_path,f)}let l=new Map;for(let[d,u]of[...c].sort(([m],[g])=>m.localeCompare(g))){let m=Yb("sha256");for(let g of u.sort())m.update(g).update(`
277
- `);l.set(d,m.digest("hex"))}return l}function it(e,t){return e.prepare(t).get().value}import{readFileSync as gS,writeFileSync as hS}from"fs";function Ft(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}async function Zd(e){let t=e.readFingerprint(),n=yS(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return bS(e.cachePath,e.readFingerprint(),r),r}function yS(e,t){try{let n=JSON.parse(gS(e,"utf-8"));return Yd(n.fingerprint)===Yd(t)?{result:n.result}:null}catch{return null}}function bS(e,t,n){hS(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
278
- `)}function Yd(e){return JSON.stringify(e)}import{readFileSync as ej,statSync as SS}from"fs";import{dirname as vS,join as RS}from"path";var to="reindex-activity.jsonl",xS=fn,kS=1024*1024,rj=1440*60*1e3;function no(e){return RS(vS(e),to)}function wS(e){if(e.reused)return 0;let t=eu(e.indexPath)+eu(e.dbPath);for(let n of e.shards??[])!n.reused&&n.outputBytes!==null&&(t+=n.outputBytes);return t}function ro(e,t){let n=t.lastRefresh;n&&io(no(e),{version:1,event:"run",recordedAt:n.completedAt,trigger:n.trigger,result:n.result,durationMs:n.durationMs,estimatedLogicalOutputBytes:wS(t)})}function tu(e,t){io(no(e),{version:1,event:"run",recordedAt:t.completedAt,trigger:t.trigger,result:"failed",durationMs:t.durationMs,estimatedLogicalOutputBytes:0})}function nu(e,t,n=new Date){io(no(e),{version:1,event:"suppressed",recordedAt:n.toISOString(),trigger:t,reason:"completed-index-is-fresh"})}function $S(e,t,n=kS,r){Rr(e,t,{maxSegmentBytes:n,previousSuffix:xS,...r?{runtime:r}:{}})}function io(e,t){try{$S(e,t)}catch{}}function eu(e){try{return SS(e).size}catch{return 0}}import{createHash as CS}from"crypto";import{existsSync as oo,readFileSync as PS,readdirSync as TS}from"fs";import{dirname as so,join as xr,relative as IS,resolve as ao,sep as ru}from"path";function iu(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=cu(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function ou(e,t){let n=new Map;for(let i of e){let o=t[i]?.packageName;o&&n.set(o,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let o=t[i],s=r.get(i);if(!o||o.parseFailed){for(let a of e)a!==i&&s.add(a);continue}for(let a of o.dependencyNames){let c=n.get(a);c&&c!==i&&s.add(c)}for(let a of[...o.pathsTargets,...o.referencesPaths]){let c=cu(a,e);c&&c!==i&&s.add(c)}}return ES(e,r)}function su(e,t,n){let r={};for(let i of e){let o=new Map;for(let s of t.files[i]??[])o.set(s.path,s);for(let s of n[i]??[])for(let a of t.files[s]??[])o.set(a.path,a);for(let s of t.shared)o.set(s.path,s);r[i]={files:[...o.values()].sort((s,a)=>s.path.localeCompare(a.path))}}return r}function co(e){if(e===".")return"root";let t=CS("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function au(e,t){let n=ao(e),r={};for(let i of t)r[i]=jS(n,i);return r}function cu(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function ES(e,t){let n={};for(let r of e){let i=new Set,o=[...t.get(r)??[]];for(;o.length>0;){let s=o.pop();if(!(s===r||i.has(s))){i.add(s);for(let a of t.get(s)??[])a!==r&&!i.has(a)&&o.push(a)}}n[r]=[...i].sort((s,a)=>s.localeCompare(a))}return n}function jS(e,t){let n=t==="."?e:xr(e,t),r=AS(n),i=LS(n),o=i?OS(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:o.pathsTargets,referencesPaths:o.referencesPaths,parseFailed:r.failed||o.failed}}function AS(e){let t=xr(e,"package.json");if(!oo(t))return{name:void 0,dependencyNames:[],failed:!1};let n=lo(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let o of["dependencies","devDependencies","peerDependencies"]){let s=n.value[o];if(s&&typeof s=="object"&&!Array.isArray(s))for(let a of Object.keys(s))i.add(a)}return{name:r,dependencyNames:[...i],failed:!1}}function LS(e){let t=xr(e,"tsconfig.json");if(oo(t))return t;let n;try{n=TS(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?xr(e,n[0]):void 0}function OS(e,t){let n=lo(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=DS(n.value,e,t),i=lu(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function DS(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=so(t),o=new Set;for(let s of r){if(!s||typeof s!="object")continue;let a=s.path;if(typeof a!="string"||a.trim()==="")continue;let c=du(a,i,n);c&&o.add(c)}return[...o]}function lu(e,t,n,r){let i=FS(t);if(i)return{pathsTargets:MS(i,so(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=NS(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=lo(o);return s.ok?lu(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function FS(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function MS(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let o of i){if(typeof o!="string")continue;let s=du(o,t,n);s&&r.add(s)}return[...r]}function NS(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=ao(so(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(ru).includes("node_modules")&&he(n,i)&&oo(i))return i}function du(e,t,n){let r=e.replace(/\/?\*+$/,""),i=ao(t,r===""?".":r);if(!he(n,i))return;let s=IS(n,i).split(ru).join("/");return s===""?".":s}function _S(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){if(t+=o,o==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}o==='"'&&(r=!1),n+=1;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
279
- `;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function lo(e){try{let t=PS(e,"utf-8"),n=JSON.parse(_S(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as BS,readFileSync as qS,readdirSync as VS,statSync as WS}from"fs";import oe from"path";var HS=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function gn(e,t=[]){let n=oe.resolve(e),r=t.flatMap(c=>GS(n,c));if(r.length>0)return uu(n,pu(r));let i=US(n),o=pu(i),s=zS(n,o)?[n,...o]:o,a=s.length>0?s:[n];return uu(n,a)}function uu(e,t){return[...new Set(t.map(n=>QS(e,n)))].sort((n,r)=>n.localeCompare(r))}function US(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=VS(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=oe.join(r,o.name);if(o.isDirectory()){!HS.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&JS(s)&&t.push(oe.dirname(s))}}return t}function GS(e,t){let n=t.trim();if(!n)return[];let r=oe.resolve(e,n);if(!he(e,r))return[];try{let i=WS(r);if(i.isDirectory())return[r];if(i.isFile()&&mu(oe.basename(r)))return[oe.dirname(r)]}catch{return[]}return[]}function JS(e){if(!mu(oe.basename(e)))return!1;let t=fu(e);return t?oe.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function mu(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function pu(e){let t=[...new Set(e.map(n=>oe.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&XS(n,r)))}function zS(e,t){if(t.length===0||t.some(r=>oe.resolve(r)===e))return!1;let n=oe.join(e,"tsconfig.json");return BS(n)&&KS(n)}function KS(e){let n=fu(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!oe.extname(r))):!1}function fu(e){try{let t=JSON.parse(qS(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function QS(e,t){let n=oe.relative(e,t);return n?n.split(oe.sep).join("/"):"."}function XS(e,t){let n=oe.relative(e,t);return!!n&&!n.startsWith("..")&&!oe.isAbsolute(n)}import{createHash as bv}from"crypto";import{existsSync as po,readFileSync as $u,statSync as Sv,writeFileSync as mo}from"fs";import{join as vv}from"path";import{readFileSync as gu}from"fs";import{createRequire as YS}from"module";import{dirname as ZS,isAbsolute as yj,relative as bj,resolve as Sj,sep as vj}from"path";var hu=YS(import.meta.url),ev=1,yu="0.4.0";function uo(){let e=tv();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function tv(){try{let e=hu.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(gu(e,"utf8"));if(t.version!==yu)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${yu}`};let n=ZS(e),r=hu.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(gu(r,"utf8"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:nv(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function nv(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${ev}`}import{createHash as rv}from"crypto";import{readFileSync as iv}from"fs";import{dirname as ov,join as bu}from"path";var kr=3;var sv="typescript-index";function Su(e){let t=bu(e,sv),n=Ns(t);return{...n,requestDir:n.legacyRequestDir}}function vu(e){try{let t=hs(vt(iv(bu(ov(e),"meta.json"),"utf8")));return t?rv("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as av}from"crypto";import{existsSync as cv,readFileSync as lv}from"fs";var dv=12e4,uv=5,wr=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;constructor(t,n={}){this.projectRoot=Us(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??hv(),this.runtime=n.runtime??yv,this.mailboxLimits=n.mailboxLimits??{}}request(t){let n=Wn(this.cacheDir),r=Su(this.cacheDir),i=pi(n.statePath);if(!Ru(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.now(),s=o+this.timeoutMs,a=(this.runtime.monotonicNow??B)()+this.timeoutMs,c=di("typescript-index-v3",{baseGeneration:this.baseGeneration,request:t}),l=ui(c),d=_s(r,{mailboxVersion:li,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:s,protocolVersion:kr,id:l,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??B)()<=a;){if(cv(d.responsePath))return pv(lv(d.responsePath,"utf8"),l,c,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=pi(n.statePath);if(!Ru(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(uv)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}};function Ru(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===kr&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&Yt(e.processIdentity,r))}function pv(e,t,n,r,i,o){let s=JSON.parse(e);if(s.protocolVersion!==kr||s.id!==t||s.operationKey!==n||s.ok===!0&&s.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(s.ok!==!0)throw new Error(typeof s.error=="string"?s.error:"TypeScript index service request failed.");let a=mv(s.response,i),c=[...new Set(o)].sort(),l=a.fragments.map(d=>d.relativePath).sort();if(JSON.stringify(l)!==JSON.stringify(c))throw new Error("TypeScript index service omitted or added an affected document.");return a}function mv(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(fv)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:gv(o.bytesBase64);return{relativePath:o.relativePath,bytes:s,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function fv(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function gv(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function hv(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:dv}var yv={now:Date.now,monotonicNow:B,randomId:av,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:xt,readProcessIdentity:kt};function Rv(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=jn(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(l=>l.kind!=="modified"||l.inputKind!=="source"||!en(l.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=vr(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=xv([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=xu(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=xu(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=wu(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=wu(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:ku(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:ku(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:a,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function xv(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function Cu(e){let t=B();try{if(!po(e.previousDbPath)||!po(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=uo();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new Be({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),s,a;try{s=An(o,{includeIgnored:!1}).filter(en).sort(),a=Dn(o)}finally{o.close()}let c=performance.now()-n,l=Rv({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?gn(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:a,producerIdentity:r.producerIdentity,rootTsconfigExists:po(vv(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let d=vu(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let m=new wr({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:l.tsconfigPath,projectArgument:l.projectArgument,projectIdentity:l.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles}),g=performance.now()-n,f=Sv(e.previousShardPath).size>=Hc;n=performance.now();let h=f?null:$u(e.previousShardPath),b=f?{completeIndexBytes:null,affectedIndexBytes:Bc(m.fragments)}:Wc({packageVersion:r.packageVersion,baseIndexBytes:h,fragments:m.fragments}),y=performance.now()-n;n=performance.now(),f?Uc({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:m.fragments}):(qc({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:h,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),Vc({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.nextFragmentGeneration,fragments:m.fragments,documentIdentities:l.nextDocumentIdentities}));let v=performance.now()-n;n=performance.now(),b.completeIndexBytes&&mo(e.candidateShardPath,b.completeIndexBytes),mo(e.candidateAffectedScipPath,b.affectedIndexBytes);let R=performance.now()-n,T={scipPath:f?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!f,durationMs:B()-t,cold:m.cold,changedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:l.previousFragmentGeneration,nextFragmentGeneration:l.nextFragmentGeneration,manifest:l.manifest,plan:l.plan,projectFileCount:s.length,referenceFragmentsByFile:new Map(m.fragments.map(D=>[D.relativePath,D.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:g,serviceMs:m.durationMs,assemblyMs:y,fragmentStoreMs:v,writeMs:R}};return e.onStatus(`Incremental TypeScript index emitted ${T.affectedFiles.length} affected document(s) in ${(T.durationMs/1e3).toFixed(3)}s (${T.cold?"cold":"warm"} service; ${f?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${g.toFixed(0)}ms, assembly ${y.toFixed(0)}ms, fragments ${v.toFixed(0)}ms, write ${R.toFixed(0)}ms).`),T}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function Pu(e){let t=uo();if(!t.available)throw new Error(t.reason);let n=Gc({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:$u(e.baseShardPath),packageVersion:t.packageVersion});mo(e.candidateShardPath,n)}function xu(e,t,n){let r=e.files.filter(i=>ms(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return fo(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function ku(e,t){return fo(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function wu(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),s=Xs({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),a=new Map;for(let c of i){let l=s.identityFor(c,"typescript-scip-document-v1");if(l.key){a.set(c,l.key);continue}if(o.has(c))return null;a.set(c,fo(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function fo(e){return bv("sha256").update(e).digest("hex")}import{existsSync as $r,renameSync as ho,rmSync as yo,statSync as kv}from"fs";import{cpus as wv}from"os";import{join as Iu}from"path";function $v(e,t,n){if(!e.defaultOutputPath)return;let r=Iu(t,e.defaultOutputPath);n!==r&&$r(r)&&ho(r,n)}function Cv(e,t,n){if(!e.defaultOutputPath)return null;let r=Iu(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return yo(i,{force:!0}),$r(r)?(ho(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Pv(e){e&&(yo(e.defaultOutputPath,{force:!0}),e.backupPath&&$r(e.backupPath)&&ho(e.backupPath,e.defaultOutputPath))}function Tv(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,wv().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Eu(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=Tv(o.length,r),c=await jv(o,a,l=>go(l,t,n));if(a>1){let l=new Map;for(let d of c.filter(u=>u.result.skipped&&u.retryable)){let u=o.find(m=>m.id===d.result.id);u&&(n(`Retrying ${u.label} indexer serially after parallel failure...`),l.set(u.id,(await go(u,t,n)).result))}s.push(...c.map(({result:d})=>l.get(d.id)??d))}else s.push(...c.map(({result:l})=>l));for(let l of i)s.push((await go(l,t,n)).result);return s.sort((l,d)=>e.findIndex(u=>u.id===l.id)-e.findIndex(u=>u.id===d.id))}async function go(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),yo(e.scipPath,{force:!0});let r=Cv(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=B();try{let a=Is(e.binary,e.args),c=await Xn({command:a.binary,args:a.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:Iv(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024});if(c.status!==0){let l=c.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${c.status}${l?`:
280
- ${l}`:""}`)}$v(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
281
- `)[0]}`,d=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:B()-o,command:i,skipped:{language:e.language,reason:d}},retryable:Ev(a)}}finally{Pv(r)}if(!$r(e.scipPath)){let a=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?a:`${e.label}: ${a}`;return n(`Skipping ${e.label}: ${a}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:B()-o,command:i,skipped:{language:e.language,reason:c}},retryable:!1}}let s;try{s=kv(e.scipPath).size}catch{s=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:B()-o,command:i,outputBytes:s},retryable:!1}}function Iv(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):nl.indexer}function Ev(e){return e instanceof Qn?e.kind==="spawn"&&Tu(e.cause):Tu(e)}function Tu(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}async function jv(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),s=Array.from({length:o},async()=>{for(;i<e.length;){let a=i++;r[a]=await n(e[a])}});return await Promise.all(s),r}import{execFileSync as Av}from"child_process";import{platform as Lv}from"os";function Cr(e,t){let n=e.installMethods,r=Nn(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n)if(Ye(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Av(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Lv()==="win32"});let o=_n(e);if(o){let s=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${r} via ${i.label}${s}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(o){let s=o instanceof Error?o.message:String(o);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}import TR from"better-sqlite3";import{existsSync as IR}from"fs";import{dirname as ER,join as jR,resolve as AR}from"path";import{randomUUID as Dv}from"crypto";import{mkdtempSync as Fv,readFileSync as Mv,rmSync as Nv,statSync as Au}from"fs";import{tmpdir as _v}from"os";import{join as Lu}from"path";import{Worker as Bv}from"worker_threads";function Ov(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Mt(){return{skippedReferences:0,skippedReferenceReasons:Ov(),skippedReferenceSamples:[]}}function Pr(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}var qv=3e5,Vv=64*1024*1024,Wv={createResultDirectory:()=>Fv(Lu(_v(),"scip-query-vue-workers-")),spawn:(e,t)=>new Bv(e,{workerData:t}),resultSize:e=>Au(e).size,readResult:e=>Mv(e,"utf-8"),removeResultDirectory:e=>Nv(e,{recursive:!0,force:!0})};function Ou(e){return e.length>=8&&Fu(e.length)>1}async function Du(e,t=Wv){let n=Fu(e.vueFiles.length),r=nR(e.vueFiles),i=iR(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),s=e.timeoutMs??eR(),a=e.maxResultBytes??tR();ju("timeoutMs",s),ju("maxResultBytes",a);let c=Dv(),l=t.createResultDirectory(),d=[],u,m,g;try{for(let h=0;h<i.length;h++){let b=h,y=i[h]??[],v=y.map(D=>D.taskId),R=Lu(l,`${b}.json`),T=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:y,resultPath:R,runId:c,workerId:b,taskIds:v});d.push({workerId:b,taskIds:v,resultPath:R,handle:T,completion:Hv(T,b)})}await Uv(d,s);let f=d.sort((h,b)=>h.workerId-b.workerId).map(h=>Jv(h,c,a,t));g={occurrences:f.flatMap(h=>h.occurrences),...Mt()};for(let h of f)Pr(g,h)}catch(f){u=f}finally{let f=await Gv(d);if(f.length===0)try{t.removeResultDirectory(l)}catch(h){f.push(h)}if(f.length>0){let h=u===void 0?f:[u,...f];m=new AggregateError(h,`Vue worker cleanup failed: ${Zv(h[0])}`)}}if(m)throw m;if(u!==void 0)throw u;if(!g)throw new Error("Vue workers completed without producing a merged result.");return g}function Hv(e,t){return new Promise((n,r)=>{let i=!1,o=c=>{i||(i=!0,e.off("error",s),e.off("exit",a),c?r(c):n())},s=c=>{o(new Error(`Vue reference worker ${t} failed: ${c.message}`,{cause:c}))},a=c=>{o(c===0?void 0:new Error(`Vue reference worker ${t} exited with code ${c}`))};e.once("error",s),e.once("exit",a)})}async function Uv(e,t){let n;try{await Promise.race([Promise.all(e.map(r=>r.completion)),new Promise((r,i)=>{n=setTimeout(()=>i(new Error(`Vue reference workers timed out after ${(t/1e3).toFixed(3)}s`)),t),n.unref()})])}finally{n&&clearTimeout(n)}}async function Gv(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function Jv(e,t,n,r){let i=r.resultSize(e.resultPath);if(!Number.isSafeInteger(i)||i<0||i>n)throw new Error(`Vue reference worker ${e.workerId} result is ${i} bytes; limit is ${n} bytes`);let o;try{o=JSON.parse(r.readResult(e.resultPath))}catch(s){throw new Error(`Vue reference worker ${e.workerId} produced invalid JSON`,{cause:s})}if(!hn(o)||o.version!==1||o.runId!==t||o.workerId!==e.workerId)throw new Error(`Vue reference worker ${e.workerId} result identity does not match its assignment`);if(!Yv(o.taskIds,e.taskIds))throw new Error(`Vue reference worker ${e.workerId} result task identities do not match its assignment`);if(o.ok===!1)throw typeof o.error!="string"?new Error(`Vue reference worker ${e.workerId} failure payload is malformed`):new Error(`Vue reference worker ${e.workerId} failed: ${o.error}`);if(o.ok!==!0||!zv(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function zv(e){if(!hn(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(Kv)||!Je(e.skippedReferences)||!hn(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!Je(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(Qv)}function Kv(e){return hn(e)&&typeof e.sourceFile=="string"&&Je(e.sourceLine)&&Je(e.sourceStartChar)&&Je(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&Je(e.symbolId)}function Qv(e){return hn(e)&&typeof e.sourceFile=="string"&&Je(e.sourceLine)&&Je(e.sourceStartChar)&&Je(e.sourceEndChar)&&typeof e.token=="string"&&Xv(e.reason)}function Xv(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function Je(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function hn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yv(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function ju(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function Zv(e){return e instanceof Error?e.message:String(e)}function Fu(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function eR(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:qv}function tR(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:Vv}function nR(e){let t=rR(),n=[];for(let r of e){let i=Mu(r),o=Math.max(1,Math.ceil(i/t));for(let s=0;s<o;s++)n.push({taskId:`${n.length}:${r}:${s}`,fileName:r,startOffset:Math.floor(i*s/o),endOffset:s===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(s+1)/o),countFileSkip:s===0})}return n}function rR(){return Number.POSITIVE_INFINITY}function iR(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:oR(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((s,a)=>a.weight<s.weight?a:s);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function oR(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Mu(e.fileName)-e.startOffset)}function Mu(e){try{return Au(e).size}catch{return 1}}import{createRequire as sR}from"module";import{existsSync as aR,readFileSync as So}from"fs";import{dirname as Nu,extname as cR,join as _u,relative as lR,resolve as dR}from"path";import{pathToFileURL as uR}from"url";function pR(e){e.transaction(()=>{e.prepare(`
282
- DELETE FROM mentions
283
- WHERE chunk_id IN (
284
- SELECT c.id
285
- FROM chunks c
286
- JOIN documents d ON d.id = c.document_id
287
- WHERE d.language = 'vue' OR d.relative_path LIKE '%.vue'
288
- )
289
- `).run(),e.prepare(`
290
- DELETE FROM chunks
291
- WHERE document_id IN (
292
- SELECT id
293
- FROM documents
294
- WHERE language = 'vue' OR relative_path LIKE '%.vue'
295
- )
296
- `).run()})()}function Bu(e,t){return e.prepare(`
297
- SELECT relative_path AS relativePath
298
- FROM documents
299
- WHERE language = 'vue' OR relative_path LIKE '%.vue'
300
- ORDER BY relative_path
301
- `).all().map(r=>dR(t,r.relativePath))}function qu(e,t){let{vueCore:n,ts:r,volarTs:i}=mR(e),{parsed:o,vueOptions:s}=fR(n,r,t),a=Nu(t),c=n.createVueLanguagePlugin(r,o.options,s,g=>g),l=gR(n,r,c),d=hR(a,o),{languageServiceHost:u}=i.createLanguageServiceHost(r,r.sys,l,g=>g,d),m=r.createLanguageService(u);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function mR(e){let t=sR(uR(_u(e,"package.json")).href);return{vueCore:bo(t,"@vue/language-core",e),ts:bo(t,"typescript",e),volarTs:bo(t,"@volar/typescript",e)}}function fR(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,Nu(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function gR(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!aR(o))return;let s=So(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??xR(o))});return r.current=i,i}function hR(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function bo(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function Vu(e,t,n){let r=yR(e);return i=>{if(!i.name)return null;let o=ze(t,i.fileName),s=n.get(i.fileName);if(!s)return null;let a=n.positionAt(s,i.textSpan.start),c=r.get(o);if(!c)return null;let l=c.starts.find(u=>u.line===a.line&&u.displayName===i.name);if(l)return l.symbolId;let d=c.containingByLine.get(a.line);return d&&d.displayName===i.name?d.symbolId:bR(c.starts,a.line,2,i.name)}}function yR(e){let t=e.prepare(`
302
- SELECT
303
- d.relative_path AS relativePath,
304
- der.start_line AS startLine,
305
- der.end_line AS endLine,
306
- der.symbol_id AS symbolId,
307
- gs.display_name AS displayName
308
- FROM defn_enclosing_ranges der
309
- JOIN documents d ON d.id = der.document_id
310
- JOIN global_symbols gs ON gs.id = der.symbol_id
311
- ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
312
- `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function bR(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let a=Math.floor((i+o)/2);e[a].line<t?i=a+1:o=a-1}let s=null;for(let a of[o,i]){let c=e[a];if(!c||c.displayName!==r)continue;let l=Math.abs(c.line-t);l>n||(!s||l<s.distance)&&(s={distance:l,symbolId:c.symbolId})}return s?.symbolId??null}function Wu(e,t,n){let r=$R(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
313
- INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
314
- VALUES (?, ?, ?, ?)
315
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=ze(t,l),u=Yu(r.name,r.version,d);o.run(u,"default",7,`Vue component|${d}`);let m=CR(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Hu(e,t,n,r,i){return e.transaction(()=>(pR(e),SR(e,t,n,r),vR(e,i)))()}function SR(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
316
- INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
317
- VALUES (?, ?, ?, ?, X'00')
318
- `),s=e.prepare(`
319
- INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
320
- VALUES (?, ?, 1)
321
- `);for(let a of n){let c=r.get(a);if(!c)continue;let l=ze(t,a),d=i.get(l);if(!d)continue;let u=o.run(d.id,-1,0,0);s.run(Number(u.lastInsertRowid),c)}}function Uu(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=r.language.maps.get(s,o);if(vo(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Gu(e){let t=new Set,n=[];for(let r of e){let i=Ju(r);t.has(i)||(t.add(i),n.push(r))}return n}function Ju(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function vR(e,t){let n=wR(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
322
- INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
323
- VALUES (?, ?, ?, ?, X'00')
324
- `),i=e.prepare(`
325
- INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
326
- VALUES (?, ?, 0)
327
- `),o=new Set,s=0,a=0;for(let c of t){let l=Ju(c);if(o.has(l))continue;o.add(l);let d=n.get(c.sourceFile);if(!d)continue;let u=r.run(d,a++,c.sourceLine,c.sourceLine),m=i.run(Number(u.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*zu(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function Ku(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function vo(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function RR(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function Qu(e,t){return ze(e,t).startsWith("node_modules/")}function ze(e,t){return lR(e,t).replaceAll("\\","/")}function xR(e){switch(cR(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function Xu(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=So(t,"utf-8"),r={text:n,lineStarts:kR(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:RR}}function kR(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function wR(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.set(a.relativePath,a.id)}return n}function $R(e){try{let t=JSON.parse(So(_u(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function CR(e,t,n,r){let i=ze(n,r),o=Yu(t.name,t.version,i);return e.get(o)?.id??null}function Yu(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}async function ko(e){return Ft(gt(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),LR(e)}async function LR(e){let t=AR(e.projectRoot,e.tsconfig);if(!IR(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new TR(e.dbPath);try{let r=Bu(n,e.projectRoot),i=jR(ER(e.dbPath),"augment-vue-meta.json");return await Zd({cachePath:i,readFingerprint:()=>MR(n,e.projectRoot,e.tsconfig),compute:()=>OR({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}async function OR(e){let t=Wu(e.db,e.projectRoot,e.vueFiles),n=Ou(e.vueFiles)?await Du({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):FR(e,t);return DR(e,t,n)}function DR(e,t,n){let r=Gu(n.occurrences),i=Hu(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:GR(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:UR(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function FR(e,t){let n=NR({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return _R({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function MR(e,t,n){let r=e.prepare(`
328
- SELECT
329
- (SELECT COUNT(*) FROM documents) AS documents,
330
- (SELECT COUNT(*) FROM global_symbols) AS symbols,
331
- (SELECT COUNT(*) FROM chunks) AS chunks,
332
- (SELECT COUNT(*) FROM mentions) AS mentions,
333
- (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
334
- (SELECT MAX(id) FROM chunks) AS maxChunkId,
335
- (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
336
- `).get();return{version:3,tsconfig:n,files:qn(t),db:r}}function NR(e){let t=Xu();return{projectRoot:e.projectRoot,context:qu(e.projectRoot,e.configPath),symbolLookup:Vu(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function _R(e){let t=[],n=Mt(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=BR(e,i);t.push(...o.occurrences),Pr(n,o)}return{occurrences:t,...n}}function BR(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Zu(e.projectRoot,t,"missing-source-file");let r=e.context.language.scripts.get(t.fileName),i=r?.generated?.languagePlugin.typescript?.getServiceScript(r.generated.root)?.code;if(!r||!i)return Zu(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=ze(e.projectRoot,t.fileName),a=[...zu(n.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:zR(a),processedStarts:new Set};return qR({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function qR(e){let t=[],n=Mt();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||VR(e.sourceInfo.text,r.start))continue;let i=Ku(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!Qu(e.projectRoot,d.fileName));if(!s){Ro(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=ze(e.projectRoot,s.fileName),c=WR(e.sourceFile,r.text,a);if(c){Ro(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=Uu(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){Ro(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}ep(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),JR(t,e,r,i,a,l)}return{occurrences:t,...n}}function VR(e,t){let n=e.lastIndexOf(`
337
- `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function WR(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Zu(e,t,n){let r=Mt();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:ze(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Ro(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(a=>a.reason===o&&a.sourceFile===r).length>=2)return;let s=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,token:i.text,reason:o})}function xo(e,t){let n=new Map;for(let o of e){let s=n.get(o.sourceFile)??[];s.push(o),n.set(o.sourceFile,s)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let s=!1;for(let a of r){let c=n.get(a)?.[o];if(c&&(i.push(c),s=!0,i.length===t))break}if(!s)break}return i}function HR(e,t){let n=xo(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=xo(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function UR(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let s=n.length-i,a=Math.ceil((t-r.length)/s);r.push(...xo(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function GR(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return HR(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function JR(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of KR(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(s))continue;let a=t.tokenContext.tokenByStart.get(s);a&&(ep(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function ep(e,t,n,r,i,o,s){let a=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:s})}function zR(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function KR(e,t,n,r,i,o){let s=e.getDocumentHighlights?.(t,n,[t])??[],a=[];for(let c of s)if(c.fileName===t)for(let l of c.highlightSpans){let d=QR(r,l.textSpan.start,o,i.text);d!==null&&a.push(d)}return a}function QR(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=vo(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Bt(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=ix(e),s=Date.now(),a=B();Ir(q(o.outputScip),{recursive:!0}),Ir(q(o.outputDb),{recursive:!0});let c=e.languages??lt(t);if(c.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${c.join(", ")}`);let l=zt("reindex.fingerprint",()=>qs(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:c.length}),d,u;if(e.skipIfUnchanged!==!1&&!Xc(t,o.outputDb)&&tp(o.outputScip)===tp(re(q(o.outputDb),"index.scip"))){let h=at(t);if(d=h?zn(h,l):void 0,d){let b=Kn(d);if(b){if(!rx(o,l))try{hi({snapshot:d,manifest:b,targetCacheDir:q(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${d.generationId.slice(0,12)}`)}catch(y){r(`Shared generation attach failed; continuing locally: ${_t(y)}`)}}else{let y=await el(d);if(y.kind==="owner")u=y.release;else if(y.kind==="generation-ready"){let v=Kn(d);if(v)try{hi({snapshot:d,manifest:v,targetCacheDir:q(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${d.generationId.slice(0,12)} after waiting`)}catch(R){r(`Shared generation attach failed after waiting; continuing locally: ${_t(R)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let m=Nc(re(q(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!m)throw u?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${q(o.outputDb)}.`);let g;try{g=await Kt("reindex.lock",()=>jx(re(q(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:c.length})}catch(h){throw m.release(),u?.(),h}let f=null;try{Fc(o.outputDb,o.outputScip,o.metaPath);let h=cx(q(o.outputDb));h.removed>0&&r(`Removed ${h.removed} abandoned reindex workspace(s)`);for(let D of h.errors)r(`Could not remove abandoned reindex workspace: ${D}`);let b=null,y=zt("reindex.reuse-check",()=>(b=ox({opts:e,paths:o,languages:c,fingerprint:l,start:s,monotonicStart:a,onStatus:r}),b),()=>({languages:c.length,reused:b!==null}));if(y)return np({snapshot:d,paths:o,projectRoot:t,fingerprint:l,onStatus:r}),ro(o.outputDb,y),y;await Kt("reindex.scip-cli-ready",()=>kx(i,r));let v=ax(o);f=v.runDir;let R,T=await Kt("reindex.fresh",async()=>(R=await lx({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:v,fingerprint:l,start:s,monotonicStart:a,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),R),()=>({languages:c.length,reused:R?.reused,skipped:R?.skipped.length}));return np({snapshot:d,paths:o,projectRoot:t,fingerprint:l,onStatus:r}),ro(o.outputDb,T),T}catch(h){let b=Lr({trigger:e.trigger,result:"failed",start:s,monotonicStart:a,error:h instanceof Error?h.message:String(h)});throw kp(o.metaPath,b),tu(o.outputDb,b),h}finally{f&&Nt(f,{recursive:!0,force:!0}),g(),m.release(),u?.()}}function np(e){if(e.snapshot){if(Kn(e.snapshot)){yi(e.snapshot,q(e.paths.outputDb),"local-fresh");return}try{let t=at(e.projectRoot),n=t?zn(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}Zc({snapshot:e.snapshot,sourceCacheDir:q(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=at(e.projectRoot);return(r?zn(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),yi(e.snapshot,q(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${_t(t)}`)}}}function rx(e,t){if(!Ce(e.outputScip)||!Ce(e.outputDb)||!xp(e.metaPath,t))return!1;let n=dt(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function _t(e){return e instanceof Error?e.message:String(e)}function ix(e){let t=e.outputScip??re(e.projectRoot,"index.scip"),n=e.outputDb??re(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:re(q(n),"meta.json")}}function ox(e){let t=dt(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!Ce(e.paths.outputScip)||!Ce(e.paths.outputDb)||!xp(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;Ft(gt(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=B()-e.monotonicStart,r=Lr({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return kp(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:sx(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function sx(e,t,n,r){let i=vp(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:yn(i[o]),outputBytes:bn(To(e.outputDb,o)),durationMs:0}))}function ax(e){let t=ZR(re(q(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:re(t,Tr(e.outputScip)),tempOutputDb:re(t,Tr(e.outputDb)),tempMetaPath:re(t,Tr(e.metaPath))}}function cx(e){let t=[],n;try{n=lp(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[_t(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{Nt(re(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${_t(o)}`)}return{removed:r,errors:t}}async function lx(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await Kt("reindex.language-indexers",async()=>(n=await ux(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:s,languageFingerprints:a,shards:c,typescriptProjectShardContext:l,incrementalTypeScript:d}=r;if(s.length>0&&e.onStatus(`Reused ${s.length} cached language shard(s): ${s.join(", ")}`),dx({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let g=zt("reindex.publish",()=>vx(e,i,o,s,a,l),{mode:"metadata-only",languages:i.length,reused:s.length}),f=g.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(f/1e3).toFixed(1)}s`),{languages:i.map(h=>h.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:f,reused:!0,skipped:o,lastRefresh:g,shards:c}}let u=zt("reindex.publish",()=>Sx(e,t,i,o,s,a,l,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:s.length,skipped:o.length}),m=u.durationMs;return e.onStatus(`Done in ${(m/1e3).toFixed(1)}s`),{languages:i.map(g=>g.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:u,shards:c}}function dx(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!Ce(e.run.paths.outputScip)||!Ce(e.run.paths.outputDb))return!1;let t=dt(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function ux(e,t){let n=hx({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[M,K]of n)K.reused&&(r.push({language:M,scipPath:K.scipPath}),i.add(M));for(let M of i)e.onStatus(`Reusing cached ${M} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),s=dt(e.paths.outputDb,e.paths.metaPath),a=vn(e.paths.metaPath),c=s.state==="legacy"||s.state==="current",l=a?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?Cu({projectRoot:e.projectRoot,cacheDir:q(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Sn(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Sn(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:Po(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,u=new Set(d?["typescript"]:[]),m=d?void 0:px(e,n),{preparedRuns:g,skippedLanguages:f,languageOutputScipPaths:h}=wx({languages:e.languages.filter(M=>!i.has(M)&&!u.has(M)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:m?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),b=m?g.filter(M=>M.language!=="typescript"||m.missedProjectIds.has(M.id)):g,y=await Eu(b,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),v=[];if(m){fx(e.paths.outputDb,y);let M=h.typescript??e.tempPaths.tempOutputScip;v=gx({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:M,reusedProjects:m.reusedProjects})}let R=[...y,...v],{indexedOutputs:T}=Cx(R,f),D=d?[{language:"typescript",scipPath:d.scipPath}]:[],C=[...r,...D,...T];Px(C,f,e.languages,e.opts.allowPartial,e.onStatus);let U=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:bn(d.scipPath)??void 0}]:[],j=yx(n,[...y,...U],m?{outputDb:e.paths.outputDb,classification:m.classification}:void 0);return{indexedOutputs:C,skippedLanguages:f,reusedLanguages:[...i],languageFingerprints:bx(n,e.languages),shards:j,typescriptProjectShardContext:m?{projects:m.allProjects,fingerprints:m.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function px(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=gn(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=au(e.projectRoot,r),o=iu(n.fingerprint.files,r),s=ou(r,i),a=su(r,o,s),c=vn(e.paths.metaPath),d=mx(c,a,f=>Ce(Ar(e.paths.outputDb,f))),u=[...d.entries()].filter(([,f])=>f.reused).map(([f])=>f),m=new Set(u),g=new Set(r.filter(f=>!m.has(f)).map(f=>`typescript:${f}`));return{allProjects:r,fingerprints:a,classification:d,reusedProjects:u,missedProjectIds:g}}function mx(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let s=e.version===Jt&&si(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[i]:void 0;if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(Ke(s)!==Ke(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function fx(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=Ar(e,r);Ir(q(i),{recursive:!0}),jr(n.scipPath,i)}}function gx(e){return e.reusedProjects.map((t,n)=>{let r=Ar(e.outputDb,t),i=Sn(e.tempOutputScip,"typescript-project-cached",n);return jr(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:bn(i)??void 0}})}function hx(e){let t=vn(e.paths.metaPath),n=vp(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=To(e.paths.outputDb,i),s=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:s,scipPath:o});continue}if(t.version!==Jt){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:s,scipPath:o});continue}if(!si(t).languageShardReuse||!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:o});continue}let a=t.languageFingerprints[i];if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:o});continue}if(!Ce(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}if(Ke(a)!==Ke(s)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:s,scipPath:o})}return r}function yx(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:yn(o.fingerprint),outputBytes:bn(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),s=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,a=s?n.classification.get(s):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:a?.reason??o?.reason??i.skipped?.reason,fingerprint:a?yn(a.fingerprint):o?yn(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:yn(o.fingerprint),outputBytes:bn(Ar(n.outputDb,i)),durationMs:0});return r}function yn(e){return YR("sha256").update(Ke(e)).digest("hex").slice(0,16)}function bn(e){try{return ex(e).size}catch{return null}}function bx(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Sx(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(rp(e.paths.outputDb,n),l=ip(n,e.tempPaths.tempOutputScip,e.onStatus));let d=Tx({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:a,completeScipAvailable:c,completeScipSanitized:l,materializeFullFallback:()=>{if(!a||a.completeScipUpdated)return l;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Pu({cacheDir:q(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let v=n.map(R=>R.language==="typescript"?{language:R.language,scipPath:a.candidateScipPath}:R);return rp(e.paths.outputDb,v),l=ip(v,e.tempPaths.tempOutputScip,e.onStatus),l}});if(Ft(gt(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&a){let v=null,R=null;try{v=new Be({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),R=new Be({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let T=Ys(v,e.fingerprint,a.referenceFragmentsByFile,R);e.onStatus(`Cached exact TypeScript reference fragments for ${T} affected document(s).`)}catch(T){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${T instanceof Error?T.message:String(T)}.`)}finally{v?.close(),R?.close()}}let u=Po(e.paths.metaPath),m=d.mode==="incremental"&&a?Ex(a,d.changedDocumentPaths):Yi({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:u,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),g=Lr({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(v=>v.language),skipped:[...r]}),f=d.mode==="incremental"&&d.scipCompanion==="deferred",h={...o};f&&delete h.typescript;let{metadata:b,pruneProjects:y}=pp({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:h,typescriptProjectShardContext:s,lastRefresh:g});return b.scipCompanion=f?"deferred":"current",mp(e.paths.outputDb,y),Io(e.tempPaths.tempMetaPath,b),Dc({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:a?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:a?.timings.serviceMs,materializationDurationMs:a?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&a?{typescriptOverlayGeneration:a.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}}),Jc(q(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),up(e.paths.outputDb,m,e.onStatus),g}function vx(e,t,n,r,i,o){let s=Po(e.paths.metaPath),a=null;try{jr(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(u){a=_d("reused","oracle-error",`Could not snapshot the prior database: ${u instanceof Error?u.message:String(u)}`)}Ft(gt(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),a??=Yi({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:s,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=Lr({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(u=>u.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=pp({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return mp(e.paths.outputDb,d),Io(e.paths.metaPath,l),Mc(e.paths.outputDb,e.paths.metaPath),up(e.paths.outputDb,a,e.onStatus),c}function Po(e){return fs(vn(e)?.fingerprint)}function up(e,t,n){try{Wd(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function pp(e){let t=Rx({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:Jt,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function Rx(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=vn(e.metaPath),n=t?.version===Jt?t.typescriptProjectShards:void 0;return{field:n,pruneProjects:n?Object.keys(n):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function mp(e,t){let n=Rp(e);if(t===null){Nt(n,{recursive:!0,force:!0});return}let r;try{r=lp(n)}catch{return}for(let i of xx(r,t))Nt(re(n,i),{force:!0})}function xx(e,t){let n=new Set(t.map(r=>`${co(r)}.scip`));return e.filter(r=>!n.has(r))}function rp(e,t){for(let n of t){let r=To(e,n.language);Ir(q(r),{recursive:!0}),n.scipPath!==r&&jr(n.scipPath,r)}}async function kx(e,t){if(!mr()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
338
- Install from: https://github.com/sourcegraph/scip/releases`);if(nx()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall with optional dependencies enabled, run 'npm install -g scip-query-scip-windows', or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(t("scip CLI not found on PATH. Attempting auto-install..."),!Pd(t))throw new Error(`The scip CLI is required but could not be installed.
339
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function wx(e){let t=[],n=[],r=e.languages.map((o,s)=>({language:o,scipPath:e.languages.length>1?Sn(e.tempOutputScip,o,s):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:o,scipPath:s})=>[o,s]));for(let{language:o,scipPath:s}of r){let a=$x({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?fp(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function $x(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[wo({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??gn(e.projectRoot,e.typescriptProjects);return t.length===0?[wo({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,r)=>wo({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Sn(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function wo(e){let t=pt(e.language),n=Nn(t),r=js(t,e.projectRoot);if(!r&&!Es(t)){if(e.skipAutoInstall){let a=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Cr(t,e.onStatus)){let a=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}}let i=r??_n(t);if(!i){let a=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}let{binary:o,args:s}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:i,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});return{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:i,binary:o,args:s,env:As(t,e.env,i)}}}function Cx(e,t){let n=new Map;for(let i of e)if(i.skipped)fp(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`,s=n.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};s.scipPaths.push(i.scipPath),n.set(o,s)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)Kc(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&dp(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function fp(e,t){let n=e.find(r=>r.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function Px(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
340
- `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
341
- `+o)}if(t.length!==0&&(i(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(o=>o.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
342
- `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
343
- `))}function ip(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Qc(e.map(o=>o.scipPath),t);return hp(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&dp(e[0].scipPath,t);return!1}function Tx(e){let t;if(Ix(e)){let i=re(e.run.tempPaths.runDir,"typescript-affected.db");try{gp(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();op(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let s=Qd({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${s.affectedDocumentCount} SQLite document(s) in ${(s.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:s.changedDocumentPaths,patchDurationMs:s.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){t=o instanceof Error?o.message:String(o),Nt(i,{force:!0}),Nt(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}}let n=e.completeScipSanitized;e.completeScipAvailable||(n=e.materializeFullFallback());let r=performance.now();return op(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Ix(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!Ce(e.run.paths.outputDb)||!Ce(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function Ex(e,t){let n=B(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(s=>!i.has(s)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:B()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:Xi(e.plan,o,e.projectFileCount)}}function op(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!Ce(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||gp(e,r);let o=mr();if(!o)throw new Error("scip CLI is not available");XR(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024,timeout:3e5,killSignal:"SIGKILL"})}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:o})}}function gp(e,t){let n=zc(e);hp(n,t)}function hp(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Sn(e,t,n){let r=tx(e)||".scip",i=Tr(e,r);return re(q(e),`${i}.${n+1}.${t}${r}`)}async function jx(e,t){for(let n=0;n<2;n++){let r=Ax(e,t);if(r)return r;let i=Lx(e);if(i&&Sp(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await Dx(i)}catch(a){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${i.pid}); refusing to steal an active lock: ${_t(a)}`,{cause:a})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${q(e)}; refusing to steal an active lock.`);let s=gi(e,{parseLegacy:Er});if(!jc(e,s,{parseLegacy:Er}))throw new Error(`Reindex lock ownership changed before preemption completed for ${q(e)}.`);continue}throw new Error(`Another scip-query reindex is already running for ${q(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${q(e)}.`)}function Ax(e,t){let n=kt(process.pid),r=Jn(e,{kind:"reindex",processIdentity:n,detail:{projectRoot:t.projectRoot,...process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1"?{processGroupLeader:!0}:{},...t.trigger?{trigger:t.trigger}:{}},parseLegacy:Er});if(r.kind==="acquired"&&r.reclaimed){let i=yp(r.reclaimed,e);i&&Sp(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${q(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function Lx(e){return yp(gi(e,{parseLegacy:Er}),e)}var Er=e=>{let t=bp(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function yp(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:q(t),startedAt:e.record.startedAt,trigger:n.trigger}}return bp(e.parsed,t)}function bp(e,t){try{let n=e;return typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0?null:{version:n.version===2?2:1,pid:n.pid,...n.processIdentity===void 0?{}:(()=>{let r=Os(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:q(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function Sp(e,t){return e?.kind==="manual-cli"&&Ox(t?.trigger)}function Ox(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function Dx(e){return!xt(e.pid)||($o(e),sp(e,"SIGTERM"),await ap(e,2e3))?!0:($o(e),sp(e,"SIGKILL"),ap(e,1e3))}function sp(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!xt(e.pid))return;$o(e)}try{process.kill(e.pid,t)}catch{}}async function ap(e,t){let n=B()+t;for(;B()<n;){if(cp(e))return!0;await Fx(50)}return cp(e)}function $o(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=kt(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!Yt(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function cp(e){if(!xt(e.pid))return!0;if(!e.processIdentity)return!1;let t=kt(e.pid);return t!==null&&!Yt(e.processIdentity,t)}function Fx(e){return new Promise(t=>setTimeout(t,e))}function vp(e,t,n){return Object.fromEntries(t.map(r=>{let i=pt(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Bs(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=r==="clojure"?Mx(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Nx(n),...o,clojureConfigPath:s,files:qn(e,{language:r,markerFiles:i})}]}))}function Mx(e){return e?.trim()||void 0}function Nx(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function To(e,t){return re(q(e),"language-indexes",`${t}.scip`)}function Rp(e){return re(q(e),"language-indexes","typescript-projects")}function Ar(e,t){return re(Rp(e),`${co(t)}.scip`)}function vn(e){try{return oi(vt(Co(e,"utf-8")))}catch{return null}}function xp(e,t){try{let n=vt(Co(e,"utf-8"));if(n.kind!=="legacy"&&n.kind!=="supported")return!1;let r=n.metadata;return n.capabilities.publishableGeneration&&Ke(r.fingerprint)===Ke(t)&&Ke([...r.indexedLanguages??[]].sort())===Ke(t.languages)}catch{return!1}}function Io(e,t){Ms(e,t,{spacing:2,trailingNewline:!0})}function kp(e,t){try{let n=oi(vt(Co(e,"utf-8")));if(!n)return;Io(e,{...n,lastRefresh:t})}catch{}}function Lr(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:B()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function Ke(e){return JSON.stringify(e)}var Eo=864e5;function wp(e,t={}){let r=[...t.check?e.filter(l=>l.check===t.check):[...e]].sort((l,d)=>l.ts-d.ts),i=new Map;for(let l of r){let d=`${l.check}\0${l.findingId}`,u=i.get(d);u||(u={check:l.check,findingId:l.findingId,caughtAt:l.ts,events:[]},i.set(d,u)),u.events.push(l)}let o=[...i.values()].filter(l=>t.sinceMs===void 0||l.caughtAt>=t.sinceMs),s=_x(r),a=new Map;for(let l of o){let d=a.get(l.check)??[];d.push(l),a.set(l.check,d)}let c=[];for(let[l,d]of a){let u=0,m=0,g=0,f=0,h=0,b=0,y=[];for(let R of d){g+=R.events.filter(C=>C.event==="reopened").length;let T=R.events[R.events.length-1],D=`${R.check}\0${R.findingId}`;if(T.event==="resolved"&&s.has(D))f+=1;else if(T.event==="resolved"){let C=nn(R.events.slice(0,-1)),U=C?.comparisonBaseCommit??C?.commit,j=T.comparisonBaseCommit??T.commit;U&&(j===U||T.verifiedAgainstCommit===U)?(u+=1,y.push((T.ts-R.caughtAt)/Eo)):h+=1}else T.event==="suppressed"?m+=1:b+=1}let v=u+m;c.push({check:l,caught:d.length,fixed:u,suppressed:m,reopened:g,moved:f,unverified:h,open:b,precision:v>0?u/v:null,medianDaysToFix:y.length>0?Bx(y):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,d)=>l.check.localeCompare(d.check))}}function _x(e){let t=new Map;for(let i of e){if(i.event!=="caught"||!i.commit||!i.symbol)continue;let o=t.get(i.commit)??[];o.push(i),t.set(i.commit,o)}let n=new Map;for(let i of e)i.event==="caught"&&i.symbol&&n.set(`${i.check}\0${i.findingId}`,i.symbol);let r=new Set;for(let i of e){if(i.event!=="resolved"||!i.commit)continue;let o=`${i.check}\0${i.findingId}`,s=i.symbol??n.get(o);if(!s)continue;(t.get(i.commit)??[]).some(c=>c.check===i.check&&c.symbol===s&&c.findingId!==i.findingId)&&r.add(o)}return r}function $p(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*Eo:Eo;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function Bx(e){let t=[...e].sort((r,i)=>r-i),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}import{statSync as qx}from"fs";import{basename as Vx,isAbsolute as Wx,join as Hx,relative as Ux}from"path";import{watch as Gx}from"chokidar";import Jx from"ignore";var Or=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Ee(t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onReindexError=t.onReindexError??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.clock=t.clock??Kx,this.reindexRunner=t.reindexRunner??tk(),this.subscriptionFactory=t.subscriptionFactory??Qx,this.gitignoreFilter=Ct(t.projectRoot),this.extraIgnore=Jx(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let t=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer();let n=this.activeOperation;return n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"}),this.stopPromise=this.finishStop(t,n).finally(()=>{this.stopInProgress=!1}),this.stopPromise}requestRefresh(t,n={}){if(!this.stopped){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=Pp(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(r,i)=>this.isIgnoredWatchPath(r,i?.isDirectory()??!1),usePolling:t,...t?{interval:500,binaryInterval:1e3}:{}});n.on("all",(r,i)=>{this.stopped||this.handleFileChange(i)}),n.on("error",r=>this.handleSourceWatcherError(n,r,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,r){if(r||this.sourcePollingFallbackStarted||!nk(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==t),t.close();try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(t,n){let r=this.relativeWatchPath(t);if(!r)return!1;let i=n?`${r}/`:r;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(t){let n=this.relativeWatchPath(t);!n||n===".."||n.startsWith("../")||n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||n.endsWith("index.db")||n.endsWith("index.scip")||n.endsWith("index.db.tmp")||Vx(n).startsWith(to)||this.scheduleReindex({kind:"watch-source",detail:n})}relativeWatchPath(t){let n=Wx(t)?t:Hx(this.projectRoot,t);return Ux(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=Pp(this.pendingTrigger,t),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let n=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let o=this.watchConfig.cooldownMs-t;this.dirty=!0;let s=this.wallNow()+o;this.setStatus({state:"cooldown",until:s,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},o);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=this.wallNow();this.setStatus({state:"indexing",startedAt:r});let i=this.reindexRunner.start(this.reindexRequest(n));this.activeOperation=i,i.completion.then(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let s=!1;try{s=this.onReindexComplete(o,n)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(s){let c=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(c),this.setStatus({state:"idle"});return}let a=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let s=o instanceof Error?o:new Error(String(o));this.onReindexError(s,n),this.onError(s),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===i&&(this.activeOperation=null)})}async finishStop(t,n){let r=[],i=n?n.cancel():null,o=await Promise.allSettled(t.map(s=>Promise.resolve().then(()=>s.close())));for(let s of o)s.status==="rejected"&&r.push(`watch subscription close failed: ${String(s.reason)}`);if(i)try{let s=await i;s.state==="degraded"&&r.push(s.reason)}catch(s){r.push(`reindex cancellation failed: ${s instanceof Error?s.message:String(s)}`)}return r.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:r.join("; ")}),{state:"degraded",reasons:r}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}reindexRequest(t){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:t}}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let t=this.lastGitState,n=this.readGitState();if(!t||!n||this.stopped){this.lastGitState=n;return}this.lastGitState=n;let r=t.head!==n.head,i=t.indexPath!==n.indexPath||t.indexMtimeMs!==n.indexMtimeMs||t.indexSize!==n.indexSize;r&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):r?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:n.indexPath??"index changed"})}readGitState(){let t=Zt(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n=Hs(this.projectRoot,t),r={head:Zt(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let i=qx(n);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function zx(e){let{projectRoot:t,config:n,languages:r,pnpmWorkspaces:i,typescriptProjectMode:o,typescriptProjects:s,clojureConfigPath:a,indexerConcurrency:c,trigger:l}=e,d=be(t),u=Object.keys(d).length>0?d:n,m=_e(t,u),g=u.indexer?.typescript,f=u.indexer?.clojure;return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:t,SCIP_REINDEX_OUTPUT_SCIP:m.indexPath,SCIP_REINDEX_OUTPUT_DB:m.dbPath,SCIP_REINDEX_LANGUAGES:(u.languages??r)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(u.indexerConcurrency??c??""),SCIP_REINDEX_PNPM_WORKSPACES:g?.pnpmWorkspaces??i?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:g?.projectMode??o,projects:g?.projects??s??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:f?.configPath??a??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1"}}}var Kx={now:B,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Qx=(e,t)=>Gx(e,t),Xx=15*6e4,Yx=1e3,Zx=64*1024;function ek(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function Cp(e,t){let n=e instanceof Error?e.message:String(e),r=t.stderrTail.trim()||t.stdoutTail.trim();return r?`${n}
344
- ${r}`:n}function tk(e={}){let t=e.timeoutMs??Xx,n=e.terminationGraceMs??Yx,r=e.maxOutputBytes??Zx,i=e.resolveLaunch??zx;return{start(o){let s=i(o),a=new AbortController,c=ek(),l=!1,d=Xn({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:r,maxStderrBytes:r,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(u=>{if(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0)throw new Error(Cp(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c));return u.durationMs}).catch(u=>{throw u instanceof Qn&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(Cp(u,c),{cause:u})}).finally(()=>{l=!0});return{completion:d,async cancel(){l||a.abort();try{await d}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Pp(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}function nk(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}import{existsSync as wk}from"fs";import{existsSync as Ip,mkdirSync as Ep,readFileSync as jp,writeFileSync as Ap}from"fs";import{homedir as rk}from"os";import{dirname as Lp,isAbsolute as ik,join as jo,relative as Tp,resolve as ok}from"path";function Op(e,t={}){let n=t.dossierDir?ok(e.projectRoot,t.dossierDir):jo(e.projectRoot,"docs","scip-query"),r={markdownPath:jo(n,"health-dossier.md"),jsonPath:jo(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=fk({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return uk(r.markdownPath,sk(i),r),pk(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function sk(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${Lo(e.health)}`,"","## Items That Need Attention","",...ak(e),"","## Blocked Or Unavailable Checks","",...ck(e),"","## Setup Smoke Tests","",...e.smokeTests.map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),"","## Setup Steps","",...e.steps.map(n=>`- ${n.status.toUpperCase()} ${n.label}${n.message?`: ${n.message}`:""}`),"","## Indexer Remediation","",...lk(e),"","## JSON","",`Machine-readable report: \`${dk(e)}\``,""].join(`
345
- `)}`}function ak(e){return e.health.issuesNeedAttention.length===0?["No prioritized health actions were reported."]:e.health.issuesNeedAttention.map(t=>`- ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort}, evidence ${t.evidence}; confirmation ${t.confirmationStatus}; safe to start ${t.safeForAgentToStart?"yes":"no"}). ${t.recommendedNextStep}`)}function ck(e){let t=[...e.smokeTests.filter(n=>n.status!=="pass").map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),...e.indexerRemediation.filter(n=>!n.after.runnable).map(n=>`- BLOCKED ${n.language}: ${n.recovery??`Install ${n.binaryLabel}.`}`)];return t.length>0?t:["No blocked or unavailable setup checks were reported."]}function lk(e){return e.indexerRemediation.length===0?["All detected indexers were already runnable."]:e.indexerRemediation.map(t=>{let n=t.after.runnable?"READY":"BLOCKED",r=t.attempted?"install attempted":"no automatic install attempted";return`- ${n} ${t.language}: ${t.binaryLabel} (${r})`})}function Lo(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function dk(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function uk(e,t,n){if(Ep(Lp(e),{recursive:!0}),(Ip(e)?jp(e,"utf-8"):null)===t){n.unchanged.push(e);return}Ap(e,t),n.written.push(e)}function pk(e,t,n){Ep(Lp(e),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
346
- `,i=Ip(e)?jp(e,"utf-8"):null;if(i&&mk(i,r)){n.unchanged.push(e);return}Ap(e,r),n.written.push(e)}function mk(e,t){try{let n=JSON.parse(e),r=JSON.parse(t);return delete n.generatedAt,delete r.generatedAt,JSON.stringify(n)===JSON.stringify(r)}catch{return e===t}}function fk(e,t){return Ao(e,t)}function Ao(e,t){return typeof e=="string"?gk(e,t):Array.isArray(e)?e.map(n=>Ao(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Ao(r,t)])):e}function gk(e,t){if(e===t)return".";if(!ik(e))return e;let n=Tp(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=Tp(rk(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as hk}from"child_process";import{readFileSync as Fp}from"fs";import{dirname as Dp,join as yk,resolve as bk}from"path";import{fileURLToPath as Sk}from"url";var Dr={typescript:{ast:"typescript",packages:["tree-sitter-typescript"]},javascript:{ast:"javascript",packages:["tree-sitter-javascript"]},java:{ast:"java",packages:["tree-sitter-java"]},scala:{ast:"scala",packages:["tree-sitter-scala"]},kotlin:{ast:"kotlin",packages:["tree-sitter-kotlin"]},rust:{ast:"rust",packages:["tree-sitter-rust"]},python:{ast:"python",packages:["tree-sitter-python"]},ruby:{ast:"ruby",packages:["tree-sitter-ruby"]},cpp:{ast:"cpp",packages:["tree-sitter-cpp"]},c:{ast:"c",packages:["tree-sitter-c"]},csharp:{ast:"csharp",packages:["tree-sitter-c-sharp"]},php:{ast:"php",packages:["tree-sitter-php"]}};function vk(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of Dr[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function Oo(e){return[...new Set(e.filter(t=>Dr[t]!==void 0))].sort()}function Mp(e,t={}){let n=t.runtime??kk,r=t.packageRoot??Rk(),i=Oo(e),o=i.filter(u=>n.probe(Dr[u].ast)),s=i.filter(u=>!o.includes(u));if(s.length===0)return{supportedLanguages:i,availableBefore:o,installed:[],availableAfter:o,unavailable:[],attempted:!1};let a=xk(r),c=vk(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let d=i.filter(u=>n.probe(Dr[u].ast));return{supportedLanguages:i,availableBefore:o,installed:l.ok?c:[],availableAfter:d,unavailable:i.filter(u=>!d.includes(u)),attempted:!0,...l.error?{error:l.error}:{}}}function Rk(){let e=Dp(Sk(import.meta.url));for(;;){let t=yk(e,"package.json");try{if(JSON.parse(Fp(t,"utf8")).name==="scip-query")return e}catch{}let n=Dp(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function xk(e){return JSON.parse(Fp(bk(e,"package.json"),"utf8")).optionalDependencies??{}}var kk={probe:e=>On(e)==="ast",resetProbe:bs,install:(e,t)=>{let n=hk(process.env.npm_execpath?process.execPath:"npm",[...process.env.npm_execpath?[process.env.npm_execpath]:[],"install","--no-save","--no-package-lock","--include=optional",...t],{cwd:e,encoding:"utf8",timeout:3e5,killSignal:"SIGKILL",maxBuffer:10485760});return n.status===0?{ok:!0}:{ok:!1,error:(n.stderr||n.stdout||n.error?.message||"npm install failed").trim()}}};function Bp(e){let t=[];e.watchEnabled||t.push({id:"enable-automatic-refresh",scope:"repository",label:"Enable automatic incremental indexing",recommended:!0,requiresConsent:!0,reason:"A demand-started project service keeps indexes current and exits after a clean idle period.",command:"scip-query setup"}),e.files.agentsMd||e.files.claudeMd?t.push({id:"update-agent-guidance",scope:"repository",label:"Update project agent guidance",recommended:!0,requiresConsent:!0,reason:"Existing AGENTS.md or CLAUDE.md guidance can be updated in place.",command:"scip-query setup-agent"}):t.push({id:"create-agent-guidance",scope:"repository",label:"Create project agent guidance",recommended:!1,requiresConsent:!0,reason:"No AGENTS.md or CLAUDE.md file exists, so setup should ask before creating one.",command:"scip-query setup-agent"}),(!e.files.codexHooks||!e.files.claudeSettings)&&t.push({id:"install-project-hooks",scope:"checkout",label:"Install project agent hooks",recommended:!0,requiresConsent:!0,reason:"Project hooks help agents check freshness and route through scip-query before editing.",command:"scip-query setup-hooks"});let n=e.readiness.indexers.filter(r=>!r.runnable);return n.length>0&&t.push({id:"install-indexers",scope:"user",label:"Install missing language indexers",recommended:!0,requiresConsent:!0,reason:`${n.length} detected language indexer(s) are not runnable.`,command:"scip-query setup"}),{actions:t}}async function qp(e={}){let t=[],n=qe(),{projectRoot:r,paths:i,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?Lc(r,n.config,e.languages):null,c=a?.config??n.config,l=Pt(c,{projectRoot:r}),d=l.filter(L=>L.level==="error"),u=null,m=null;if(d.length===0&&c.watch?.enabled!==s)try{u=Oc(r,c,s)}catch(L){m=qt(L)}let g=u?.config??c,f=pn();_(t,{id:"automatic-indexing-config",label:"Automatic indexing config",status:m!==null?"failed":d.length>0||!s?"skipped":"ok",message:m??(d.length>0?"Skipped because the existing project config has validation errors.":s?u?.changed?"Enabled demand-started automatic incremental indexing for this project.":"Demand-started automatic incremental indexing is already enabled.":"Automatic incremental indexing remains explicitly disabled for this project."),...u?{details:[u.configPath]}:{}}),_(t,{id:"scip-cli",label:"scip CLI",status:f?"ok":"warn",message:f?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let h=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:yr({quiet:!0});_(t,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":h.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${h.installed.length} installed, ${h.alreadyLinked.length} already linked, ${h.pruned.length} pruned, ${h.skipped.length} skipped.`,details:[...h.pruned.map(L=>`Pruned ${L}`),...h.skipped.map(L=>`Skipped ${L}`)]});let b=u?Pt(g,{projectRoot:r}):l,y=b.filter(L=>L.level==="error");_(t,{id:"config",label:"Project config",status:y.length>0?"failed":b.length>0?"warn":"ok",message:b.length===0?"Config OK.":`${b.length} diagnostic(s), ${y.length} error(s).`,details:b.map(L=>`${L.level.toUpperCase()} ${L.path}: ${L.message}`)});let v=ve(r,g);_(t,{id:"readiness",label:"Indexer readiness",status:v.languages.length===0?"failed":v.indexers.some(L=>!L.runnable)?"warn":"ok",message:v.languages.length===0?"No supported project languages detected.":`Detected languages: ${v.languages.join(", ")}`,details:v.indexers.map(L=>`${L.runnable?"OK":L.installed?"WARN":"MISSING"} ${L.language}: ${L.binaryLabel}${L.note?` - ${L.note}`:""}`)});let R=e.installAstParsers===!1?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:Mp(v.languages);_(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers===!1?"skipped":R.unavailable.length>0?"warn":"ok",message:e.installAstParsers===!1?"Skipped by setup choice.":R.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${R.availableAfter.length}/${R.supportedLanguages.length} selected language parser(s) available${R.installed.length>0?`; installed ${R.installed.join(", ")}`:""}.`,details:[...R.unavailable.length>0?[`Unavailable: ${R.unavailable.join(", ")}`]:[],...R.error?[R.error]:[]]});let T=e.installIndexers??!0,D=T?Dk(r,v,t):[];T||_(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped by guided setup choice."});let C=ve(r,g),U=await $k({projectRoot:r,paths:i,config:g,readiness:C,configHasErrors:y.length>0,steps:t,onStatus:e.onStatus}),j=U.reindexResult,M=U.freshness,K=Ee(g),N=Ck({projectRoot:r,cacheDir:i.cacheDir,watchConfig:K,readiness:C,configHasErrors:y.length>0,reindexResult:j,postReindexFreshness:M,steps:t}),G=ve(r,g),In=tt(G),us=je(r,g,i);_(t,{id:"capabilities",label:"Capability matrix",status:qk(In),message:Vk(In)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let ps=e.runHealth===!1?Nk(t):await Mk(i.dbPath,t),Te=G.languages.includes("rust")?Vn(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;_(t,{id:"rust-semantic-session",label:"Rust semantic session",status:Te===null?"skipped":Te.valid?"ok":"failed",message:Te===null?"Skipped because Rust was not detected.":`${Te.transport}/${Te.state} selected from ${Te.source}; ${Te.fallback} fallback; opt out with ${Te.optOut}.`});let ie=null;try{e.noHooks?_(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(ie=Dt(r),_(t,{id:"project-hooks",label:"Project agent hooks",status:ie.skipped.length>0?"warn":"ok",message:`${ie.installed.length} installed, ${ie.updated.length} updated, ${ie.unchanged.length} already configured, ${ie.removed.length} hook config(s) cleaned up, ${ie.skipped.length} skipped.`,details:[...ie.gitExcluded.map(L=>`Checkout-local Git exclude: ${L}`),...ie.removed.map(L=>`Removed ${L}`),...ie.skipped.map(L=>`Skipped ${L.target}: ${L.reason}`),...ie.warnings]}))}catch(L){_(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:qt(L)})}let xe=null;try{e.noAgentGuidance?_(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(xe=ir(r,{gitHook:e.gitHook}),_(t,{id:"agent-guidance",label:"Project agent guidance",status:xe.skipped.length>0?"warn":"ok",message:`${xe.written.length} written, ${xe.unchanged.length} already wired, ${xe.skipped.length} skipped.`,details:xe.skipped.map(L=>`Skipped ${L.target}: ${L.reason}`)}))}catch(L){_(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:qt(L)})}let En=Pk({reindexResult:j,readiness:G,capabilities:In,freshness:us,health:ps,hooksResult:ie,agentResult:xe,watchConfig:K,watchService:N,rustSemanticSession:Te,steps:t});_(t,{id:"smoke-tests",label:"Setup smoke tests",status:Tk(En),message:Ik(En),details:En.map(L=>`${L.command}: ${L.status} - ${L.evidence}`)});let zg={repository:[...a?.changed?[a.configPath]:[],...u?.changed?[u.configPath]:[],...xe?.written.filter(L=>!L.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...ie?.installed??[],...ie?.updated??[],...ie?.gitExcluded??[],...xe?.written.filter(L=>L.startsWith(".git/hooks/"))??[]])],user:[...h.installed,...R.installed,...D.filter(L=>L.attempted).map(L=>`${L.binaryLabel} installer`)]},Fe={projectRoot:r,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:f,languages:G.languages,steps:t,skills:h,astParsers:R,initialReadiness:v,indexerRemediation:D,readiness:G,capabilities:In,freshness:us,reindex:j,automaticRefreshConfig:u,watchService:N,rustSemanticSession:Te,health:ps,smokeTests:En,healthDossier:null,hooks:ie,setupAgent:xe,changeScopes:zg,filesWritten:xe?.written??[],verdict:Fo(t,G)};if(e.runHealth===!1)return _(t,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),Fe.verdict=Fo(t,G),Fe;let Ie=Op(Fe,{dossierDir:e.dossierDir});return Fe.healthDossier=Ie,Fe.changeScopes.repository.push(...Ie.written),Fe.filesWritten=[...Fe.filesWritten,...Ie.written],_(t,{id:"health-dossier",label:"Health dossier",status:Ie.status==="failed"?"failed":"ok",message:Ie.status==="failed"?Ie.error:`${Ie.written.length} written, ${Ie.unchanged.length} unchanged.`,details:[Ie.markdownPath,Ie.jsonPath]}),Fe.verdict=Fo(t,G),Fe}async function $k(e){if(e.readiness.languages.length===0||e.configHasErrors)return _(e.steps,{id:"reindex",label:"Index refresh",status:"skipped",message:e.readiness.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."}),{reindexResult:null,freshness:null};let t=[],n=null,r=null;try{let i=0,o=!1;for(let s=0;s<2;s+=1){if(n=await Bt({projectRoot:e.projectRoot,languages:e.readiness.languages,outputScip:e.paths.indexPath,outputDb:e.paths.dbPath,pnpmWorkspaces:e.config.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.config.indexer?.typescript?.projectMode,typescriptProjects:e.config.indexer?.typescript?.projects,clojureConfigPath:e.config.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:e.config.indexerConcurrency,trigger:{kind:"setup",detail:"scip-query setup"},onStatus:a=>{t.push(a),e.onStatus?.(a)}}),i+=n.durationMs,o||=!n.reused,r=je(e.projectRoot,e.config,e.paths),s===0&&n.skipped.length===0&&r.state==="stale"){t.push(`Index inputs changed during the first build (${r.reason}); running one settling refresh.`);continue}break}if(!n)throw new Error("Setup index refresh produced no result.");_(e.steps,{id:"reindex",label:"Index refresh",status:n.skipped.length>0?"warn":"ok",message:`${o?"Indexed":"Reused"} ${n.languages.join(", ")} in ${(i/1e3).toFixed(1)}s.`,details:[...t,...n.skipped.map(s=>`Skipped ${s.language}: ${s.reason}`)]})}catch(i){_(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:qt(i),details:t})}return{reindexResult:n,freshness:r}}function Ck(e){let t=e.readiness.languages.length===0?"Skipped because no supported languages were detected.":e.configHasErrors?"Skipped because config validation has errors.":e.watchConfig.enabled?e.reindexResult===null||e.reindexResult.skipped.length>0||e.postReindexFreshness?.state!=="fresh"?"Skipped because the initial refresh did not produce a complete fresh generation.":null:"Disabled by watch.enabled=false; setup left the explicit opt-out unchanged.";if(t!==null)return _(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=tr({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:ue,watchOverrides:e.watchConfig});if(e.watchConfig.idleTimeoutMs>0&&n.state.idleDeadlineAt===void 0)throw new Error("Automatic indexing service did not publish its configured clean-idle deadline.");let r=e.watchConfig.idleTimeoutMs===0?"configured to remain running":`clean-idle exit scheduled for ${n.state.idleDeadlineAt}`;return _(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"ok",message:`${n.disposition} pid ${n.state.pid}; ${r}.`,details:[`watcher=${n.state.watcher.state}`,`autoRefresh=${e.watchConfig.autoRefresh}`,`gitPollMs=${e.watchConfig.gitPollMs}`]}),n}catch(n){return _(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:qt(n)}),null}}function Vp(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${Lo(e.health)}`),console.log(""),e.health.issuesNeedAttention.length===0)console.log("Items that need attention: none reported by the health pass.");else{console.log("Items that need attention:");for(let t of e.health.issuesNeedAttention)console.log(` - ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort})`)}if(e.health.unavailableReason&&console.log(`Health pass: ${e.health.unavailableReason}`),e.health.warnings.length>0){console.log("Health warnings:");for(let t of e.health.warnings)console.log(` - ${t}`)}e.healthDossier&&console.log(`Health dossier: ${e.healthDossier.markdownPath}`),console.log(""),console.log("Change scopes:"),Do("Repository records (commit)",e.changeScopes.repository),Do("Checkout preferences (do not commit)",e.changeScopes.checkout),Do("User environment",e.changeScopes.user),console.log(""),console.log("Setup steps:");for(let t of e.steps)console.log(` ${t.status.toUpperCase()} ${t.label}${t.message?` - ${t.message}`:""}`);console.log(""),console.log("Smoke tests:");for(let t of e.smokeTests)console.log(` ${t.status.toUpperCase()} ${t.command} - ${t.evidence}`);if(e.indexerRemediation.length>0){console.log(""),console.log("Indexer remediation:");for(let t of e.indexerRemediation){let n=t.after.runnable?"ready":"blocked",r=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${r})`),t.recovery&&console.log(` ${t.recovery}`)}}}function Do(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function Pk(e){let t=e.steps.find(o=>o.id==="reindex"),n=e.steps.find(o=>o.id==="project-hooks"),r=e.steps.find(o=>o.id==="agent-guidance"),i=e.steps.find(o=>o.id==="watch-refresh");return[{id:"reindex",command:"scip-query reindex",status:e.reindexResult?"pass":t?.status==="failed"?"fail":"unavailable",evidence:e.reindexResult?`${e.reindexResult.languages.join(", ")} indexed${e.reindexResult.reused?" from cache":""}.`:t?.message??"No reindex result was produced."},{id:"status",command:"scip-query status",status:e.freshness.state==="fresh"?"pass":"fail",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"scip-query config-validate",status:Ek(e.steps),evidence:jk(e.steps)},{id:"capabilities",command:"scip-query capabilities",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?`${e.capabilities.matrix.length} language capability row(s) available.`:"No detected languages produced capability rows."},{id:"capability-matrix",command:"scip-query capability-matrix --json",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?Ak(e.capabilities):"No detected languages produced capability rows."},{id:"health",command:"scip-query health",status:e.health.score===null?"unavailable":"pass",evidence:e.health.score===null?e.health.unavailableReason??"Health report was not available.":`Health score ${e.health.score}.`},{id:"diff-impact",command:"scip-query diff-impact --json",status:Np(e.readiness,e.freshness),evidence:_p(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:Np(e.readiness,e.freshness),evidence:_p(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:Lk(e.capabilities),evidence:Ok(e.capabilities)},{id:"setup-hooks",command:"scip-query setup-hooks",status:e.hooksResult?"pass":n?.status==="failed"?"fail":"unavailable",evidence:e.hooksResult?`${e.hooksResult.installed.length} installed, ${e.hooksResult.updated.length} updated, ${e.hooksResult.unchanged.length} already configured.`:n?.message??"Project agent hooks were not configured."},{id:"watch-refresh",command:"scip-query status --json",status:i?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",evidence:i?.message??"Watch refresh policy was not evaluated."},{id:"rust-semantic-session",command:"scip-query status --json",status:e.rustSemanticSession===null?"unavailable":e.rustSemanticSession.valid?"pass":"fail",evidence:e.rustSemanticSession===null?"Rust was not detected.":`${e.rustSemanticSession.transport}/${e.rustSemanticSession.state}; ${e.rustSemanticSession.fallback} fallback; ${e.rustSemanticSession.optOut}.`},{id:"setup-agent",command:"scip-query setup-agent",status:e.agentResult?"pass":r?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:r?.message??"Project agent guidance was not written."}]}function Tk(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Ik(e){let t=e.filter(i=>i.status==="pass").length,n=e.filter(i=>i.status==="unavailable").length,r=e.filter(i=>i.status==="fail").length;return`${t} passed, ${n} unavailable, ${r} failed.`}function Ek(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function jk(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function Ak(e){let t=e.matrix.filter(n=>[n.indexing,n.sourceFacts,n.semantic,n.cleanupVerification].some(r=>r.status==="unavailable")).length;return`${e.matrix.length} language row(s), ${t} with unavailable capability cells.`}function Np(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function _p(e,t){if(!e.gitAvailable)return"Git is not available for this project.";let n=t.lastRefresh?` Last refresh: ${t.lastRefresh.result} by ${t.lastRefresh.trigger.kind} at ${t.lastRefresh.completedAt}.`:"";return`Git is available and index freshness is ${t.state}: ${t.reason}${n}`}function Lk(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function Ok(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(i=>i.cleanupVerification.status==="available").length,n=e.matrix.filter(i=>i.cleanupVerification.status==="partial").length,r=e.matrix.filter(i=>i.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${r} unavailable cleanup-verification row(s).`}function Dk(e,t,n){let r=[];if(t.languages.length===0)return _(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),r;for(let s of t.indexers){if(s.runnable)continue;let a=pt(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=Cr(a,m=>c.push(m)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let u=Fk(Bn(a,e));r.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:d,before:s,after:u,messages:c,recovery:u.runnable?void 0:u.note??u.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(r.length===0)return _(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),r;let i=r.filter(s=>!s.after.runnable),o=r.filter(s=>s.attempted);return _(n,{id:"indexer-remediation",label:"Indexer remediation",status:i.length>0?"warn":"ok",message:i.length===0?`${o.length} install attempt(s); all detected indexers are runnable.`:`${o.length} install attempt(s); ${i.length} indexer(s) still blocked.`,details:r.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),r}function Fk(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function Mk(e,t){if(!wk(e)){let n="Skipped because no SQLite index database exists yet.";return _(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Mo(n)}try{let n=await Zn({full:!0,json:!0});return _(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),_k(n)}catch(n){let r=qt(n);return _(t,{id:"health",label:"Health audit",status:"failed",message:r}),Mo(r)}}function Nk(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return _(e,{id:"health",label:"Health audit",status:"skipped",message:t}),Mo(t)}function _k(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(Bk),warnings:e.warnings??[]}}function Bk(e){return{category:e.category,description:e.description,count:e.count,impact:e.impact,effort:e.effort,evidence:e.evidence,locRecoverable:e.locRecoverable,confirmationStatus:"unconfirmed",safeForAgentToStart:!1,recommendedNextStep:"Run scip-audit to confirm this signal; use scip-improve when the user wants confirmed issues fixed autonomously."}}function Mo(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Fo(e,t){return e.some(n=>n.status==="failed")?"blocked":t.indexers.some(n=>!n.runnable)||e.some(n=>n.status==="warn"||n.status==="skipped")?"partial":"ready"}function qk(e){let t=e.matrix.flatMap(n=>[n.indexing.status,n.sourceFacts.status,n.semantic.status,n.cleanupVerification.status]);return t.some(n=>n==="unavailable")||t.some(n=>n==="partial")?"warn":"ok"}function Vk(e){return e.matrix.length===0?"No language capability rows.":`${e.matrix.filter(n=>n.indexing.status==="available").length}/${e.matrix.length} language(s) have available indexing.`}function _(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function qt(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as Wk}from"readline";function Hk(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function Uk(e,t,n){if(n.length===0)return e;if(t==="up")return{...e,cursor:(e.cursor-1+n.length)%n.length};if(t==="down")return{...e,cursor:(e.cursor+1)%n.length};let r=n[e.cursor]?.id;if(!r)return e;let i=new Set(e.selected);return i.has(r)?i.delete(r):i.add(r),{...e,selected:i}}async function Wp(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=Hk(e);Wk(t);let i=t.isRaw;t.setRawMode(!0),t.resume();let o=(s=!1)=>{s||n.write(`\x1B[${e.length+3}A`),n.write(`scip-query setup
347
- `),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
348
-
349
- `),e.forEach((a,c)=>{let l=c===r.cursor?"\u203A":" ",d=r.selected.has(a.id)?"\u25CF":"\u25CB";n.write(`${l} ${d} ${a.label} [${a.scope}]\x1B[K
350
- `)}),n.write("\x1B[K")};o(!0);try{return await new Promise((s,a)=>{let c=(d,u)=>{if(u.ctrl&&u.name==="c"){l(),a(new Error("Setup cancelled."));return}if(u.name==="return"||u.name==="enter"){l(),n.write(`
351
- `),s(r.selected);return}let m=u.name==="up"?"up":u.name==="down"?"down":u.name==="space"?"toggle":null;m&&(r=Uk(r,m,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!i),t.pause()}}import{existsSync as Hp,mkdirSync as Gk,writeFileSync as Jk}from"fs";import{dirname as zk,join as Up}from"path";function Gp(e,t={}){let n=Up(e,".github","workflows","scip-query.yml"),r=Kk({hasNpmProject:Hp(Up(e,"package.json"))});return Hp(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(Gk(zk(n),{recursive:!0}),Jk(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function Kk(e){let t=`scip-query@${ue}`;return`name: scip-query
352
-
353
- # Generated by scip-query setup-ci.
354
- # Install the language indexers your repository needs before the reindex step
355
- # if they are not already provided by your dependency install.
356
-
357
- on:
358
- pull_request:
359
-
360
- jobs:
361
- diff-gate:
362
- runs-on: ubuntu-latest
363
- steps:
364
- - uses: actions/checkout@v4
365
- with:
366
- fetch-depth: 0
367
- - uses: actions/setup-node@v4
368
- with:
369
- node-version: 22
370
- - uses: actions/cache@v4
371
- with:
372
- path: ~/.cache/scip-query
373
- key: scip-query-\${{ runner.os }}-\${{ hashFiles('package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb', 'Cargo.lock', 'go.sum', 'poetry.lock', 'uv.lock') }}
374
- ${e.hasNpmProject?` - run: npm ci
375
- `:[" # TODO: install this repository's dependencies before indexing."," # This project did not have a package.json when the workflow was generated."].join(`
376
- `)+`
377
- `} - run: npx ${t} reindex
378
- - run: npx ${t} diff-gate --base "origin/\${{ github.base_ref }}"
379
- `}import{existsSync as Qk}from"fs";import{join as Fr}from"path";function Jp(e){let t=e.global===!0,n=e.project===!0,r=!t&&!n,i=t||r,o=n||r,s={dryRun:e.dryRun===!0};return i&&(s.global=Ed({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=Xk(e.projectRoot,{dryRun:e.dryRun})),s}function Xk(e,t={}){return{hooks:Dt(e,{remove:!0,dryRun:t.dryRun}),agentSetup:Gl(e,{dryRun:t.dryRun}),left:Yk(e)}}function Yk(e){return[[".scipquery.json",Fr(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",Fr(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",Fr(e,".scipquery","ledger")],["docs/scip-query/",Fr(e,"docs","scip-query")]].filter(([,t])=>Qk(t)).map(([t])=>t)}import{existsSync as Zk,readFileSync as ew}from"fs";import{createRequire as tw}from"module";import Nr from"path";import{performance as Mr}from"perf_hooks";var nw=tw(import.meta.url),Rn;function Yp(e){let t=rw();if(!t)return Hn("typescript is not installed");let n=zs(e);if(n.length===0)return Hn("no tsconfig found");try{return new No(e.config.projectRoot,t,n.map(r=>iw(t,r)))}catch(r){return Hn(r instanceof Error?r.message:String(r),n[0],n)}}function Zp(e,t,n){let r=Mr.now(),i=zp(t,e),o=Mr.now()-r,s=Mr.now(),a=zp(n,e),c=Mr.now()-s,l=[],d=0,u=0,m=0,g=0,f=0;for(let h of e){let b=i.get(h.symbolId)??[],y=a.get(h.symbolId)??[];u+=b.length,m+=y.length;let v=Kp(b),R=Kp(y),T=Qp(b,R),D=Qp(y,v);if(T.length===0&&D.length===0){d+=1;continue}g+=T.length,f+=D.length,l.push({symbol:h.symbol,missing:T,extra:D})}return{slot:"semantic-references",definitions:e.length,matches:d,mismatchCount:l.length,missingReferenceCount:g,extraReferenceCount:f,baselineReferenceCount:u,candidateReferenceCount:m,baselineMs:Number(o.toFixed(3)),candidateMs:Number(c.toFixed(3)),mismatches:l}}var No=class{constructor(t,n,r){this.projectRoot=t;this.ts=n;this.bundles=r}projectRoot;ts;bundles;language="typescript";referencesCache=new Map;availability(){return{available:!0,tsconfigPath:this.bundles[0]?.tsconfigPath,tsconfigPaths:this.bundles.map(t=>t.tsconfigPath)}}importUsage(t){return[]}referencesFor(t){let n=this.referencesCache.get(t.symbolId);if(n)return n;let r=this.computeReferences(t);return this.referencesCache.set(t.symbolId,r),r}referencesForDefinitions(t){let n=new Map;for(let r of t)n.set(r.symbolId,this.referencesFor(r));return n}calleesFor(t){return[]}signatureFor(t){return null}computeReferences(t){let n=Nr.join(this.projectRoot,t.relativePath),r=this.bundleForFile(n);if(!r)return[];let i=r.service.getProgram()?.getSourceFile(n);if(!i)return[];let o=sw(this.ts,i,t);if(o===null)return[];let s=r.service.findReferences(n,o)??[],a=[];for(let c of s)for(let l of c.references){let d=aw(this.ts,r.service,this.projectRoot,l);d&&(d.file===t.relativePath&&d.line>=t.startLine&&d.line<=t.endLine||a.push(d))}return Gs(a)}bundleForFile(t){let n=tm(t);return this.bundles.find(r=>r.files.has(n))??null}};function rw(){if(Rn!==void 0)return Rn;try{Rn=nw("typescript")}catch{Rn=null}return Rn}function iw(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(Xp(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,Nr.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>Xp(e,s)).join(`
380
- `));let i=new Set(r.fileNames.map(tm)),o=e.createLanguageService(ow(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function ow(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?Nr.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(Zk(n))return e.ScriptSnapshot.fromString(ew(n,"utf8"))},getScriptVersion:()=>"0",readDirectory:e.sys.readDirectory,readFile:e.sys.readFile,fileExists:e.sys.fileExists,directoryExists:e.sys.directoryExists,realpath:e.sys.realpath,useCaseSensitiveFileNames:()=>e.sys.useCaseSensitiveFileNames}}function sw(e,t,n){let r=t.text.split(`
381
- `),i=Math.max(0,n.startLine),o=Math.min(r.length-1,Math.max(n.endLine,n.startLine));for(let s=i;s<=o;s+=1){let a=r[s]?.indexOf(n.leaf)??-1;if(a>=0)return e.getPositionOfLineAndCharacter(t,s,a)}return null}function aw(e,t,n,r){let i=Js(n,r.fileName);if(!i)return null;let o=t.getProgram()?.getSourceFile(r.fileName);if(!o)return null;let s=e.getLineAndCharacterOfPosition(o,r.textSpan.start);return{file:i,line:s.line,column:s.character}}function zp(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function Kp(e){return new Set(e.map(em))}function Qp(e,t){return e.filter(n=>!t.has(em(n)))}function em(e){return`${e.file}:${e.line}:${e.column}`}function tm(e){return Nr.resolve(e).replace(/\\/g,"/")}function Xp(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
382
- `)}import{readFileSync as cw}from"fs";function nm(e){let t=[];for(let[n,r]of cw(e,"utf8").split(`
383
- `).entries()){let i=r.trim();if(!i)continue;let o;try{o=JSON.parse(i)}catch(s){throw new Error(`${e}:${n+1}: invalid profile JSON: ${s instanceof Error?s.message:String(s)}`,{cause:s})}if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`${e}:${n+1}: profile event must be a JSON object`);t.push(o)}return t}function rm(e,t={}){let n=new Map,r=new Map,i=new Map,o=new Set,s=new Set,a=new Set,c=new Set,l=0,d=0,u=0;for(let[b,y]of e.entries()){let v=Re(y.name)??Re(y.phase),R=gw(y.durationMs),T=Re(y.runId);v&&R!==null&&(l+=1,s.add(v),T&&o.add(T),lw(i,y,v,R),dw(r,y,v,R,T),Re(y.subsystemWorkIdentity)&&c.add(v));let D=Re(y.workIdentity);if(!D)continue;d+=1,v&&a.add(v);let C=fw(y.workOutcome);if(!v||R===null||!C){u+=1;continue}let U=T??`unknown-run-${b}`,j=JSON.stringify([v,D]),M=n.get(j)??{spanName:v,workIdentity:D,observations:[]};M.observations.push({runId:U,command:Re(y.command)??"unknown",durationMs:R,outcome:C}),n.set(j,M)}let m=[...n.values()].map(mw).filter(b=>b!==null).sort((b,y)=>y.estimatedAvoidableMs-b.estimatedAvoidableMs||y.repeatComputations-b.repeatComputations||b.spanName.localeCompare(y.spanName)||b.workIdentity.localeCompare(y.workIdentity)),g=[...r.values()].map(uw).filter(b=>b!==null).sort((b,y)=>y.laterRunMs-b.laterRunMs||y.laterRunEvents-b.laterRunEvents||b.spanName.localeCompare(y.spanName)),f=[...i.values()].map(pw).sort((b,y)=>y.totalDurationMs-b.totalDurationMs||b.subsystem.localeCompare(y.subsystem)),h=t.top??20;return{profileEvents:e.length,spanEvents:l,distinctSpanNames:s.size,instrumentedEvents:d,unclassifiedInstrumentedEvents:u,exactIdentifiedSpanNames:a.size,workloadIdentifiedEvents:f.reduce((b,y)=>b+y.workloadIdentifiedEvents,0),workloadIdentifiedSpanNames:c.size,runCount:o.size,repeatedGroups:m.length,largestOpportunityMs:m[0]?.estimatedAvoidableMs??0,rows:m.slice(0,h),repeatedWorkloads:g.length,largestRepeatedWorkloadMs:g[0]?.laterRunMs??0,workloadRows:g.slice(0,h),subsystemCoverage:f}}function im(e,t){let n=["scip-query work-audit",`Profile: ${t}`,`Profile events: ${e.profileEvents}; spans: ${e.spanEvents}; distinct span names: ${e.distinctSpanNames}; runs: ${e.runCount}`,`Subsystem identity coverage: ${e.workloadIdentifiedSpanNames}/${e.distinctSpanNames} span names, ${e.workloadIdentifiedEvents}/${e.spanEvents} events`,`Exact identity coverage: ${e.exactIdentifiedSpanNames}/${e.distinctSpanNames} span names, ${e.instrumentedEvents}/${e.spanEvents} events`,`Repeated work groups: ${e.repeatedGroups}; largest measured opportunity: ${e.largestOpportunityMs}ms`,""];if(e.rows.length===0)n.push("No exact repeated computations were found in work-identified profile events."),e.instrumentedEvents===0&&n.push("This profile predates exact work identities or its spans have not been instrumented yet.");else{n.push("Exact repeated computations:"),n.push("avoidableMs withinRunMs crossRunMs repeats runs span workIdentity commands");for(let r of e.rows)n.push([r.estimatedAvoidableMs,r.withinRunAvoidableMs,r.crossRunRecomputeMs,r.repeatComputations,r.runCount,r.spanName,r.workIdentity,r.commands.join(", ")].join(" "))}if(n.push("",`Repeated subsystem workloads: ${e.repeatedWorkloads}`),e.workloadRows.length===0)n.push("No named subsystem workload was observed in more than one run.");else{n.push("laterRunMs firstRunMs laterEvents runs subsystem span subsystemWorkIdentity commands");for(let r of e.workloadRows)n.push([r.laterRunMs,r.firstRunMs,r.laterRunEvents,r.runCount,r.subsystem,r.spanName,r.subsystemWorkIdentity,r.commands.join(", ")].join(" "))}return n.push("","Rows are independent measurements; nested spans can overlap and must not be summed."),n.push("Within-run time is direct duplication. Cross-run time is a durable-cache opportunity that still needs safe invalidation."),n.push("Subsystem workload time is an aggregate observation against the same command/project inputs, not proven avoidable time."),`${n.join(`
384
- `)}
385
- `}function lw(e,t,n,r){let i=Re(t.subsystem)??n.split(/[.:]/,1)[0]??n,o=e.get(i)??{subsystem:i,events:0,totalDurationMs:0,spanNames:new Set,workloadIdentifiedEvents:0,workloadIdentifiedSpanNames:new Set,exactIdentifiedEvents:0,exactIdentifiedSpanNames:new Set};o.events+=1,o.totalDurationMs+=r,o.spanNames.add(n),Re(t.subsystemWorkIdentity)&&(o.workloadIdentifiedEvents+=1,o.workloadIdentifiedSpanNames.add(n)),Re(t.workIdentity)&&(o.exactIdentifiedEvents+=1,o.exactIdentifiedSpanNames.add(n)),e.set(i,o)}function dw(e,t,n,r,i){let o=Re(t.subsystemWorkIdentity);if(!o||!i||t.workloadIdentityKind!=="published-project")return;let s=Re(t.subsystem)??n.split(/[.:]/,1)[0]??n,a=JSON.stringify([n,o]),c=e.get(a)??{subsystem:s,spanName:n,subsystemWorkIdentity:o,observations:[]};c.observations.push({runId:i,command:Re(t.command)??"unknown",durationMs:r}),e.set(a,c)}function uw(e){let t=new Map;for(let o of e.observations){let s=t.get(o.runId)??[];s.push(o),t.set(o.runId,s)}let n=[...t.values()];if(n.length<2)return null;let r=n[0],i=n.slice(1).flat();return{subsystem:e.subsystem,spanName:e.spanName,subsystemWorkIdentity:e.subsystemWorkIdentity,commands:[...new Set(e.observations.map(o=>o.command))].sort(),runCount:n.length,totalEvents:e.observations.length,firstRunEvents:r.length,laterRunEvents:i.length,totalDurationMs:Vt(e.observations.map(o=>o.durationMs)),firstRunMs:Vt(r.map(o=>o.durationMs)),laterRunMs:Vt(i.map(o=>o.durationMs))}}function pw(e){return{subsystem:e.subsystem,events:e.events,totalDurationMs:e.totalDurationMs,spanNames:[...e.spanNames].sort(),workloadIdentifiedEvents:e.workloadIdentifiedEvents,workloadIdentifiedSpanNames:e.workloadIdentifiedSpanNames.size,exactIdentifiedEvents:e.exactIdentifiedEvents,exactIdentifiedSpanNames:e.exactIdentifiedSpanNames.size}}function mw(e){let t=e.observations.filter(a=>a.outcome==="computed");if(t.length<2)return null;let n=new Map;for(let a of t){let c=n.get(a.runId)??[];c.push(a),n.set(a.runId,c)}let r=[...n.values()],i=Vt(r.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=Vt(r.slice(1).map(a=>a[0]?.durationMs??0)),s=[...new Set(e.observations.map(a=>a.command))].sort();return{spanName:e.spanName,workIdentity:e.workIdentity,commands:s,computations:t.length,runCount:r.length,repeatComputations:t.length-1,withinRunRepeats:t.length-r.length,crossRunRecomputes:Math.max(0,r.length-1),totalComputeMs:Vt(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:i,crossRunRecomputeMs:o,estimatedAvoidableMs:i+o,cacheHits:_r(e.observations,"cache-hit"),cacheMisses:_r(e.observations,"cache-miss"),reused:_r(e.observations,"reused"),skipped:_r(e.observations,"skipped")}}function fw(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function _r(e,t){return e.filter(n=>n.outcome===t).length}function gw(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Re(e){return typeof e=="string"&&e.length>0?e:null}function Vt(e){return e.reduce((t,n)=>t+n,0)}var om={status:"experimental-composite",comparableAcrossLanguages:!1,scope:"completed-analyses-only",note:"The score summarizes analyses that completed under the attached capability matrix. It is not normalized across languages or frameworks and is not suitable for a public leaderboard."};function sm(e,t){let n=hw(t);return{...e,warnings:[...e.warnings??[],om.note,...n],capabilities:t,scoreInterpretation:om}}function hw(e){return e.matrix.flatMap(t=>{let n=[t.indexing,t.sourceFacts,t.semantic,t.cleanupVerification].map(r=>/syntax only/i.test(r.reason)?`${r.label}=partial (syntax only)`:r.status==="available"?null:`${r.label}=${r.status}`).filter(r=>r!==null);return n.length===0?[]:[`${t.language} capability limits: ${n.join(", ")}. Unsupported analyses are not clean zeros.`]})}import{basename as yw,join as bw}from"path";var xn=class extends Error{constructor(n,r,i){super(`${n} ${i?`Current revision: ${i}. Retry with --replace ${i} after reviewing it.`:"The suppression file was left untouched."}`);this.path=r;this.currentRevision=i;this.name="SuppressionWriteConflictError"}path;currentRevision};function dm(e,t,n={}){let r=n instanceof Date?{now:n}:n,i=vw(t),o=Rw(r.expectedRevision),s=bw(ic(e),oc(i)),a=r.now??new Date,c="unchanged",l=ct(s,d=>{if(!d.revision.exists){if(o)throw new xn(`Cannot replace ${s}: the observed suppression no longer exists.`,s);return c="created",{kind:"write",text:lm(am(i,void 0,a,r.toolVersion))}}let u=Sw(d);if(xw(u.suppression,i))return c="unchanged",{kind:"unchanged"};if(!o)throw new xn(`A different suppression decision already exists at ${s}.`,s,d.revision.hash);if(o!==d.revision.hash)throw new xn(`Suppression ${s} changed after the revision you reviewed.`,s,d.revision.hash);return c="replaced",{kind:"write",text:lm(am(i,u.suppression,a,r.toolVersion))}},{maxRetries:0,onBeforeCommit:r.onBeforeCommit});return{path:s,disposition:c,revision:l.current.revision.hash}}function Sw(e){let t;try{t=JSON.parse(e.text)}catch(r){throw new Error(`Cannot update ${e.path}: the existing suppression is malformed JSON.`,{cause:r})}let n=ac(t,kw(e.path));if("error"in n)throw new Error(`Cannot update ${e.path}: ${n.error}.`);return n}function am(e,t,n,r=ue){let i=n.toISOString();return{kind:nc,schemaVersion:rc,suppressionIdentity:sc(e),writer:{tool:"scip-query",version:r},...e,createdAt:t?.createdAt??e.createdAt??i,...t?{updatedAt:i}:{}}}function vw(e){let t=e.reason?.trim();if(!t)throw new Error("suppression requires a non-empty reason");let n=e.id?.trim(),r=e.check?.trim();if(!n&&!r)throw new Error("suppression requires an id or a check");return{...n?{id:n}:{},...r?{check:r}:{},...e.file?{file:e.file}:{},reason:t,...e.expiresAt?{expiresAt:e.expiresAt}:{},...e.createdAt?{createdAt:e.createdAt}:{}}}function Rw(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Error("--replace requires the 64-character SHA-256 revision reported by suppress.");return t}function xw(e,t){return JSON.stringify(cm(e))===JSON.stringify(cm(t))}function cm(e){let{createdAt:t,...n}=e;return n}function kw(e){let t=yw(e);return t.endsWith(".json")?t.slice(0,-5):t}function lm(e){return`${JSON.stringify(e,null,2)}
386
- `}var jw=new Set(gs),Aw=18e4,gm=100*1024*1024,Lw=new Set(Ss),Ow=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],Dw=[["health","--json"],["dead","--json","--full"],["isolated","--json","--full"],["similar","--json","--full"],["similar-files","--json","--full"],["recent-duplicates","--json","--full"],["doc-drift","--json","--full"],["unused-params","--json","--full"],["wrapper-candidates","--json","--full"],["passthrough-candidates","--json","--full"],["stale-abstractions","--json","--full"],["incomplete-migration","--json","--full"],["cleanup-plan","--verify","--json"],["complexity-hotspots","--json","--full"]];function Fw(e){return e.filter(t=>jw.has(t))}async function hm(e){let t=z(e),n=te(),r=be(n),i=_e(n,r),o=S(t,"json");try{let s=Fw(Et(t,"language")),a=await Bt({projectRoot:n,languages:s.length>0?s:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:S(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,clojureConfigPath:r.indexer?.clojure?.configPath,skipIfUnchanged:!S(t,"force"),allowPartial:S(t,"allowPartial"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",indexerConcurrency:Q(t,"indexerConcurrency")??r.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...o?{onStatus:()=>{}}:{}});if(o){E("reindex",[],t,a);return}console.log(`${a.reused?"Reused":"Indexed"} ${a.languages.join(", ")} in ${(a.durationMs/1e3).toFixed(1)}s`)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exit(1)}}function ym(){let e=te(),t=Tt(e);try{let n=Sr({projectRoot:e,dbPath:t,onStatus:r=>console.log(r)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function bm(e){let t=z(e),n=te(),r=Tt(n);try{let i=await ko({projectRoot:n,dbPath:r,tsconfig:w(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${i.vueFiles}; resolved references: ${i.resolvedReferences}; inserted mentions: ${i.insertedMentions}; not-inserted identifier tokens: ${i.skippedReferences}; synthetic symbols: ${i.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${i.skippedReferenceReasons["no-definition"]}; same-file definition ${i.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${i.skippedReferenceReasons["unindexed-definition"]}; missing source ${i.skippedReferenceReasons["missing-source-file"]}; missing service script ${i.skippedReferenceReasons["missing-service-script"]}. Samples: ${i.skippedReferenceSamples.length} omitted, ${i.resolvedReferenceSamples.length} resolved.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function Sm(e){let t=z(e);pe(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=Va(n,{base:w(t,"base")}),o=Wa(n,r,i.changedFiles,i.changedRanges);Si(on,o)})}async function vm(e){let t=z(e);try{let n=await sl({base:w(t,"base")});if(S(t,"json")){E("diff-impact",[],t,n);return}al(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Rm(e,t){let n=z(t),r=String(e).split(",").filter(i=>i.length>0);pe(i=>{let o=[];for(let c of r)wc.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:w(n,"scope"),full:S(n,"full")},a=o.length===1?$c(i,o[0],s):Cc(i,o,s);Si(rn,a)})}async function xm(e){let t=z(e);if(S(t,"writeBaseline")||S(t,"baseline")){Qw(t);return}try{let n=await Zn({scope:w(t,"scope"),full:S(t,"full"),json:S(t,"json")}),{projectRoot:r,config:i,dbPath:o}=qe(),s=tt(ve(r,i),{hasIndexedGraph:Pe(o)}),a=sm(n,s);if(S(t,"json")){E("health",[],t,a);return}ol(a)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function km(e){let t=z(e),n=te(),r=Q(t,"timeoutMs")??Aw,i=S(t,"progress"),o=S(t,"profile"),s=w(t,"profileOut"),a={projectRoot:n,...Gw(n),index:_o(Pe(Tt(n))),commands:[]};S(t,"coldIndex")&&(Wt(i,"cold index started"),a.coldIndex=await Mw(n),Wt(i,`cold index finished ${a.coldIndex.durationMs}ms`),Qt({type:"bench-index",phase:"cold-index",projectRoot:n,durationMs:a.coldIndex.durationMs,result:a.coldIndex.result,files:a.coldIndex.files,symbols:a.coldIndex.symbols},s),Wt(i,"warm index started"),a.warmIndex=await qw(n),Wt(i,`warm index finished ${a.warmIndex.durationMs}ms`),Qt({type:"bench-index",phase:"warm-index",projectRoot:n,durationMs:a.warmIndex.durationMs,result:a.warmIndex.result,files:a.warmIndex.files,symbols:a.warmIndex.symbols},s),a.index=_o(Pe(Tt(n))));for(let c of Vw(t))a.commands.push(Hw(n,c,r,{progress:i,profile:o,profileOut:s}));if(S(t,"json")){E("bench",[],t,a);return}Jw(a)}function wm(e,t){let n=z(t),r=Ew(String(e)),i=rm(nm(r),{top:Q(n,"top")??20});if(S(n,"json")){E("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(im(i,r))}function $m(e){let t=z(e);pe(n=>{let r=n.config.projectRoot,i=w(t,"scope")??null,o=S(t,"full"),s=Q(t,"limit")??200,a=Math.max(0,Q(t,"maxMismatches")??10),c=ws(n).filter(R=>en(R.relativePath)).filter(R=>!n.isIgnored(R.relativePath)).sort(Kw),l=i?c.filter(R=>R.relativePath.includes(i)):c,d=o?l:l.slice(0,s),u=ot.now(),m=Qs(n),g=Number((ot.now()-u).toFixed(3)),f=ot.now(),h=Yp(n),b=Number((ot.now()-f).toFixed(3)),y=Zp(d,m,h),v={projectRoot:r,selection:{scope:i,full:o,limit:o?null:s,maxMismatchDetails:a,totalTypeScriptDefinitions:c.length,scopedDefinitions:l.length,comparedDefinitions:d.length},baseline:{provider:"ts-morph",createMs:g,availability:m.availability()},candidate:{provider:"tsserver",createMs:b,availability:h.availability()},comparison:{...y,mismatches:y.mismatches.slice(0,a)}};if(S(t,"json")){E("typescript-semantic-compare",[],t,v);return}zw(v)})}async function Mw(e){let t=be(e),n=_e(e,t),r=Br(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;Nw(r);let o=_w(r,i);try{let s=await Cm(()=>Bt({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench --cold-index"},onStatus:()=>{}}));return um(r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...Pm(e)}}catch(s){throw um(r,i,o,"restore-backup"),s}}var Bo={existsSync:Pe,readFileSync:ww,writeFileSync:Tw,renameSync:$w,rmSync:Cw,unlinkSync:Pw};function qo(e){return ht(Br(e),"bench-restore.json")}function Nw(e,t=Bo){let n=qo(e);if(!t.existsSync(n))return!1;let r=Bw(t.readFileSync(n,"utf8"));return r&&!t.existsSync(r.originalPath)&&t.existsSync(r.backupPath)&&t.renameSync(r.backupPath,r.originalPath),t.unlinkSync(n),!0}function _w(e,t,n=Bo){return n.existsSync(e)?(n.writeFileSync(qo(e),JSON.stringify({originalPath:e,backupPath:t})),n.renameSync(e,t),!0):!1}function um(e,t,n,r,i=Bo){n&&r==="restore-backup"&&!i.existsSync(e)&&i.existsSync(t)?i.renameSync(t,e):n&&r==="discard-backup"&&i.rmSync(t,{recursive:!0,force:!0});let o=qo(e);i.existsSync(o)&&i.unlinkSync(o)}function Bw(e){try{let t=JSON.parse(e);return typeof t.originalPath=="string"&&typeof t.backupPath=="string"?{originalPath:t.originalPath,backupPath:t.backupPath}:null}catch{return null}}async function qw(e){let t=be(e),n=_e(e,t),r=await Cm(()=>Bt({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench warm index"},onStatus:()=>{}}));return{durationMs:r.durationMs,result:r.value.reused?"reused":"rebuilt",languages:r.value.languages,...Pm(e)}}async function Cm(e){let t=ot.now(),n=await e();return{durationMs:Math.round(ot.now()-t),value:n}}function Pm(e){return Pe(Tt(e))?pe(t=>{let n=wt(t);return{files:n.documents,symbols:n.symbols}}):{}}function Vw(e){let t=Et(e,"command");return t.length>0?t.map(Ww).filter(n=>n.length>0):[...Ow.map(n=>[...n]),...S(e,"includeHeavy")?Dw.map(n=>[...n]):[]]}function Ww(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function Hw(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;Wt(r.progress,`${i} started`),Qt({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=ot.now(),s={...r.profile?Uw(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=fm(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:gm,timeout:n}),c=Math.round(ot.now()-o),l={command:i,durationMs:c,exitCode:a.status,signal:a.signal,timedOut:a.error?.code==="ETIMEDOUT"||a.error?.name==="ETIMEDOUT",stdoutBytes:a.stdout?.length??0,stderrBytes:a.stderr?.length??0,...r.profileOut?{profilePath:r.profileOut}:{}};return Wt(r.progress,`${i} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),Qt({type:"bench-command-finish",command:i,projectRoot:e,durationMs:c,exitCode:l.exitCode,signal:l.signal,timedOut:l.timedOut,stdoutBytes:l.stdoutBytes,stderrBytes:l.stderrBytes},r.profileOut),l}function Wt(e,t){e&&process.stderr.write(`[bench] ${t}
387
- `)}function Uw(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function Gw(e){let t=fm("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:gm,timeout:3e4,killSignal:"SIGKILL"});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
388
- `).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(r=>Lw.has(Iw(r).toLowerCase())).length}}function Jw(e){console.log("scip-query bench"),console.log(`Project: ${e.projectRoot}`),console.log(`Repo files: ${e.repoFiles??"unknown"}; source-like files: ${e.sourceFiles??"unknown"}`),e.index&&console.log(`Index: ${e.index.files} files, ${e.index.symbols} symbols, ${Ve(e.index.indexSizeBytes)}`),e.coldIndex&&pm("Cold index",e.coldIndex),e.warmIndex&&pm("Warm index",e.warmIndex),console.log(`
389
- Commands:`);for(let t of[...e.commands].sort((n,r)=>r.durationMs-n.durationMs)){let n=t.timedOut?"timeout":t.exitCode===0?"ok":`exit ${t.exitCode??t.signal??"unknown"}`;console.log(` ${String(t.durationMs).padStart(7)}ms ${n.padEnd(10)} ${String(t.stdoutBytes).padStart(8)}B out ${t.command}`)}}function pm(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function zw(e){if(console.log("TypeScript semantic provider comparison"),console.log(`Project: ${e.projectRoot}`),console.log(`Definitions: ${e.selection.comparedDefinitions}/${e.selection.scopedDefinitions} compared`+(e.selection.scope?`, scope ${e.selection.scope}`:"")),console.log(`ts-morph: create ${e.baseline.createMs}ms, refs ${e.comparison.baselineMs}ms, refs ${e.comparison.baselineReferenceCount}`),console.log(`tsserver: create ${e.candidate.createMs}ms, refs ${e.comparison.candidateMs}ms, refs ${e.comparison.candidateReferenceCount}`),console.log(`Matches: ${e.comparison.matches}; mismatches: ${e.comparison.mismatchCount}; missing refs: ${e.comparison.missingReferenceCount}; extra refs: ${e.comparison.extraReferenceCount}`),e.comparison.mismatches.length!==0){console.log(`
390
- Mismatch samples:`);for(let t of e.comparison.mismatches)console.log(` ${t.symbol}`),console.log(` missing=${t.missing.length} extra=${t.extra.length}`)}}function Kw(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function Qw(e){let t=w(e,"scope");pe(n=>{if(S(e,"writeBaseline")){let i=Xa(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=Ya(n,{scope:t});if(r.fixedFindings.length>0&&console.log(`${r.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),r.newFindings.length===0){console.log(`OK: no new findings vs baseline (${r.baselineCount} baselined, ${r.current.length} current).`);return}console.log(`FAIL: ${r.newFindings.length} new finding(s) vs ${r.baselinePath}:`);for(let i of r.newFindings)console.log(` + ${i}`);process.exitCode=1})}function Tm(){let e=yr(),t=e.installed.length+e.alreadyLinked.length;console.log(`
391
- ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.pruned.length} pruned, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function Im(e){let t=z(e),n=te(),r=Dt(n,{shared:S(t,"shared"),remove:S(t,"remove"),force:S(t,"force")});if(S(t,"json")){E("setup-hooks",[],t,r);return}for(let o of r.installed)console.log(` done: ${o}`);for(let o of r.updated)console.log(` update: ${o}`);for(let o of r.unchanged)console.log(` ok: ${o} (already configured)`);for(let o of r.removed)console.log(` remove: ${o}`);for(let o of r.gitExcluded)console.log(` local: ${o} (excluded through .git/info/exclude)`);for(let o of r.warnings)console.log(` warning: ${o}`);for(let o of r.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);r.installed.length+r.updated.length+r.unchanged.length>0?(console.log(`
392
- Checkout-local scip-query hooks are configured for this clone and must not be committed.`),console.log("Review new or changed hooks in Codex/Claude Code with /hooks before they run.")):console.log(`
393
- No project-local hook config was written.`)}function Em(){let e=!1;pn()?console.log("scip CLI: installed"):(Hi(),e=!0);let t=te(),n=be(t),r=ve(t,n);if(r.languages.length===0){console.log(`
394
- No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
395
- Detected languages: ${r.languages.join(", ")}`),console.log(`
396
- Indexer readiness:`);for(let o of r.indexers){let s=o.runnable?" OK":o.installed?" WARN":" MISSING",a=o.resolvedBinary?` (${o.resolvedBinary})`:"";console.log(`${s} ${o.language}: ${o.binaryLabel}${a}`),o.note&&console.log(` ${o.note}`),!o.installed&&o.installUrl&&console.log(` install: ${o.installUrl}`),o.runnable||(e=!0)}let i=zm(r);i.length>0&&console.log(`
397
- Semantic provider readiness:`);for(let o of i){let s=o.available?" OK":o.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${o.language}: ${s$(o)}${Km(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function jm(e){Lm(e,"capabilities")}function Am(e){S(z(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),Lm(e,"capability-matrix")}function Lm(e,t){let n=z(e),{projectRoot:r,config:i,paths:o,dbPath:s}=qe(),a=ve(r,i),c=je(r,i,o),l=tt(a,{hasIndexedGraph:Pe(s)&&c.state!=="missing"});if(S(n,"json")){E(t,[],n,l);return}Vo(l)}function Om(){let e=te(),t=lt(e),n=Ac(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Dm(e){let t=z(e),n=te(),r=be(n),i=Pt(r,{projectRoot:n});if(S(t,"json"))E("config-validate",[],t,{diagnostics:i});else if(i.length===0)console.log("Config OK.");else for(let o of i)console.log(`${o.level.toUpperCase()} ${o.path}: ${o.message}`);i.some(o=>o.level==="error")&&(process.exitCode=1)}function Fm(e,t){let n=z(t),r=w(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=dm(te(),{id:String(e),check:w(n,"check"),file:w(n,"file"),reason:r,expiresAt:w(n,"expiresAt")},{expectedRevision:w(n,"replace")});if(S(n,"json")){E("suppress",[String(e)],n,i);return}console.log(`Suppression ${i.disposition} at ${i.path}. Revision: ${i.revision}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exitCode=1}}function Mm(e){let t=z(e),n=Date.now(),r=w(t,"since"),i;if(r){let y=$p(r,n);if(y===null){console.error(`error: could not parse --since "${r}" (use 30d, 12w, or an ISO date).`),process.exitCode=1;return}i=y}let o=te(),s=ur(o),a=wp(s.events,{sinceMs:i,check:w(t,"check")}),c=Ze("Committed outcome history",s.compatibility);if(S(t,"json")){E("effectiveness",[],t,{...a,recordCompatibility:{outcomeEvents:s.compatibility}});return}if(c&&console.log(`WARN: ${c}`),a.checks.length===0){console.log(s.events.length===0?`No outcome events recorded yet (${ht(ln,"*.json")} is missing or empty). Events accrue as diff-gate runs; commit the event files so history is shared.`:"No findings match the requested window/check.");return}let l=["check","caught","fixed","suppressed","open","moved","unverified","precision","median-days-to-fix"],d=a.checks.map(y=>[y.check,String(y.caught),String(y.fixed),String(y.suppressed),String(y.open),String(y.moved),String(y.unverified),y.precision===null?"-":`${Math.round(y.precision*100)}%`,y.medianDaysToFix===null?"-":y.medianDaysToFix.toFixed(1)]),u=l.map((y,v)=>Math.max(y.length,...d.map(R=>R[v].length))),m=y=>y.map((v,R)=>v.padEnd(u[R])).join(" ");console.log(m(l));for(let y of d)console.log(m(y));let g=a.checks.reduce((y,v)=>y+v.fixed,0),f=a.checks.reduce((y,v)=>y+v.suppressed,0),h=a.checks.reduce((y,v)=>y+v.unverified,0),b=g+f;b>0?console.log(`
398
- ${g} finding(s) verified fixed against a stable comparison base, ${f} suppressed, ${h} disappeared without comparable evidence \u2014 overall precision ${Math.round(g/b*100)}%.`):h>0&&console.log(`
399
- ${h} finding(s) disappeared without comparable comparison-base evidence; precision is not available.`)}function Nm(e){let t=z(e),{report:n,hasIndexerProblems:r,hasErrors:i}=_m("doctor");S(t,"json")?E("doctor",[],t,n):n$(n,r),process.exitCode=i?1:0}function _m(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=qe(),o=Pt(n,{projectRoot:t}),s=ve(t,n),a=je(t,n,r),c=Pe(i),l=tt(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=wl(t,n,r),u=s.indexers.some(f=>!f.runnable),m=o.some(f=>f.level==="error")||u||a.state==="missing"||a.state==="stale",g=o.some(f=>f.level==="error")||u||a.state==="missing";return{report:{command:e,projectRoot:t,dbPath:i,configuredDbPath:r.dbPath,exists:c,configDiagnostics:o,readiness:s,freshness:a,capabilities:l,sharedCache:d,ok:!m},hasIndexerProblems:u,hasErrors:g}}function Bm(e){let t=z(e),n=te(),r=ir(n,{gitHook:S(t,"gitHook")});for(let i of r.written)console.log(` done: ${i}`);for(let i of r.unchanged)console.log(` ok: ${i} (already wired)`);for(let i of r.skipped)console.log(` skip: ${i.target} \u2014 ${i.reason}`);console.log(`
400
- Agents reading this project now know to route through the scip-query skills and gate their diffs.`),console.log("Keep the index fresh (`scip-query reindex` or `scip-query watch`) so the gate sees current code.")}async function qm(e){let t=z(e);try{let n={gitHook:S(t,"gitHook"),noHooks:S(t,"noHooks")||t.hooks===!1,dossierDir:w(t,"dossierDir"),runHealth:S(t,"yes")?!1:t.health!==!1,installSkills:t.skills!==!1,installAstParsers:t.parsers!==!1,...S(t,"yes")?{automaticRefresh:!0}:{}},r=S(t,"json"),i=!r&&!S(t,"yes")&&process.stdin.isTTY&&process.stdout.isTTY;(S(t,"guided")||i)&&(n=await Xw(n,{json:S(t,"json")})),r||(n.onStatus=s=>console.log(` ${s}`));let o=await qp(n);S(t,"json")?E("setup",[],t,o):Vp(o),process.exitCode=o.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Xw(e,t){let{projectRoot:n,config:r}=qe(),i=ve(n,r),o=Bp({files:Yw(n),watchEnabled:Ee(r).enabled,readiness:i}),s=i.languages.map(f=>({id:`language:${f}`,scope:"project",label:`Index ${f}`,reason:"Detected in this project.",selected:!0})),a=o.actions.map(f=>({id:f.id,scope:f.scope==="repository"?"project":f.scope,label:f.label,reason:f.reason,selected:f.recommended})),c=Oo(i.languages);a.push({id:"install-agent-skills",scope:"user",label:"Install agent skills",reason:"Makes scip-query workflows available to local agents.",selected:!0},...c.length>0?[{id:"install-ast-parsers",scope:"user",label:`Install or repair AST parsers (${c.join(", ")})`,reason:"Installs the Tree-sitter runtime and grammars used for source-level analysis.",selected:!0}]:[],{id:"run-health-analysis",scope:"analysis",label:"Run full health analysis and write dossier",reason:"Optional and can take much longer than indexing.",selected:!1});let l=!t.json&&process.stdin.isTTY&&process.stdout.isTTY,d=l?await Wp([...s,...a]):new Set([...Zw(o.actions),...s.map(f=>f.id)]);l&&e$(o.actions,d);let u=d.has("create-agent-guidance")||d.has("update-agent-guidance"),m=o.actions.some(f=>f.id==="enable-automatic-refresh"),g=o.actions.some(f=>f.id==="install-indexers");return{...e,...m?{automaticRefresh:d.has("enable-automatic-refresh")}:{},noHooks:e.noHooks||o.actions.some(f=>f.id==="install-project-hooks")&&!d.has("install-project-hooks"),noAgentGuidance:!u,...g?{installIndexers:d.has("install-indexers")}:{},languages:i.languages.filter(f=>d.has(`language:${f}`)),installSkills:d.has("install-agent-skills"),installAstParsers:d.has("install-ast-parsers"),runHealth:d.has("run-health-analysis")}}function Yw(e){return{agentsMd:Pe(ht(e,"AGENTS.md")),claudeMd:Pe(ht(e,"CLAUDE.md")),codexHooks:Pe(ht(e,".codex","hooks.json")),claudeSettings:Pe(ht(e,".claude","settings.local.json"))}}function Zw(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function e$(e,t){console.log(""),console.log("Selected setup changes:");for(let n of["repository","checkout","user"]){let r=e.filter(o=>o.scope===n&&t.has(o.id)).map(o=>o.label);console.log(` ${n} (${n==="repository"?"commit these shared project changes":n==="checkout"?"keep these local to this checkout":"changes this machine or user environment"}): ${r.length>0?r.join(", "):"none"}`)}}function Vm(e){let t=z(e),n=te(),r=Gp(n,{force:S(t,"force"),dryRun:S(t,"dryRun")});if(S(t,"dryRun")){console.log(r.content);return}if(r.skipped){console.log(`skip: ${r.path} \u2014 ${r.reason}`);return}console.log(`done: ${r.path}`)}function Wm(e){let t=z(e);if(S(t,"global")&&S(t,"project")){console.error("error: choose either --global or --project, not both."),process.exitCode=1;return}let n=Jp({projectRoot:te(),global:S(t,"global"),project:S(t,"project"),dryRun:S(t,"dryRun")});if(S(t,"json")){E("uninstall",[],t,n);return}let r=n.dryRun?"would ":"";if(n.global){for(let o of n.global.removed)console.log(` ${r}remove: ${o}`);for(let o of n.global.left)console.log(` left: ${o}`);for(let o of n.global.skipped)console.log(` skip: ${o}`)}if(n.project){for(let o of n.project.hooks.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.unchanged)console.log(` ok: ${o} (no managed block)`);for(let o of n.project.hooks.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.agentSetup.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.left)console.log(` left: ${o}`)}(n.global?.removed.length??0)+(n.project?.hooks.removed.length??0)+(n.project?.agentSetup.removed.length??0)===0&&console.log(n.dryRun?"No scip-query-owned files would be removed.":"No scip-query-owned files removed.")}function Hm(e){let t=z(e),n=te(),r=be(n),i=Q(t,"debounce"),o=Q(t,"cooldown"),s=Q(t,"gitPoll"),a=Q(t,"idleTimeout"),c=S(t,"daemon"),l=S(t,"status"),d=S(t,"stop"),u=S(t,"json"),m=[c,l,d].filter(Boolean).length;if(m>1){console.error("error: choose only one of --daemon, --status, or --stop."),process.exitCode=1;return}if(u&&m===0){console.error("error: --json requires --daemon, --status, or --stop."),process.exitCode=1;return}let g=[["--debounce",i,!1],["--cooldown",o,!0],["--git-poll",s,!1],["--idle-timeout",a,!0]].find(([,C,U])=>C!==void 0&&(!Number.isInteger(C)||(U?Number(C)<0:Number(C)<=0)));if(g){console.error(`error: ${g[0]} requires ${g[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}let f={...i===void 0?{}:{debounceMs:i},...o===void 0?{}:{cooldownMs:o},...s===void 0?{}:{gitPollMs:s},...a===void 0?{}:{idleTimeoutMs:a}};i&&((r.watch??={}).debounceMs=i),o!==void 0&&((r.watch??={}).cooldownMs=o),s&&((r.watch??={}).gitPollMs=s),a!==void 0&&((r.watch??={}).idleTimeoutMs=a);let h=Ee(r);r.watch=h;let b=_e(n,r),y={projectRoot:n,cacheDir:b.cacheDir,cliVersion:ue,watchOverrides:f};if(l){let C=Um(Ri(y),h.enabled);u?E("watch",[],t,C):Gm(C);return}if(d){try{let C=Rl(y);u?E("watch",[],t,C):console.log(C.disposition==="stopped"?`Stopped watch service${C.pid?` (pid ${C.pid})`:""}.`:"Watch service is already stopped.")}catch(C){console.error(`error: ${C instanceof Error?C.message:String(C)}`),process.exitCode=1}return}if(!h.enabled){console.error('error: watch mode is disabled. Set "watch.enabled": true in .scipquery.json to start it.'),process.exitCode=1;return}if(c){try{let C=tr(y);u?E("watch",[],t,C):console.log(`${C.disposition==="started"?"Started":"Reused"} watch service for ${n} (pid ${C.state.pid}).`)}catch(C){console.error(`error: ${C instanceof Error?C.message:String(C)}`),process.exitCode=1}return}let v=kl(ht(Br(b.dbPath),Vs),n);if(!v.acquired){console.error(v.message),process.exitCode=1;return}let R=new Or({projectRoot:n,config:r,languages:r.languages,onStatus:C=>{process.stdout.write(`\r\x1B[K${bi(C)}`)},onReindexComplete:C=>(console.log(`
401
- Reindex complete in ${(C/1e3).toFixed(1)}s`),je(n,r,b).state==="fresh"),onRefreshSuppressed:C=>{nu(b.dbPath,C),console.log(`
402
- Skipped redundant refresh; the completed index already includes the queued changes.`)},onError:C=>{console.error(`
403
- Watch error: ${C.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${h.debounceMs}ms | Cooldown: ${h.cooldownMs}ms | Git poll: ${h.gitPollMs}ms`),console.log(`Press Ctrl+C to stop.
404
- `),R.start();let T=!1,D=()=>{T||(T=!0,R.stop().then(C=>{if(C.state==="degraded"){T=!1,console.error(`
405
- Unable to stop safely: ${C.reasons.join("; ")}`);return}v.release(),console.log(`
406
- Stopped.`),process.exit(0)}))};process.on("SIGINT",D),process.on("SIGTERM",D)}function Um(e,t=!0){let{classification:n}=e,r=Sl(e.paths.refreshRequestsPath);switch(n.kind){case"stopped":return e.lockIsLive&&e.lock?{enabled:t,state:"running",mode:"foreground-or-starting",pid:e.lock.pid,projectRoot:e.identity.projectRoot,worktreeId:e.identity.worktreeId,startedAt:e.lock.startedAt,refreshRequests:r}:{enabled:t,state:"stopped",mode:"none",refreshRequests:r};case"live":return{enabled:t,state:"running",mode:"daemon",pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,startedAt:n.state.startedAt,heartbeatAt:n.state.heartbeatAt,lastActivityAt:n.state.lastActivityAt,idleDeadlineAt:n.state.idleDeadlineAt,watcher:n.state.watcher,indexGeneration:n.state.indexGeneration,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,reindexActivity:n.state.reindexActivity,refreshRequests:r,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};case"stale":case"incompatible":return{enabled:t,state:n.kind,mode:"daemon",reason:n.reason,pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,heartbeatAt:n.state.heartbeatAt,watcher:n.state.watcher,indexGeneration:n.state.indexGeneration,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,reindexActivity:n.state.reindexActivity,refreshRequests:r,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};default:return t$(n)}}function Gm(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`),mm(e.refreshRequests);return}let t="pid"in e?` (pid ${e.pid})`:"";if(console.log(`Watch service: ${e.state} [${e.mode}]${t}`),"projectRoot"in e&&e.projectRoot){let n="worktreeId"in e&&e.worktreeId?` [${e.worktreeId.slice(0,12)}]`:"";console.log(`Worktree: ${e.projectRoot}${n}`)}if("watcher"in e&&e.watcher&&console.log(`Watcher: ${bi(e.watcher)}`),"indexGeneration"in e&&e.indexGeneration&&console.log(`Index generation: ${e.indexGeneration.slice(0,12)}`),"idleDeadlineAt"in e&&e.idleDeadlineAt&&console.log(`Idle exit: ${e.idleDeadlineAt}`),"reason"in e&&console.log(`Reason: ${e.reason}`),"lastError"in e&&e.lastError&&console.log(`Last error: ${e.lastError.message}`),"reindexActivity"in e&&e.reindexActivity){let n=e.reindexActivity;console.log(`Reindex activity (24h): ${n.runs} run(s) (${n.rebuilt} rebuilt, ${n.reused} reused, ${n.failed} failed), ${n.suppressed} redundant refresh(es) suppressed, ${Ve(n.estimatedLogicalOutputBytes)} estimated logical output`)}if("refreshRequests"in e&&e.refreshRequests&&mm(e.refreshRequests),"typescriptSemantic"in e&&e.typescriptSemantic){let n=e.typescriptSemantic;console.log(`TypeScript semantics: ${n.state} (${n.projectsCreated} Projects, ${n.requests} requests)`)}if("typescriptIndex"in e&&e.typescriptIndex){let n=e.typescriptIndex;console.log(`TypeScript index: ${n.state} (${n.initializations} warmups, ${n.programUpdates} updates, ${n.requests} requests)`)}}function mm(e){console.log(`Refresh requests: ${e.pending} pending, ${e.claimed} claimed, ${e.completed} completed, ${e.expired} expired${e.invalid>0?`, ${e.invalid} invalid`:""}`)}function t$(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function Jm(e){let t=z(e),{report:n}=_m("status"),r=Ee(be(n.projectRoot)).enabled,i=Um(Ri({projectRoot:n.projectRoot,cacheDir:Br(n.configuredDbPath),cliVersion:ue}),r),o=qd(n.dbPath),s=dt(n.dbPath,n.freshness.metaPath),a=Vn(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(S(t,"json")){E("status",[],t,{...n,affectedSetShadow:o,sqliteGeneration:s,rustSemanticSession:a,watchService:i,stats:_o(n.exists)});return}r$(n,{affectedSetShadow:o,capabilities:S(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:i})}function n$(e,t){console.log(`Doctor: ${e.ok?"OK":"needs attention"}`);for(let n of e.configDiagnostics)console.log(` ${n.level.toUpperCase()} ${n.path}: ${n.message}`);if(t)for(let n of e.readiness.indexers.filter(r=>!r.runnable))console.log(` MISSING ${n.language}: ${n.note??n.binaryLabel}`);console.log(` Freshness: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),Vo(e.capabilities)}function r$(e,t){console.log(`Project: ${e.projectRoot}`),console.log(`DB path: ${e.dbPath}`),e.dbPath!==e.configuredDbPath&&console.log(`Config: ${e.configuredDbPath} (fallback to project root index.db)`);for(let n of zm(e.readiness)){let r=n.available?"available":n.dependencyAvailable?"fallback":"unavailable",i=n.language==="typescript"?"TS sem:":`${n.language} sem:`;console.log(`${i.padEnd(9)}${r}${Km(n)}`),n.reason&&console.log(`${n.language} note: ${n.reason}`)}console.log(`Exists: ${e.exists?"yes":"no"}`),console.log(`Fresh: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),e.freshness.lastRefresh&&console.log(`Refresh: ${a$(e.freshness.lastRefresh)}`),Gm(t.watchService),i$(e.sharedCache),console.log(`Rust sess: ${t.rustSemanticSession.transport}/${t.rustSemanticSession.state} (${t.rustSemanticSession.source}; worker fallback; opt out with ${t.rustSemanticSession.optOut})`),t.rustSemanticSession.valid||console.log("Rust note: invalid durable-session value; using worker fallback"),o$(t.sqliteGeneration),console.log(`Shadow: ${Vd(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),c$(e.exists),t.capabilities&&(console.log(""),Vo(e.capabilities))}function i$(e){if(e.state!=="managed"){console.log(`Shared: ${e.state}${e.reason?` (${e.reason})`:""}`);return}let t=e.activeGenerationId?.slice(0,12)??"none",n=e.lastAction??"none";console.log(`Shared: ${n}, active ${t}, ${e.generations} generation(s), ${Ve(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${Ve(e.unreferencedBytes)}), ${e.temporaryGenerations} temporary`),e.cleanup?.kind==="swept"&&console.log(`Cache GC: ${e.cleanup.deletedWorktrees??0} worktree(s), ${e.cleanup.deletedGenerations??0} generation(s), ${Ve(e.cleanup.deletedBytes??0)} removed`)}function o$(e){if(e.state==="legacy"){console.log("DB gen: legacy (no generation record)");return}if(e.state==="invalid"){console.log(`DB gen: invalid (${e.reason})`);return}let t=e.generation.publication,n=t?.mode??"unknown",r=t?[t.affectedDocumentCount===void 0?null:`${t.affectedDocumentCount} affected`,t.changedDocumentCount===void 0?null:`${t.changedDocumentCount} changed`,t.producerDurationMs===void 0?null:`${t.producerDurationMs.toFixed(0)}ms producer`,`${t.converterDurationMs.toFixed(0)}ms convert`,t.patchDurationMs===void 0?null:`${t.patchDurationMs.toFixed(0)}ms patch`,`${t.scipCompanion??"current"} SCIP companion`].filter(i=>i!==null).join(", "):"no publication metrics";console.log(`DB gen: ${e.state} ${e.generation.currentGeneration.slice(0,12)} (${n}; ${r})`),console.log(`DB layout: ${e.generation.artifactSet==="immutable-v1"?"immutable artifact set; stable paths are mirrors":"legacy stable paths"}`),e.generation.previousGeneration&&console.log(`Recovery: ${e.generation.previousGeneration.generationIdentity.slice(0,12)} at ${e.generation.previousGeneration.databasePath}`),t?.fallbackReason&&console.log(`DB fallback: ${t.fallbackReason}`),e.reason&&console.log(`DB note: ${e.reason}`)}function zm(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function s$(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function Km(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function a$(e){let t=(e.durationMs/1e3).toFixed(1),n=e.trigger.detail?` (${e.trigger.detail})`:"",r=e.error?`: ${e.error}`:"";return`${e.result} by ${e.trigger.kind}${n} in ${t}s at ${e.completedAt}${r}`}function _o(e){if(e)return pe(t=>{let n=wt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function c$(e){e&&pe(t=>{let n=wt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Ve(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function Vo(e){console.log(`Capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`);for(let t of e.capabilities)console.log(` ${t.status.toUpperCase().padEnd(11)} ${t.label} [${t.evidence}]`),console.log(` ${t.reason}`);if(e.matrix.length!==0){console.log(`
407
- Language matrix:`);for(let t of e.matrix){console.log(` ${t.language}`);for(let n of[t.indexing,t.sourceFacts,t.semantic,t.detectors,t.cleanupVerification])console.log(` ${n.status.toUpperCase().padEnd(11)} ${n.label}`),console.log(` ${n.reason}`)}}}function kn(e){return{...e,options:I(e.options)}}function Oe({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=kn(l);return{...d,renderShape:"list",handler:dl({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c})}}function qr({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d,...u}){let m=kn(u);return{...m,renderShape:"table",handler:ul({commandName:m.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d})}}function Qm({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,key:l,...d}){let u=kn(d);return{...u,renderShape:"grouped-by-file",handler:pl({commandName:u.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,key:l})}}function Xm({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=kn(l);return{...d,renderShape:"sectioned-report",handler:ml({commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,coverage:s,agentResult:a,after:c})}}function Vr({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=kn(l);return{...d,budget:d.budget??"semantic",renderShape:"sectioned-report",handler:fl(d.id,{commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,coverage:s,agentResult:a,after:c})}}import{existsSync as B$,mkdirSync as q$,writeFileSync as V$}from"fs";import{dirname as W$,relative as H$}from"path";import{existsSync as Xe,readdirSync as f$,readFileSync as yt}from"fs";import{basename as g$,dirname as of,isAbsolute as sf,join as h$,relative as y$,resolve as wn,sep as b$}from"path";import{spawnSync as d$}from"child_process";import{dirname as u$}from"path";function Zm(e){let n=(e.spawnSync??d$)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:u$(e.specPath),maxBuffer:1024*1024*32,timeout:3e4,killSignal:"SIGKILL"});if(n.status!==0)return null;let r=n.stdout??"";return r.includes("<?xml")?r:null}function ef(e){let t=m$(e),n=new Map,r=new Map,i=[],o=new Map;for(let a of t)a.type==="OpDeclNode"&&a.kind===3&&a.uniquename?n.set(a.uid,a.uniquename):a.type==="BuiltInKind"&&a.uniquename?r.set(a.uid,a.uniquename):a.type==="UserDefinedOpKind"&&a.uniquename&&(i.push(a),o.set(a.uid,a));let s=[];for(let a of i){let c=tf(a.block,n,r,o,a.filename,new Set([a.uid]),0);s.push({name:a.uniquename,reads:c.reads,writes:c.writes})}return{modelParse:"sany",variables:[...n.values()].sort(),operators:i.map(a=>a.uniquename).sort(),actions:s}}var p$=8;function m$(e){let t=[],n=/<entry>\s*<UID>(\d+)<\/UID>\s*<(\w+)>/g;for(let r of e.matchAll(n)){let i=r.index,o=e.indexOf("</entry>",i),s=e.slice(i,o<0?e.length:o),a=Wo(s,"uniquename"),c=Wo(s,"kind"),l=Wo(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:Ym(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:Ym(l),block:s})}return t}function tf(e,t,n,r,i,o,s){let a=new Set,c=new Set,l=[...e.matchAll(/<(\w+Ref)>\s*<UID>(\d+)<\/UID>/g)],d="read";for(let[,u,m]of l){if(u==="BuiltInKindRef"){let g=n.get(m)??"";g==="'"?d="write-next":g==="UNCHANGED"?d="unchanged-run":d==="unchanged-run"&&g==="$Tuple"||d!=="write-next"&&(d="read");continue}if(u==="OpDeclNodeRef"){let g=t.get(m);if(!g)continue;d==="write-next"?(c.add(g),d="read"):d==="unchanged-run"||a.add(g);continue}if(u==="UserDefinedOpKindRef"){d==="unchanged-run"&&(d="read");let g=r.get(m);if(g&&s<p$&&!o.has(g.uid)&&g.filename===i){let f=tf(g.block,t,n,r,i,new Set([...o,g.uid]),s+1);for(let h of f.reads)a.add(h);for(let h of f.writes)c.add(h)}continue}d==="unchanged-run"&&(d="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function Wo(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function Ym(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var af=["update","insert","delete"],cf=["select","query","findFirst","findMany"],Ho=new Set([...af,...cf]);function Uo(e){let t=e.methods&&e.methods.length>0?e.methods:[...Ho],n=new Set(af),r=new Set(cf);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var S$=/^(.*)@L(\d+)-L(\d+)$/;function Go(e){let t=e.match(S$);if(!t)return{ref:e};let n=t[1],r=Number.parseInt(t[2],10),i=Number.parseInt(t[3],10);return n?r<1?{error:`codeRef "${e}" line window must start at line 1 or later`}:i<r?{error:`codeRef "${e}" line window end (L${i}) is before its start (L${r})`}:{ref:n,window:{startLine:r,endLine:i}}:{error:`codeRef "${e}" has a line window but no referent before @L${t[2]}-L${t[3]}`}}var v$=new Set(["auto","sany","tlc","apalache","none"]),Hr=/^[A-Za-z_][A-Za-z0-9_]*$/;function lf(e){return v$.has(e)}function Ur(e,t){let n=[],r=ge(e,t);if(!r)return{errors:[`map path escapes project root: ${t}`]};if(!Xe(r))return{errors:[`map file not found: ${t}`]};let i;try{i=JSON.parse(yt(r,"utf8"))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let o=R$(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:of(r)},errors:n}:{errors:n}}function ge(e,t){if(!t)return null;let n=sf(t)?wn(t):wn(e,t);return he(e,n)?n:null}function df(e,t,n){if(!n)return null;if(sf(n)){let s=wn(n);return he(e,s)?s:null}let r=wn(e,n);if(he(e,r)&&Xe(r))return r;let i=wn(t,n);if(he(e,i)&&Xe(i))return i;let o=he(e,r)?r:i;return he(e,o)?o:null}function uf(e,t){let n=ge(e,t);if(!n||!Xe(n))return null;let r=yt(n,"utf8");return{path:n,modelParse:"regex-fallback",text:r,variables:D$(r),operators:F$(r),actions:[]}}function pf(e,t,n){let r=ge(e,t);if(!r||!Xe(r))return null;let i=yt(r,"utf8"),o=ef(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function Jo(e,t){let n=ge(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!Xe(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let r=JSON.parse(yt(n,"utf8")),i=Array.isArray(r)?r:W(r)&&Array.isArray(r.steps)?r.steps:null;if(!i)return{steps:[],errors:["trace file must be an array or an object with a steps array"]};let o=[],s=[];for(let[a,c]of i.entries()){if(!W(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}o.push({action:c.action,before:W(c.before)?c.before:void 0,after:W(c.after)?c.after:void 0,code:typeof c.code=="string"?c.code:void 0})}return{steps:o,errors:s}}catch(r){let i=r instanceof Error?r.message:String(r);return{steps:[],errors:[`trace file is not valid JSON: ${i}`]}}}function zo(e,t){let n=new Set,r=[];for(let i of t){let o=ge(e,i)??i;n.has(o)||(n.add(o),r.push(i))}return r}function R$(e,t){if(!W(e))return t.push("map file must contain a JSON object"),null;let n=P$(e.variables,t);C$(n,t);let r=L$(e.actions,n,t),i=x$(e.init,t);w$(i,r,t);let o={module:rf(e.module,"module",t),config:rf(e.config,"config",t),scope:X(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:X(e.invariants)??[],traces:X(e.traces)??[],unmappedWriteScope:$$(e.unmappedWriteScope,t)};return N$(e.scope,t),t.length===0?o:null}function x$(e,t){if(e===void 0)return;if(!W(e)){t.push("init must be an object when present");return}let n=X(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let r=k$(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function k$(e,t){if(e===void 0)return;if(!W(e)){t.push("init.waive must be an object when present");return}let n=typeof e.reason=="string"?e.reason.trim():"";if(!n){t.push("init.waive.reason must be a non-empty string");return}return{reason:n}}function w$(e,t,n){if(!e)return;let r=new Set(e.codeRefs),i=new Set;for(let o of Object.values(t))for(let s of o.code)r.has(s)&&i.add(s);i.size>0&&n.push(`init.codeRefs overlaps action code referents: ${[...i].sort().join(", ")} \u2014 a referent cannot be both Init and an action`)}function $$(e,t){return e===void 0?"scope-files":e==="actions"||e==="scope-files"?e:(t.push('unmappedWriteScope must be "actions" or "scope-files" when present'),"scope-files")}function C$(e,t){Wr(e,t,"alias",n=>n.aliases),Wr(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),Wr(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),Wr(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=Uo(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function Wr(e,t,n,r){let i=new Map;for(let[o,s]of Object.entries(e))for(let a of r(s)){let c=i.get(a);c?c.push(o):i.set(a,[o])}for(let[o,s]of i)s.length<2||t.push(`variables ${[...new Set(s)].sort().join(", ")} share ${n} "${o}" \u2014 conformance scanning cannot attribute a matching write/read to one variable unambiguously`)}function P$(e,t){if(!W(e))return t.push("variables must be an object keyed by TLA+ variable name"),{};let n={};for(let[r,i]of Object.entries(e)){if(!Hr.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!W(i)){t.push(`variables.${r} must be an object`);continue}let o=ff(i.code);if(!o||o.length===0){t.push(`variables.${r}.code must name at least one TypeScript referent`);continue}let s=X(i.aliases)??[],a=I$(i.resource,r,t),c=E$(i.statements,r,t),l=j$(i.ormCalls,r,t),d=A$(i.waive,r,t),u=T$(i.selfAlias,r,t),m=u?[...new Set([r,...s])]:[...new Set(s)];u===!1&&m.length===0&&!a&&!c&&!l&&!d&&t.push(`variables.${r}.selfAlias is false but no aliases, resource, statements, ormCalls, or waive are set \u2014 ${r} would be unattributable; add an explicit alias, bind resource/statements/ormCalls, or add variables.${r}.waive with a reason`),n[r]={code:o,aliases:m,projection:typeof i.projection=="string"?i.projection:void 0,...a?{resource:a}:{},...c?{statements:c}:{},...l?{ormCalls:l}:{},...d?{waive:d}:{},...u===!1?{selfAlias:!1}:{}}}return n}function T$(e,t,n){return e===void 0?!0:typeof e=="boolean"?e:(n.push(`variables.${t}.selfAlias must be a boolean when present`),!0)}function I$(e,t,n){if(e===void 0)return;if(!W(e)){n.push(`variables.${t}.resource must be an object when present`);return}let r=typeof e.path=="string"?e.path.trim():"";if(!r){n.push(`variables.${t}.resource.path must be a non-empty string`);return}return{path:r}}function E$(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.statements must be an array when present`);return}let r=[];return e.forEach((i,o)=>{if(!W(i)){n.push(`variables.${t}.statements[${o}] must be an object`);return}let s=typeof i.pattern=="string"?i.pattern.trim():"";if(!s){n.push(`variables.${t}.statements[${o}].pattern must be a non-empty string`);return}try{new RegExp(s)}catch(a){let c=a instanceof Error?a.message:String(a);n.push(`variables.${t}.statements[${o}].pattern is not a valid regular expression: ${c}`);return}r.push({pattern:s})}),r.length>0?r:void 0}function j$(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.ormCalls must be an array when present`);return}let r=[];return e.forEach((i,o)=>{if(!W(i)){n.push(`variables.${t}.ormCalls[${o}] must be an object`);return}let s=typeof i.table=="string"?i.table.trim():"";if(!s){n.push(`variables.${t}.ormCalls[${o}].table must be a non-empty string`);return}if(i.methods===void 0){r.push({table:s});return}let a=X(i.methods);if(!a){n.push(`variables.${t}.ormCalls[${o}].methods must be an array of strings when present`);return}let c=a.filter(l=>!Ho.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...Ho].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function A$(e,t,n){if(e===void 0)return;if(!W(e)){n.push(`variables.${t}.waive must be an object when present`);return}let r=typeof e.reason=="string"?e.reason.trim():"";if(!r){n.push(`variables.${t}.waive.reason must be a non-empty string`);return}return{reason:r}}function L$(e,t,n){if(!W(e))return n.push("actions must be an object keyed by TLA+ action name"),{};let r=new Set(Object.keys(t)),i={};for(let[o,s]of Object.entries(e)){if(!Hr.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!W(s)){n.push(`actions.${o} must be an object`);continue}let a=ff(s.code);if(!a||a.length===0){n.push(`actions.${o}.code must name at least one TypeScript referent`);continue}for(let m of a){let g=Go(m);"error"in g&&n.push(`actions.${o}.code: ${g.error}`)}let c=X(s.reads)??[],l=X(s.writes)??[],d=X(s.calls)??[];for(let m of[...c,...l])r.has(m)||n.push(`actions.${o} references unknown variable: ${m}`);let u=O$(s.waive,s.allowUnknown===!0,c,l,r,o,n);i[o]={code:a,reads:c,writes:l,calls:d,...u?{waive:u}:{}}}return i}function O$(e,t,n,r,i,o,s){if(W(e)){let a=typeof e.reason=="string"?e.reason.trim():"";a||s.push(`actions.${o}.waive.reason must be a non-empty string`);let c=X(e.reads)??[],l=X(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${o}.waive must list reads or writes`),nf(o,"reads",c,i,s),nf(o,"writes",l,i,s),{reads:[...new Set(c)],writes:[...new Set(l)],reason:a}}if(e!==void 0&&s.push(`actions.${o}.waive must be an object when present`),t)return{reads:[...new Set(n)],writes:[...new Set(r)],reason:"legacy allowUnknown",legacy:!0}}function nf(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function D$(e){let t=new Set;for(let n of e.matchAll(/^\s*VARIABLES?\s+([^\n]+)/gm)){let r=n[1]??"";for(let i of r.split(",")){let o=i.trim();Hr.test(o)&&t.add(o)}}return[...t].sort()}function F$(e){let t=new Set;for(let n of e.matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?:\([^)]*\))?\s*==/gm))t.add(n[1]);return[...t].sort()}var M$=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function mf(e){if(!e||!Xe(e))return[];let t=yt(e,"utf8").replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,r=!1;for(let i of t.split(/[\s,]+/))if(i){if(M$.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&Hr.test(i)&&n.add(i)}return[...n].sort()}function rf(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function ff(e){return typeof e=="string"?[e]:X(e)}function N$(e,t){e!==void 0&&(X(e)||t.push("scope must be an array of strings when present"))}function Gr(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var _$=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function gf(e,t){if(!Xe(t))return{status:"none"};let r=yt(t,"utf8").match(_$)?.[1],i=y$(e,t).split(b$).join("/"),o=g$(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(d=>!!d)),a=of(t);if(!Xe(a))return{status:"none"};let c=[];for(let d of f$(a)){if(!d.endsWith(".scip-tla.json"))continue;let u=h$(a,d),m;try{m=JSON.parse(yt(u,"utf8"))}catch{continue}W(m)&&typeof m.module=="string"&&s.has(m.module)&&c.push(u)}c.sort();let l=r??i;return c.length===0?{status:"none"}:c.length>1?{status:"ambiguous",candidates:c,moduleName:l}:{status:"found",mapPath:c[0],moduleName:l}}function Jr(e,t,n,r,i={count:e.length,loc:r}){let o=i.count===e.length&&i.loc===r?`${e.length}, ${r} LOC`:`${e.length} of ${i.count}, ${r} of ${i.loc} LOC`;console.log(`\u2550\u2550\u2550 ${t} (${o}) \u2550\u2550\u2550`),console.log(n),console.log("");let s=new Map;for(let l of e){let d=s.get(l.relativePath)??[];d.push(l),s.set(l.relativePath,d)}let a=[...s.entries()].map(([l,d])=>({file:l,bucket:d,totalLoc:d.reduce((u,m)=>u+m.loc,0)})).sort((l,d)=>d.totalLoc-l.totalLoc||l.file.localeCompare(d.file)),c=!0;for(let{file:l,bucket:d}of a){c||console.log(""),c=!1,console.log(` ${l}`),d.sort((u,m)=>u.startLine-m.startLine);for(let u of d){let m=u.implicitUsageReason?` [implicit usage: ${u.implicitUsageReason}]`:"";console.log(` ${ae(u.startLine,u.endLine)} (${u.loc} LOC) ${u.shortName}${m}`)}}}var Ko=20,hf=Z("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:H(t,0)||void 0,minLoc:P(n,"minLoc",1),includeTests:S(n,"includeTests"),skipBarrels:S(n,"skipBarrels"),includeMembers:S(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=sa(e,i),s=o.symbols.filter(N=>N.kind==="dead-code"),a=o.symbols.filter(N=>N.kind==="file-internal"),c=o.symbols.filter(N=>N.kind==="implicit-usage"),l=!S(n,"onlyInternal"),d=!S(n,"onlyDead"),u=!S(n,"onlyDead")&&!S(n,"onlyInternal"),m=l?s:[],g=d?a:[],f=u?c:[],h=m.reduce((N,G)=>N+G.loc,0),b=g.reduce((N,G)=>N+G.loc,0),y=f.reduce((N,G)=>N+G.loc,0),v=S(n,"full"),R=v?m:m.slice(0,Ko),T=v?g:g.slice(0,Ko),D=v?f:f.slice(0,Ko),C=R.reduce((N,G)=>N+G.loc,0),U=T.reduce((N,G)=>N+G.loc,0),j=D.reduce((N,G)=>N+G.loc,0),M={total:m.length+g.length+f.length,deadCode:m.length,fileInternal:g.length,implicitUsage:f.length,loc:h+b+y};if(S(n,"json")){E("dead",t,n,{...o,shown:{deadCode:m,fileInternal:g,implicitUsage:f},shownCounts:M,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,implicitUsage:o.counts.implicitUsage,loc:o.counts.loc}},{analysisBudget:r.analysisBudget});return}if(m.length===0&&g.length===0&&f.length===0){A.empty("No matching dead-code symbols found.");return}m.length>0&&(Jr(R,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
408
- Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,C,{count:m.length,loc:h}),!v&&m.length>R.length&&console.log(`
409
- Showing top ${R.length} by LOC. Re-run with --full for the remaining ${m.length-R.length}.`)),g.length>0&&(m.length>0&&console.log(""),Jr(T,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
410
- single-use helper, an abstraction-in-progress, or a callback registered
411
- through a framework path that static analysis cannot trace (signal
412
- handlers, event listeners, dependency injection). NOT necessarily dead \u2014
413
- review case by case.`,U,{count:g.length,loc:b}),!v&&g.length>T.length&&console.log(`
414
- Showing top ${T.length} by LOC. Re-run with --full for the remaining ${g.length-T.length}.`)),f.length>0&&((m.length>0||g.length>0)&&console.log(""),Jr(D,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
415
- consumer that the static reference graph cannot trace. Investigation
416
- signals only \u2014 not deletion candidates and not counted as dead code.`,j,{count:f.length,loc:y}),!v&&f.length>D.length&&console.log(`
417
- Showing top ${D.length} by LOC. Re-run with --full for the remaining ${f.length-D.length}.`));let K=[];l&&K.push(`${m.length} dead code (${h} LOC)`),d&&K.push(`${g.length} file-internal (${b} LOC)`),u&&K.push(`${f.length} implicit usage (${y} LOC)`),console.log(`
418
- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${m.length+g.length+f.length} symbols \u2014 ${K.join(" + ")}`)}),yf=fe("unused-imports",{query:({db:e,args:t,budget:n})=>da(e,O(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
419
- ${e.length} unused import(s)`)}),bf=gl("isolated",{query:({db:e,opts:t,budget:n})=>Ra(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ae(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
420
- ${e.length} isolated symbol(s)`)}),Sf=Z("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Ma(e,{scope:w(n,"scope"),minLoc:P(n,"minLoc",10),minCallees:P(n,"minCallees",6),limit:F(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(S(n,"json")){E("extract-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return A.empty("No extraction candidates found.");Ae("extraction candidates");for(let o of i){console.log(`
421
- ${V(o.relativePath,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC, ${o.totalCallees} callees)`),console.log(` Kind: ${o.extractionKind}; tier: ${o.actionTier}`),console.log(` Recommendation: ${o.recommendation}`);for(let s of o.evidenceReasons)console.log(` - ${s}`);for(let s=0;s<o.clusters.length;s++){let a=o.clusters[s];console.log(` Cluster ${s+1} (${Math.round(a.isolation*100)}% isolated, ${a.callees.length} callees):`);for(let c of a.callees)console.log(` ${c}`)}}console.log(`
422
- ${i.length} extraction candidate(s) found.`)}),vf=Z("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Na(e,{target:H(t,0)||void 0,scope:w(n,"scope"),minConsumers:P(n,"minConsumers",1),limit:F(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(S(n,"json")){E("locality-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return A.empty("No locality candidates found.");Ae("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?V(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
423
- ${s} ${o.sourceUnit.shortName}`),console.log(` Current directory: ${o.currentDirectory}; tier: ${o.recommendedTier}; action: ${o.actionTier}`),console.log(` Consumer coverage: ${o.consumerCoverage}; consumers: ${o.consumerFiles.length}`),o.nearestCommonOwner&&console.log(` Nearest common owner: ${o.nearestCommonOwner}`),o.suggestedHome&&console.log(` Suggested home: ${o.suggestedHome}`),o.whyNoSuggestedHome&&console.log(` Suggested home withheld: ${o.whyNoSuggestedHome}`),o.boundaryMarkers.length>0&&console.log(` Boundary markers: ${o.boundaryMarkers.join("; ")}`),console.log(` Recommendation: ${o.recommendation}`),o.consumerFiles.length>0){for(let a of o.consumerFiles.slice(0,8))console.log(` - consumer: ${a}`);o.consumerFiles.length>8&&console.log(` - ... ${o.consumerFiles.length-8} more consumer(s)`)}for(let a of o.counterevidence)console.log(` - counterevidence: ${a}`)}console.log(`
424
- ${i.length} locality candidate(s) found.`)}),Rf=fe("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>Qa(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:F(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
425
- Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
426
- Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
427
- ${e.length} wrapper candidate(s).`)}),xf=fe("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>za(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:F(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
428
- Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
429
- Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
430
- Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
431
- Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
432
- ${e.length} passthrough candidate(s).`)}),kf=fe("stale-abstractions",{query:({db:e,opts:t,budget:n})=>Ka(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),limit:F(t,"limit",30),includeLowConfidence:S(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
433
- ${e.reason}
434
- Kind: ${e.stalenessKind}; tier: ${e.actionTier}
435
- Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
436
- ${e.length} stale abstraction(s).`)}),wf=er("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>bc(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",10),limit:F(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.score.toFixed(1).padStart(5)} ${String(e.loc).padStart(4)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${String(e.calleeCount).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No complexity hotspots found.",heuristicLabel:"complexity hotspot candidates",dashWidths:[5,4,6,7,7,6]}),$f=ke("similar",{query:({db:e,args:t,opts:n,budget:r})=>{if(S(n,"plan")){let o=H(t,0),s=H(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:Pa(e,o,s,{scanLimit:r.scanLimit,semantic:r.semantic})}}let i=H(t,0);return i?{mode:"target",rows:Ca(e,i,{minSimilarity:P(n,"minSimilarity",.4),limit:F(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Ta(e,{minSimilarity:P(n,"minSimilarity",.4),limit:F(n,"limit",20),scope:w(n,"scope"),minCallees:P(n,"minCallees",4),crossFileOnly:S(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.semantic})}},emptyMessage:e=>{if(e.mode==="plan")return e.result?void 0:"No similarity evidence found for that pair.";if(!(e.rows.length>0))return e.mode==="target"?"No similar symbols found.":"No similar symbol pairs found."},heuristicLabel:"similarity candidates",render:e=>{if(e.mode==="plan"){let t=e.result;if(!t)return;let n=t.similarityBasis==="source-tokens"?"source-token overlap":"weighted callee overlap";console.log(`
437
- ${Math.round(t.similarity*100)}% ${n}
438
- `),console.log(` A: ${t.symbolA.shortName} (${t.symbolA.file}, ${t.symbolA.loc} LOC)`),console.log(` B: ${t.symbolB.shortName} (${t.symbolB.file}, ${t.symbolB.loc} LOC)`),console.log(` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`),console.log(` Recommendation: ${t.recommendation}
439
- `),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let r of t.sharedEvidence)console.log(` ${r}`);if(t.uniqueToA.length>0){console.log(`
440
- Unique to A (${t.uniqueToA.length}):`);for(let r of t.uniqueToA)console.log(` ${r}`)}if(t.uniqueToB.length>0){console.log(`
441
- Unique to B (${t.uniqueToB.length}):`);for(let r of t.uniqueToB)console.log(` ${r}`)}console.log(`
442
- Strategy: ${t.consolidationStrategy}`);return}if(e.mode==="target"){A.list(e.rows,t=>{let n=t.similarityBasis??"callees",r=n==="source-tokens"?"Shared source tokens":"Shared callees",i=n==="source-tokens"?"Only tokens in":"Only in",o=[`
443
- ${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${r}: ${t.sharedCallees.join(", ")}`];return t.evidenceClassReasons.length&&o.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.uniqueToA.length&&o.push(` ${i} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${i} B: ${t.uniqueToB.join(", ")}`),o.join(`
444
- `)});return}A.list(e.rows,t=>`
445
- ${Math.round(t.similarity*100)}% similar:
446
- A: ${t.shortNameA} (${t.fileA})
447
- B: ${t.shortNameB} (${t.fileB})
448
- Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})
449
- Recommendation: ${t.recommendation}
450
- `+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
451
- `:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
452
- ${e.rows.length} similar pair(s) found.`)}}),Cf=et({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Ia(e,{minSimilarity:P(n,"minSimilarity",.5),limit:F(n,"limit",20),scope:w(n,"scope"),minDeps:Q(n,"minDeps"),filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{A.list(e,t=>{let n=[`
453
- ${Math.round(t.similarity*100)}% similar:`,` ${t.fileA}`,` ${t.fileB}`,` Shared deps (${t.sharedDeps.length}): ${t.sharedDeps.join(", ")}`];return t.uniqueToA.length&&n.push(` Only in first: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&n.push(` Only in second: ${t.uniqueToB.join(", ")}`),n.join(`
454
- `)}),console.log(`
455
- ${e.length} similar pair(s) found.`)}}),Pf=et({commandName:"similar-chains",query:({db:e,opts:t})=>Fa(e,{minSimilarity:P(t,"minSimilarity",.5),limit:F(t,"limit",15),scope:w(t,"scope"),minChainLength:P(t,"minLength",3),maxChainLength:P(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
456
- \u2500\u2500 Chain pair ${t+1} (${Math.round(n.similarity*100)}% similar, ${n.divergencePoints.length} divergence point(s)) \u2500\u2500`),console.log(` Chain A: ${n.chainA.join(" \u2192 ")}`),console.log(` Chain B: ${n.chainB.join(" \u2192 ")}`),n.commonPrefix.length&&console.log(` Common prefix: ${n.commonPrefix.join(" \u2192 ")}`),n.commonSuffix.length&&console.log(` Common suffix: ${n.commonSuffix.join(" \u2192 ")}`),console.log(" Divergence points (consolidation targets):");for(let r of n.divergencePoints)console.log(` [${r.index}] ${r.nodeA} \u2194 ${r.nodeB}`)}console.log(`
457
- ${e.length} similar chain pair(s) found.`)}}),Tf=ke("drift",{query:({db:e,args:t,opts:n,budget:r})=>Ja(e,{scope:H(t,0),minDeviation:P(n,"minDeviation",5),semantic:r.semantic,includePatternDeviations:S(n,"patterns"),includeArchitecture:S(n,"architecture"),limit:F(n,"limit",50)}),emptyMessage:e=>e.results.length===0&&!e.architecture?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{if(console.log(""),A.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="architecture-violation"||t.kind==="layer-violation"?"ARCH":"UNIQUE",r=t.policyBasis?`, policy: ${t.policyBasis}`:"",i=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${r}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&i.push(` ${t.detail}`),i.join(`
458
- `)},t=>t.file),e.architecture){let t=e.architecture,n=t.edges.filter(r=>r.policyStatus==="undeclared").length;if(console.log(`
459
- Architecture context: ${t.coverage.mappedFiles}/${t.coverage.totalFiles} file(s) mapped; ${t.policyCoverage.declaredRows}/${t.policyCoverage.totalBoundaries} dependency row(s) declared; ${n} undeclared boundary edge(s).`),t.reciprocalPairs.length>0){console.log(` Reciprocal pairs (${t.reciprocalPairs.length}):`);for(let r of t.reciprocalPairs)console.log(` ${r.boundaries[0]} <-> ${r.boundaries[1]}`)}if(t.cycles.length>0){console.log(` Connected boundary groups (${t.cycles.length}):`);for(let r of t.cycles){let i=r.violatesPolicy?" [violates requireAcyclic]":" [signal]";console.log(` { ${r.boundaries.join(", ")} }${i}`)}}}console.log(`
460
- ${e.unusedImports} unused import(s), ${e.architectureViolations} declared architecture violation(s), ${e.patternDeviations} pattern deviation(s)${e.totalResults?` \u2014 showing ${e.results.length} of ${e.totalResults} (use -n to change)`:""}`)}}),If=ke("convergence",{query:({db:e,args:t,budget:n})=>Pc(e,O(t,0),O(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols did not resolve, or the pair has no fingerprint evidence (small helpers with few callees fall below the similarity threshold; try --min-callees 1).",render:e=>{if(e){console.log("\nDeprecated: use `similar <symbol1> <symbol2> --plan` for the same weighted similarity basis."),console.log(`
461
- ${Math.round(e.similarity*100)}% callee overlap
462
- `),console.log(` A: ${e.symbolA.shortName} (${e.symbolA.file}, ${e.symbolA.loc} LOC)`),console.log(` B: ${e.symbolB.shortName} (${e.symbolB.file}, ${e.symbolB.loc} LOC)
463
- `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
464
- Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
465
- Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
466
- Strategy: ${e.consolidationStrategy}`)}}}),Ef=fe("similar-signatures",{query:({db:e,opts:t,budget:n})=>Ec(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),maxShapeFrequency:P(t,"maxShapeFrequency",12),limit:F(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
467
- Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,r=e.functions.map(i=>` ${V(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
468
- `);return`${n}
469
- ${r}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
470
- ${e.length} group(s) found.`)}),jf=fe("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>Ua(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),minLoc:P(t,"minLoc",3),limit:F(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
471
- Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((r,i)=>` ${(i===0?"canonical":"duplicate").padEnd(9)} ${V(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
472
- `);return`${t}
473
- ${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>console.log(`
474
- ${e.length} group(s) found.`)}),Af=fe("twin-drift",{query:({db:e,opts:t,budget:n})=>Ga(e,{scope:w(t,"scope"),minSimilarity:P(t,"minSimilarity",.3),includeHomonyms:S(t,"includeHomonyms"),limit:F(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
475
- ${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(i=>` ${V(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
476
- `),r=e.firstDivergentTokens?`
477
- first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
478
- ${n}${r}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
479
- ${e.length} group(s) found.`)}),Lf=fe("not-implemented",{query:({db:e,opts:t,budget:n})=>dc(e,{scope:w(t,"scope"),limit:F(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
480
- ${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
481
- ${e.length} reachable placeholder stub(s).`)}),Of=fe("decorative-checkers",{query:({db:e,opts:t,budget:n})=>uc(e,{scope:w(t,"scope"),limit:F(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.nameKind}, resolved: ${e.resolvedVia}${e.delegateTarget?` -> ${e.delegateTarget}`:""})`,emptyMessage:()=>"No decorative checker candidates found.",heuristicLabel:"decorative checker candidates",after:e=>console.log(`
482
- ${e.length} decorative checker candidate(s).`)}),Df=Z("test-quality",({db:e,args:t,opts:n,budget:r})=>{let i=pc(e,{scope:w(n,"scope"),limit:F(n,"limit",30),scanLimit:r.scanLimit,rotDays:Q(n,"rotDays")});if(S(n,"json")){E("test-quality",t,n,i,{analysisBudget:r.analysisBudget});return}if(Ae("test-quality findings"),i.assertionFree.length+i.skipped.length+i.mockEcho.length===0){A.empty("No test-quality findings.");return}i.assertionFree.length>0&&(console.log(`
483
- ASSERTION-FREE (${i.assertionFree.length})`),A.list(i.assertionFree,s=>` ${V(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),i.skipped.length>0&&(console.log(`
484
- SKIPPED (${i.skipped.length})`),A.list(i.skipped,s=>` ${s.file}:${s.startLine+1} "${s.title}" (${s.blockKind}.${s.skipKind}, age: ${s.ageDays??"unknown"}d, ${s.rot})`)),i.mockEcho.length>0&&(console.log(`
485
- MOCK-ECHO (${i.mockEcho.length})`),A.list(i.mockEcho,s=>` ${V(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
486
- ${i.assertionFree.length} assertion-free, ${i.skipped.length} skipped, ${i.mockEcho.length} mock-echo.`)}),Ff=et({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let r=O(t,0),i=O(t,1),o=w(n,"out")??cc(r,i),s=ge(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=lc(e,r,i,s);if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=H$(e.config.projectRoot,s);if(!S(n,"force")&&B$(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return q$(W$(s),{recursive:!0}),V$(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
487
- Wrote behavioral A/B scaffold: ${e.outPath}`),console.log(` A: ${e.a.shortName} (${V(e.a.file,e.a.startLine,e.a.startLine)})`),console.log(` B: ${e.b.shortName} (${V(e.b.file,e.b.startLine,e.b.startLine)})`);let t=e.signatureCompatible===null?"unknown":e.signatureCompatible?"compatible":"MISMATCH";console.log(` Signature compatibility: ${t}`),console.log(`
488
- Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),Mf=Z("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=mi(e,{scope:w(n,"scope"),minLoc:P(n,"minLoc",1),maxDepth:P(n,"maxDepth",5),scanLimit:r.scanLimit}),o=te(),s=S(n,"patch"),a=S(n,"json"),c=S(n,"verify")||s;if(s&&!S(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){E("cleanup-plan",t,n,i,{analysisBudget:r.analysisBudget});return}return A.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=Ti(i),d=c?$i(o,i):void 0;if(a){E("cleanup-plan",t,n,{result:i,verification:d},{analysisBudget:r.analysisBudget});return}if(s){let u=Ii(d,l);if(u.length>0){for(let g of u)console.error(`error: ${g}`);process.exitCode=1;return}let m=Fl(o,l);if(m.trim()===""){console.error("error: verified cleanup plan produced an empty patch."),process.exitCode=1;return}console.error(`cleanup-plan --patch: ${l.length} verified batch(es), ${i.totalLoc} LOC.`),console.log(m);return}console.log(`Cleanup plan: ${i.totalSymbols} symbol(s), ${i.totalLoc} LOC across ${i.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
489
- `);for(let u of i.batches){let m=u.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${u.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${u.depth}: dead once batch ${u.depth-1} lands (cascade, ${u.loc} LOC) \u2500\u2500`;console.log(m);for(let g of u.entries)console.log(` ${g.file}:${g.startLine+1}-${g.endLine+1} ${g.shortName} (${g.loc} LOC)`);u.filesEmptied.length>0&&console.log(` -> empties: ${u.filesEmptied.join(", ")}`),console.log("")}if(i.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let u of i.blocked)console.log(` ${u.shortName} (${u.file}) blocked by ${u.blockingFiles.join(", ")}`)}if(d){if(console.log(`
490
- Verifying batches against the project checker (throwaway worktree at HEAD)...`),d.checkers.length===0){console.log(" No checker detected (need tsconfig.json, go.mod, Python project markers, Clojure project markers, or Cargo.toml) -- skipped.");return}for(let g of d.checkers)console.log(` Checker: ${g}`);if(d.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${d.uncoveredFiles.join(", ")}`),d.baselineErrors>0&&console.log(` Baseline has ${d.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),d.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${d.dirtyOverlap.join(", ")}`),d.dirtyWorkingTree.length>0){let g=d.dirtyWorkingTree.slice(0,5),f=d.dirtyWorkingTree.length-g.length;console.log(` WARNING: verification ran at HEAD; ${d.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${g.join(", ")}${f>0?`, ... ${f} more`:""}`)}let u=U$(d.checkers),m=G$(d.checkers);for(let g of d.batches)if(g.status==="verified")console.log(` Batch ${g.depth}: VERIFIED (${u})${m}`);else{console.log(` Batch ${g.depth}: FAILED${g.reason?` (${g.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let f of g.errors??[])console.log(` ${f}`)}}}),Nf=Z("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!S(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let r=S(t,"all"),i=Q(t,"batch");if(r===(i!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=mi(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",1),maxDepth:P(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){A.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=Ti(o,{all:r,batch:i});if(s.length===0){console.error(`error: No cleanup batch ${i} exists.`),process.exitCode=1;return}let a=te(),c=$i(a,o),l=Ii(c,s,{allowDirty:S(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}Pi(a,s);let d=s.reduce((m,g)=>m+g.entries.length,0),u=s.reduce((m,g)=>m+g.loc,0);console.log(`Applied ${s.length} verified cleanup batch(es): ${d} symbol(s), ${u} LOC.`)});function U$(e){return e.join(", ")}function G$(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var _f=Z("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=S(n,"full"),o=mc(e,{windowCommits:P(n,"window",100),minSimilarity:Q(n,"minSimilarity"),limit:F(n,"limit",30),scope:w(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic,historyMode:i?"full":"bounded"});if(S(n,"json")){E("recent-duplicates",t,n,o,{analysisBudget:r.analysisBudget});return}if(!o.available)return A.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return A.empty(`No recent re-implementations found (window: last ${o.windowCommits} commits).`);Ae("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
491
- `);let s=o.rootCauseGroups?.filter(a=>a.count>1)??[];if(s.length>0){console.log(`Root-cause groups (${s.length}):`);for(let a of s)console.log(` ${a.count} pair(s) ${a.kind.toUpperCase()} ${a.domain} ${Math.round(a.maxSimilarity*100)}% max`),a.establishedFile&&a.establishedSymbol&&console.log(` established: ${a.establishedFile} ${a.establishedSymbol}`),console.log(` files: ${a.relatedFiles.slice(0,6).join(", ")}`),console.log(` -> ${a.recommendation}`);console.log("")}for(let a of o.findings){let c=a.sharedEvidence.slice(0,16).join(", ");a.kind==="echo"?(console.log(` ${Math.round(a.similarity*100)}% ECHO ${a.domain} ${a.echoFile} ${a.echoSymbol} (added ${a.echoAgeCommits} commits ago)`),console.log(` duplicates established ${a.establishedFile} ${a.establishedSymbol}`)):(console.log(` ${Math.round(a.similarity*100)}% TWIN ${a.domain} ${a.echoFile} ${a.echoSymbol}`),console.log(` and ${a.establishedFile} ${a.establishedSymbol} (both new \u2014 consolidate before they diverge)`)),console.log(` basis: ${a.basis}`),c.length>0&&console.log(` shared: ${c}`)}console.log(`
492
- ${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Bf=me(({db:e,args:t,opts:n})=>{let r=S(n,"full"),i=Ha(e,{doc:t[0]===void 0?void 0:O(t,0),limit:F(n,"limit",20),minCoupling:P(n,"minCoupling",3),includeSnapshotExcluded:r,historyMode:r?"full":"bounded"});if(S(n,"json")){E("doc-drift",t,n,i);return}if(!i.available)return A.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return A.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);Ae("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
493
- `);for(let o of i.findings){let s=o.snapshotExcluded?" [snapshot (excluded by policy)]":"",a=o.docLastChangedAtEstimated?" [docLastChangedAt estimated from file mtime]":"";console.log(` staleness ${o.staleness} ${o.doc}${s}${a}`);for(let c of o.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${c} \u2014 that file no longer exists`);for(let c of o.subjects.slice(0,4)){let l=c.evidence==="both"?`referenced by doc + coupled ${c.coChanges}x`:c.evidence==="reference"?"referenced by doc":`coupled ${c.coChanges}x historically`;console.log(` ${c.changesSinceDocUpdate} change(s) since doc update ${c.file} (${l}; ${c.actionTier}/${c.docIntent})`);let d=c.docIntentReasons[0];d&&console.log(` intent: ${d}`);let u=c.citationContexts?.[0];u&&console.log(` cited claim: ${Yn(u)}`)}}console.log(`
494
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),qf=fe("unused-params",{query:({db:e,opts:t,budget:n})=>ec(e,{scope:w(t,"scope"),limit:F(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName}
495
- trailing unused: ${e.unusedTrailing.join(", ")} (${e.unusedTrailing.length} of ${e.paramCount} params -- type-safe to remove at the signature; check call sites for side-effectful arguments)`,emptyMessage:()=>"No trailing unused parameters found.",heuristicLabel:"unused trailing parameter candidates",after:e=>console.log(`
496
- ${e.length} function(s) with trailing unused parameters.`)});var Vf=ke("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Ea(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:F(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{A.list(e,t=>{let n=[`
497
- ${Math.round(t.similarity*100)}% similar React structure:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedNativeTags.length&&n.push(` Shared native tags: ${t.sharedNativeTags.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),n.join(`
498
- `)}),console.log(`
499
- ${e.length} duplicated React component pair(s) found.`)}}),Wf=ke("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>ja(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:F(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{A.list(e,t=>{let n=[`
500
- ${Math.round(t.similarity*100)}% similar React behavior:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedHooks.length&&n.push(` Shared hooks: ${t.sharedHooks.join(", ")}`),t.sharedReactHooks.length&&n.push(` Shared React hooks: ${t.sharedReactHooks.join(", ")}`),t.sharedEffects.length&&n.push(` Shared effects: ${t.sharedEffects.join(", ")}`),t.sharedState.length&&n.push(` Shared state: ${t.sharedState.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedHandlers.length&&n.push(` Shared handlers: ${t.sharedHandlers.slice(0,12).join(", ")}`),t.sharedHandlerVerbs.length&&n.push(` Shared action verbs: ${t.sharedHandlerVerbs.slice(0,12).join(", ")}`),n.join(`
501
- `)}),console.log(`
502
- ${e.length} React hook candidate pair(s) found.`)}}),Hf=ke("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Aa(e,{minComponentLines:P(n,"minComponentLines",300),minFileLines:P(n,"minFileLines",800),minJsxTokens:P(n,"minJsxTokens",80),minBehaviorTokens:P(n,"minBehaviorTokens",40),limit:F(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{A.list(e,t=>[`
503
- ${t.componentLines} component line(s): ${t.component} (${t.file})`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` File lines: ${t.fileLines}; JSX tokens: ${t.jsxTokens}; behavior tokens: ${t.behaviorTokens}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`,` Reasons: ${t.reasons.join("; ")}`].join(`
504
- `)),console.log(`
505
- ${e.length} large React component(s) found.`)}}),Uf=ke("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>La(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:F(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{A.list(e,t=>{let n=[`
506
- ${Math.round(t.similarity*100)}% similar Vue structure:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedDirectives.length&&n.push(` Shared directives: ${t.sharedDirectives.join(", ")}`),t.sharedSlots.length&&n.push(` Shared slots: ${t.sharedSlots.join(", ")}`),t.sharedIdentifiers.length&&n.push(` Shared identifiers: ${t.sharedIdentifiers.slice(0,20).join(", ")}`),n.join(`
507
- `)}),console.log(`
508
- ${e.length} duplicated Vue component pair(s) found.`)}}),Gf=ke("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Oa(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:F(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{A.list(e,t=>{let n=[`
509
- ${Math.round(t.similarity*100)}% similar Vue behavior:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComposables.length&&n.push(` Shared composables: ${t.sharedComposables.join(", ")}`),t.sharedStores.length&&n.push(` Shared stores: ${t.sharedStores.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedLifecycle.length&&n.push(` Shared lifecycle: ${t.sharedLifecycle.join(", ")}`),t.sharedFunctions.length&&n.push(` Shared functions: ${t.sharedFunctions.slice(0,12).join(", ")}`),t.sharedFunctionVerbs.length&&n.push(` Shared action verbs: ${t.sharedFunctionVerbs.slice(0,12).join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),t.sharedTemplateEvents.length&&n.push(` Shared template events: ${t.sharedTemplateEvents.slice(0,20).join(", ")}`),n.join(`
510
- `)}),console.log(`
511
- ${e.length} Vue composable candidate pair(s) found.`)}}),Jf=ke("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Da(e,{minTotalLines:S(n,"reviewThresholds")&&hl(n,"minTotalLines")==="default"?300:P(n,"minTotalLines",800),minTemplateLines:P(n,"minTemplateLines",300),minScriptLines:P(n,"minScriptLines",300),minStyleLines:P(n,"minStyleLines",500),limit:F(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{A.list(e,t=>{let n=[`
512
- ${t.totalLines} total line(s): ${t.file}`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` Blocks: template ${t.templateLines}, script ${t.scriptLines}, style ${t.styleLines}, external script ${t.externalScriptLines}, custom ${t.customBlockLines}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`];return t.externalScriptPaths.length&&n.push(` External scripts: ${t.externalScriptPaths.join(", ")}`),n.push(` Reasons: ${t.reasons.join("; ")}`),n.join(`
513
- `)}),console.log(`
514
- ${e.length} large Vue view pressure file(s) found.`)}});function se(e){return{docs:$("Cleanup"),...e}}function ne({heuristicLabel:e,...t}){return se({...t,heuristic:{label:e}})}var zr=[se({id:"unused-params",command:"unused-params",agent:k("Which trailing parameters are never read by their bodies?","candidate parameters with callable and file identities",[],"bounded","repository"),description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:I([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings",x,30),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:$("Cleanup",["scip-query unused-params -s src/services"]),handler:qf}),se({id:"cleanup-plan",command:"cleanup-plan",agent:k("What code can be deleted safely, and in what dependency order?","ordered cleanup batches, evidence, and optional verification outcomes",[],"bounded","repository"),description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",x,1),p("--max-depth <n>","Maximum cascade depth",x,5),p("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),p("--patch","With --verify, print the compiler-verified deletion patch to stdout"),p("--json","Output as JSON for programmatic consumption"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:Mf}),se({id:"cleanup-apply",command:"cleanup-apply",agent:k("Can a compiler-verified cleanup batch be applied to this working tree?","applied files, deletions, verification, and refusal reasons",[],"bounded","repository"),description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",x,1),p("--max-depth <n>","Maximum cascade depth",x,5),p("--verified","Required: verify the selected cleanup batch before applying it"),p("--batch <n>","Apply one batch depth",x),p("--all","Apply every compiler-verified batch in the plan"),p("--force-dirty","Allow applying when plan files already have working-tree edits"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:Nf}),se({id:"recent-duplicates",command:"recent-duplicates",agent:k("Did recent code reimplement established code?","recent and established symbol pairs with similarity evidence",[],"bounded","repository"),description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:I([p("--window <n>",'How many commits back counts as "recent"',x,100),p("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",Se),p("-n, --limit <n>","Maximum findings",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:$("Cleanup",["scip-query recent-duplicates --window 50"]),handler:_f}),se({id:"doc-drift",command:"doc-drift [doc]",agent:k("Which documentation may be stale relative to changing code?","document paths, coupled code subjects, and history evidence",["path"],"bounded","repository"),description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:I([p("-n, --limit <n>","Maximum docs to report",x,20),p("--min-coupling <n>","Minimum historical co-changes to track a subject",x,3),p("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:$("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Bf}),se({id:"dead",command:"dead [scope]",agent:k("Which symbols have no repository use or only file-internal use?","symbol identities, ranges, liveness classes, and evidence",["path"],"bounded","repository"),description:"Find repository-dead code, file-internal symbols, and implicit-usage signals",options:I([p("--min-loc <n>","Only show symbols >= N lines",x,1),p("--include-tests","Include definitions from test files (test references always count)"),p("--skip-barrels","Ignore refs from barrel re-export files"),p("--include-members","Include class members"),p("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),p("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query dead --min-loc 10"]),handler:hf}),se({id:"unused-imports",command:"unused-imports <file>",agent:k("Which imports in this file are unused?","import symbol identities and source ranges",["file"],"bounded"),description:"Find imports not referenced in the same file",options:I([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:yf}),se({id:"isolated",command:"isolated",agent:k("Which symbols are disconnected from the repository reference graph?","isolated symbol identities and files",[],"bounded","repository"),description:"Find completely orphaned symbols (no references at all)",options:I([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum lines of code",x,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:bf}),ne({id:"similar",command:"similar [symbol] [other]",agent:k("Which callable resembles this one, or how similar are these two?","symbol pairs, similarity scores, and shared evidence",["symbol","symbol"],"bounded","repository"),description:"Find heuristic function similarity candidates from callee fingerprints",options:I([p("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",Se,.4),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-callees <n>","Minimum callees to consider",x,4),p("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),p("--plan","Render a consolidation preview for two symbols"),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:$f}),ne({id:"similar-files",command:"similar-files [file]",agent:k("Which files have similar callable structure?","file pairs with similarity scores and shared symbols",["file"],"bounded","repository"),description:"Find heuristic similar-file candidates from dependency profiles",options:I([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",Se,.5),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-deps <n>","Minimum dependencies to consider",x),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Cf}),ne({id:"react-component-duplicates",command:"react-component-duplicates [file]",agent:k("Which React components appear to duplicate one another?","component pairs with structural similarity evidence",["file"],"bounded","repository"),description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:I([p("--min-similarity <n>","Minimum JSX structure similarity (0-1)",Se,.62),p("--min-tokens <n>","Minimum structural tokens to consider",x,8),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Vf}),ne({id:"react-hook-candidates",command:"react-hook-candidates [file]",agent:k("Which repeated React logic could become a custom hook?","component groups and shared hook-shaped behavior",["file"],"bounded","repository"),description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:I([p("--min-similarity <n>","Minimum behavior similarity (0-1)",Se,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Wf}),ne({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",agent:k("Which React components have evidence of being too large or overloaded?","component identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:I([p("--min-component-lines <n>","Minimum component lines",x,300),p("--min-file-lines <n>","Minimum file lines",x,800),p("--min-jsx-tokens <n>","Minimum JSX structure tokens",x,80),p("--min-behavior-tokens <n>","Minimum behavior tokens",x,40),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Hf}),ne({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",agent:k("Which Vue components appear to duplicate one another?","component pairs with structural similarity evidence",["file"],"bounded","repository"),description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:I([p("--min-similarity <n>","Minimum template similarity (0-1)",Se,.62),p("--min-tokens <n>","Minimum structural tokens to consider",x,8),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Uf}),ne({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",agent:k("Which repeated Vue logic could become a composable?","component groups and shared composable-shaped behavior",["file"],"bounded","repository"),description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:I([p("--min-similarity <n>","Minimum behavior similarity (0-1)",Se,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Gf}),ne({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",agent:k("Which Vue views have evidence of being too large or overloaded?","view identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:I([p("--min-total-lines <n>","Minimum total component lines",x,800),p("--min-template-lines <n>","Minimum template lines",x,300),p("--min-script-lines <n>","Minimum script lines",x,300),p("--min-style-lines <n>","Minimum style lines",x,500),p("--review-thresholds","Use lower review thresholds without changing health scoring"),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Jf}),ne({id:"similar-chains",command:"similar-chains",agent:k("Which transitive chains of similar symbols suggest repeated designs?","similarity-connected symbol chains and scores",[],"bounded","repository"),description:"Find heuristic similar-chain candidates from dependency flows",options:I([p("--min-similarity <n>","Minimum chain similarity (0-1)",Se,.5),p("-n, --limit <n>","Number of results",x,15),p("-s, --scope <path>","Limit to files matching path"),p("--min-length <n>","Minimum chain length",x,3),p("--max-length <n>","Maximum chain length",x,8),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Pf}),ne({id:"extract-candidates",command:"extract-candidates",agent:k("Which cohesive code regions are strong extraction candidates?","symbol identities with cohesion, reuse, and extraction evidence",[],"bounded","repository"),description:"Find heuristic extraction candidates from isolated callee clusters",options:I([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum function LOC",x,10),p("--min-callees <n>","Minimum callees to analyze",x,6),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Sf}),ne({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",agent:k("Which definitions live far from most of their consumers?","symbols, current homes, consumer locality, and suggested homes",[["symbol","file"]],"bounded","repository"),description:"Find directory-locality and ancestry candidates from consumer ownership",options:I([p("-s, --scope <path>","Limit scan mode to files matching path"),p("--min-consumers <n>","Minimum consumers in scan mode",x,1),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:vf}),ne({id:"drift",command:"drift [module]",agent:k("Where has a module or abstraction drifted across parallel implementations?","drifted symbol families, files, and evidence",["module"],"bounded","repository"),description:"Detect drift candidates: unused imports and declared architecture violations; pass --architecture for boundary context",options:I([p("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",He,5),p("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),p("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),p("-n, --limit <n>","Number of results",x,50),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:Tf}),ne({id:"wrapper-candidates",command:"wrapper-candidates",agent:k("Which callables are unnecessary forwarding wrappers?","wrapper identities, targets, and forwarding evidence",[],"bounded","repository"),description:"Find heuristic wrapper candidates only called by one consumer (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:I([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",x,15),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:Rf}),ne({id:"passthrough-candidates",command:"passthrough-candidates",agent:k("Which parameters are passed through layers without local use?","parameter paths across call chains",[],"bounded","repository"),description:"Find heuristic passthrough candidates that forward to one callee",options:I([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",x,15),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:xf}),ne({id:"stale-abstractions",command:"stale-abstractions",agent:k("Which abstractions no longer earn their indirection?","abstraction identities with usage, change, and replacement evidence",[],"bounded","repository"),description:"Find heuristic stale abstraction candidates with 0-1 consumers (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:I([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",x,3),p("-n, --limit <n>","Number of results",x,30),p("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:kf}),ne({id:"complexity-hotspots",command:"complexity-hotspots",agent:k("Which symbols combine high complexity with high change pressure?","ranked symbols with complexity and churn evidence",[],"bounded","repository"),description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:I([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",x,10),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:wf}),se({id:"convergence",command:"convergence <symbol1> <symbol2>",agent:k("How should these two similar symbols converge?","deprecated alias result for a two-symbol similarity plan",["symbol","symbol"],"bounded"),evidence:"heuristic",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:I([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:If}),Qm({id:"redundant-reexports",command:"redundant-reexports",agent:k("Which re-exports add no useful API boundary?","re-export sites, original definitions, and consumer evidence",[],"bounded","repository"),description:"Find barrel re-exports that nobody imports through",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded analysis on large indexes")],docs:$("Cleanup"),query:({db:e,opts:t})=>Tc(e,{scope:w(t,"scope"),limit:F(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
515
- barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
516
- Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
517
- Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
518
- ${e.length} redundant re-export(s).`)}),se({id:"duplicate-bodies",command:"duplicate-bodies",agent:k("Which callable bodies are exact duplicates?","callable groups with exact normalized-body identity",[],"bounded","repository"),description:"Find exact duplicate small-body candidates across files",options:I([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC per function body",x,15),p("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",x,3),p("-n, --limit <n>","Number of groups",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:jf}),se({id:"twin-drift",command:"twin-drift",agent:k("Which same-concept twin implementations have drifted?","twin symbol pairs, history, and divergence evidence",[],"bounded","repository"),description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:I([p("-s, --scope <path>","Limit to files matching path"),p("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",Se,.3),p("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),p("-n, --limit <n>","Number of groups",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:Af}),ne({id:"not-implemented",command:"not-implemented",agent:k("Which callables are placeholders rather than real implementations?","callable identities and placeholder evidence",[],"bounded","repository"),description:"Reachable placeholder stub candidates (throw-stub, TODO+return-default, empty body) \u2014 production callers can actually reach these; an unreachable stub is dead's job, not this one's",options:I([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"reachable placeholder stubs",budget:"candidate-scan",renderShape:"list",docs:$("Cleanup",["scip-query not-implemented -s src/services"]),handler:Lf}),ne({id:"decorative-checkers",command:"decorative-checkers",agent:k("Which validation checks cannot meaningfully fail?","checker identities, call sites, and decorative behavior evidence",[],"bounded","repository"),description:"Decorative checker candidates: validate*/verify*/check*/assert*/is*/has* callables with no reachable failure exit anywhere in their body",options:I([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"decorative checker candidates",budget:"candidate-scan",renderShape:"list",docs:$("Cleanup",["scip-query decorative-checkers -s src/services"]),handler:Of}),se({id:"test-quality",command:"test-quality",agent:k("Which tests have weak assertions or poor production-code reach?","test identities with assertion and reachability evidence",[],"bounded","repository"),description:"Test-quality candidates: assertion-free it/test bodies, a skipped-test ledger with git-blame age, and mock-echo tests that assert the same literal they stubbed into a mock",options:I([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings per sub-check",x,30),p("--rot-days <n>","Skips older than this many days are reported as rot",x,60),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"test-quality findings"},renderShape:"custom",docs:$("Cleanup",["scip-query test-quality -s tests/queries"]),handler:Df}),se({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",agent:k("How do these two twin implementations differ in structure and behavior?","side-by-side symbol evidence and divergence classification",["symbol","symbol"],"complete"),description:"Generate a behavioral A/B scaffold comparing two same-concept twins (scip-audit integrity scenario) \u2014 a ready-to-fill vitest file, not an auto-executor",options:I([p("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),p("--force","Overwrite an existing scaffold file at the output path")]),evidence:"heuristic",renderShape:"custom",docs:$("Cleanup",["scip-query twin-ab src/a.ts/escapeRegex src/b.ts/escapeRegExp"]),handler:Ff}),se({id:"similar-signatures",command:"similar-signatures",agent:k("Which callables have suspiciously similar signatures?","callable pairs with signature similarity evidence",[],"bounded","repository"),description:"Find functions with near-identical type signatures (same shape)",options:I([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC per function",x,3),p("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",x,12),p("-n, --limit <n>","Number of groups",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:Ef})];var J$=me(({db:e,args:t,opts:n})=>{let r=wt(e);if(S(n,"json")){E("stats",t,n,r);return}console.log(`Documents: ${r.documents}`),console.log(`Symbols: ${r.symbols}`),console.log(`Definitions: ${r.definitions}`),console.log(`References: ${r.references}`),console.log(`Index size: ${Ve(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),zf=[{id:"stats",command:"stats",description:"Show index statistics",agent:k("How large and fresh is the current index?","document, symbol, definition, reference, size, and build-time totals",[],"complete","repository"),options:[cl()],renderShape:"custom",docs:$("Core"),handler:J$}];var z$=er("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>va(e,{limit:F(t,"limit",20),scope:w(t,"scope"),minFanIn:P(t,"minFanIn",2),minFanOut:P(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.actionTier.padEnd(6)} ${e.riskKind.padEnd(20)} ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),K$=me(({db:e,args:t,opts:n})=>{let r=H(t,0),i=F(n,"limit",30);if(r){let c=pa(e,r);if(S(n,"json")){E("fan-in",t,n,{mode:"symbol",symbol:r,rows:c});return}if(c.length===0)return A.empty(`No fan-in for ${r}.`);A.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let o=fa(e,{limit:i,scope:w(n,"scope")});if(S(n,"json")){E("fan-in",t,n,{mode:"top",rows:o});return}let s=new Map;for(let c of o)s.set(c.name,(s.get(c.name)??0)+1);let a=new Set([...s].filter(([,c])=>c>1).map(([c])=>c));A.table(["files","symbol"],o.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),Q$=me(({db:e,args:t,opts:n})=>{let r=H(t,0),i=F(n,"limit",30);if(r){let s=ma(e,r);if(S(n,"json")){E("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return A.empty(`No fan-out for ${r}.`);A.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=ga(e,{limit:i,scope:w(n,"scope")});if(S(n,"json")){E("fan-out",t,n,{mode:"top",rows:o});return}A.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),X$=me(({db:e,args:t,opts:n})=>{let r=H(t,0),i=H(t,1),o=F(n,"limit",20);if(r&&i){let a=ha(e,r,i);if(S(n,"json")){E("coupling",t,n,{mode:"pair",result:a});return}console.log(`${a.file1} \u2194 ${a.file2}: ${a.sharedSymbols} shared symbols (${a.actionTier})`),console.log(` Risk: ${a.couplingKind}`),console.log(` Recommendation: ${a.recommendation}`);return}let s=ya(e,{limit:o,scope:w(n,"scope")});if(S(n,"json")){E("coupling",t,n,{mode:"top",rows:s});return}A.table(["tier","risk","shared","file1 \u2192 file2"],s.map(a=>` ${a.actionTier.padEnd(6)} ${a.couplingKind.padEnd(22)} ${String(a.sharedSymbols).padStart(6)} ${a.file1} \u2192 ${a.file2}`))}),Y$=et({commandName:"cycles",query:({db:e,opts:t})=>ba(e,{scope:w(t,"scope"),maxDepth:P(t,"maxDepth",10)}),emptyMessage:e=>e.cycles.length===0?e.truncated?`No circular dependencies found. Search truncated at depth ${e.maxDepth}; deeper cycles may exist.`:"No circular dependencies found.":void 0,toJson:e=>e,render:e=>{let t=e.cycles.filter(r=>r.kind==="real"),n=e.cycles.filter(r=>r.kind==="module-hierarchy");for(let r=0;r<t.length;r++){console.log(`
519
- Cycle ${r+1} (${t[r].path.length-1} files):`);for(let i=0;i<t[r].path.length;i++){let o=i<t[r].path.length-1?" \u2192":" (cycle)";console.log(` ${t[r].path[i]}${o}`)}}t.length===0?console.log("No real circular dependencies found."):console.log(`
520
- ${t.length} real cycle(s) found.`),e.truncated&&console.log(`(search truncated at depth ${e.maxDepth} \u2014 deeper cycles may exist)`),n.length>0&&console.log(`(${n.length} module-hierarchy cycle(s) hidden \u2014 barrel files participating in normal parent/child re-export patterns. Pass --include-module-hierarchy to see them.)`)}}),Z$=et({commandName:"architecture",query:({db:e,opts:t})=>Sa(e,{scope:w(t,"scope")}),emptyMessage:e=>e.configured?void 0:"No architecture boundaries configured. Add architecture.boundaries to .scipquery.json.",render:e=>{if(console.log(`Mapped ${e.coverage.mappedFiles}/${e.coverage.totalFiles} indexed file(s) across ${e.boundaries.length} boundary(ies); ${e.policyCoverage.declaredRows}/${e.policyCoverage.totalBoundaries} dependency row(s) declared.`),e.policyCoverage.missingRows.length>0){let t=e.policyCoverage.requiresCompletePolicy?" [violates requireCompletePolicy]":"";console.log(`Missing dependency rows: ${e.policyCoverage.missingRows.join(", ")}${t}`)}if(e.coverage.unmappedFiles.length>0&&console.log(`Unmapped files: ${e.coverage.unmappedFiles.length}`),e.coverage.ambiguousFiles.length>0){console.log(`Ambiguous files: ${e.coverage.ambiguousFiles.length}`);for(let t of e.coverage.ambiguousFiles.slice(0,5))console.log(` ${t.file} -> ${t.boundaries.join(", ")}`)}if(e.forbiddenEdges.length>0){console.log(`
521
- Forbidden boundary edges (${e.forbiddenEdges.length}):`);for(let t of e.forbiddenEdges){console.log(` ${t.from} -> ${t.to}: ${t.fileEdgeCount} file edge(s), ${t.importerCount} importer(s), ${t.importedFileCount} imported file(s)`);for(let n of t.examples)console.log(` ${n.fromFile} -> ${n.toFile}`)}}else console.log(`
522
- No declared boundary violations found.`);if(e.staleAllowances.length>0){console.log(`
523
- Stale dependency allowances (${e.staleAllowances.length}): declared but unused, so the policy is wider than the code requires.`);for(let t of e.staleAllowances)console.log(` ${t.from} -> ${t.to}`)}if(e.boundaryLimits.length>0){console.log(`
524
- Boundaries over configured limits (${e.boundaryLimits.length}):`);for(let t of e.boundaryLimits)console.log(` ${t.boundary}: ${t.kind} ${t.observed} exceeds limit ${t.limit}`)}if(e.testBoundaryViolations.length>0){console.log(`
525
- Test boundary violations (${e.testBoundaryViolations.length}): a test reaches further than the boundary of the code it covers is allowed to reach.`);for(let t of e.testBoundaryViolations.slice(0,20)){let n=t.ownerBoundary??"(no subject found)";console.log(` ${t.testFile} [${n}] -> ${t.importedBoundary} (${t.importedFile})`)}e.testBoundaryViolations.length>20&&console.log(` ... +${e.testBoundaryViolations.length-20} more`)}if(e.fragileEdges.length>0){console.log(`
526
- Single-import boundary edges (${e.fragileEdges.length} of ${e.edges.length}): the whole boundary dependency is carried by one file-level import. Breadth alone does not establish importance -- inspect before concluding either way.`);for(let t of e.fragileEdges.slice(0,10)){let n=t.examples[0];console.log(` ${t.from} -> ${t.to}${n?` (${n.fromFile} -> ${n.toFile})`:""}`)}e.fragileEdges.length>10&&console.log(` ... +${e.fragileEdges.length-10} more`)}if(e.coarseBoundaries.length>0){console.log(`
527
- Boundaries too coarse to check (${e.coarseBoundaries.length}): these own an internal dependency cycle that the boundary graph cannot express, so requireAcyclic reports nothing about the code inside them.`);for(let t of e.coarseBoundaries){console.log(` ${t.boundary}: ${t.subUnits.join(" <-> ")}`);for(let n of t.narrowestEdges){console.log(` narrowest: ${n.from} -> ${n.to} (${n.fileEdgeCount} file edge(s))`);for(let r of n.examples.slice(0,3))console.log(` ${r.fromFile} -> ${r.toFile}`)}}}if(e.edges.length>0){console.log(`
528
- Boundary graph (${e.edges.length} directed edge(s)):`);for(let t of e.edges)console.log(` ${t.from} -> ${t.to} ${t.policyStatus.padEnd(10)} ${t.fileEdgeCount} file edge(s)`)}if(e.reciprocalPairs.length>0){console.log(`
529
- Reciprocal boundary pairs (${e.reciprocalPairs.length}):`);for(let t of e.reciprocalPairs)console.log(` ${t.boundaries[0]} <-> ${t.boundaries[1]} ${t.forward.fileEdgeCount}/${t.reverse.fileEdgeCount} file edge(s)`)}if(e.cycles.length>0){console.log(`
530
- Strongly connected boundary groups (${e.cycles.length}):`);for(let t of e.cycles){let n=t.violatesPolicy?" [violates requireAcyclic]":"";console.log(` { ${t.boundaries.join(", ")} }${n}`);for(let r of t.narrowestEdges)console.log(` inspect ${r.from} -> ${r.to}: ${r.fileEdgeCount} file edge(s)`)}}}}),eC=et({commandName:"deep-chains",query:({db:e,opts:t})=>wa(e,{limit:F(t,"limit",10),scope:w(t,"scope"),minDepth:P(t,"minDepth",3)}),emptyMessage:e=>e.length===0?"No deep chains found.":void 0,render:e=>{for(let t=0;t<e.length;t++){console.log(`
531
- Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].components){let r=n.length===1?n[0]:`{ ${n.join(", ")} } (cycle)`;console.log(` \u2192 ${r}`)}console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),Kf=[qr({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",agent:k("Which symbols are the largest reference choke points?","ranked symbol identities with reference and file counts",[],"bounded","repository"),options:[p("-n, --limit <n>","Number of results",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")],docs:$("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>aa(e,{limit:F(t,"limit",30),scope:w(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",agent:k("How many files reference this symbol, or which symbols have highest fan-in?","exact symbols with referencing-file counts",["symbol"],"bounded","repository"),options:I([p("-n, --limit <n>","Number of results for top mode",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:K$},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",agent:k("How many external symbols does this file use, or which files have highest fan-out?","files with external-symbol counts",["file"],"bounded","repository"),options:I([p("-n, --limit <n>","Number of results for top mode",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:Q$},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",agent:k("How strongly are these files coupled, or which pairs are most coupled?","file pairs with coupling evidence and scores",["file","file"],"bounded","repository"),options:I([p("-n, --limit <n>","Number of results for top mode",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:X$},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",agent:k("Which file dependency cycles exist?","dependency-cycle file chains",[],"bounded","repository"),options:I([p("-s, --scope <path>","Limit to files matching path"),p("--max-depth <n>","Bound DFS search depth",x,10)]),renderShape:"custom",docs:$("Graph"),handler:Y$},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",agent:k("Does the repository obey its declared architecture boundaries?","boundary coverage and dependency-rule violations",[],"complete","repository"),options:I([p("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",renderShape:"custom",docs:$("Graph",["scip-query architecture --json"]),handler:Z$},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",agent:k("Which files are high-connectivity coupling hubs?","ranked files with fan-in and fan-out counts",[],"bounded","repository"),options:I([p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-fan-in <n>","Minimum fan-in",x,2),p("--min-fan-out <n>","Minimum fan-out",x,2),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:$("Graph"),handler:z$},{id:"deep-chains",command:"deep-chains",description:"Find the longest condensed dependency-component chains",agent:k("Which dependency chains are deepest and riskiest?","ranked component chains with depth, risk, and recommendation",[],"bounded","repository"),options:I([p("-n, --limit <n>","Number of chains to show",x,10),p("-s, --scope <path>","Limit to files matching path"),p("--min-depth <n>","Minimum chain depth",x,3),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:eC},Vr({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",agent:k("Who calls this symbol and what does it call?","caller and callee symbol identities with files",["symbol"],"bounded"),options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:$("Graph"),query:({db:e,args:t,budget:n})=>tn(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:le(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(ce(t,String(n[0])),console.log(`Symbol: ${e.shortName}
532
- `))},toJson:(e,{db:t,args:n})=>we(t,String(n[0]),e,"callGraph"),sections:e=>e?[{title:`CALLERS (${e.callers.length})`,rows:e.callers.map(t=>` ${t.file} ${t.shortName}`)},{title:`CALLEES (${e.callees.length})`,rows:e.callees.map(t=>` ${t.file} ${t.shortName}`)}]:[]})];var tC=Z("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=O(t,0),o=fc(e,i,{semantic:r.semantic});if(S(n,"json")){E("complexity",t,n,we(e,i,o,"complexity"),{analysisBudget:r.analysisBudget});return}if(!o)return A.empty(le(e,i,"Symbol not found."));ce(e,i),console.log(`${V(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
533
- `),console.log(` LOC: ${o.loc}`),console.log(` Branches: ${o.branches}`),console.log(` Cyclomatic estimate: ${o.cyclomaticEstimate}`),console.log(` Callees: ${o.calleeCount}`),console.log(` Fan-in: ${o.fanIn}`),console.log(` Fan-out: ${o.fanOut}`)}),nC=me(({db:e,args:t,opts:n})=>{let r=Ic(e,{samples:P(n,"samples",50),scope:w(n,"scope")});if(S(n,"json")){E("self-audit",t,n,r);return}if(!r.available)return A.empty("No semantic or source-backed oracle available to audit against.");let i=r.oracleKind==="source"?"source facts":"compiler semantics";console.log(`Sampled ${r.sampleSize} symbols; ${i} oracle answered ${Math.round(r.oracleCoverage*100)}%.
534
- `),console.log(`Agreement with ${i} (file-level):`);for(let o of r.scores){let s=o.precision===null?`unverified ${o.unverified} (oracle partial \u2014 no precision claim)`:`precision ${o.precision}`;console.log(` ${o.question.padEnd(11)} ${s} recall ${o.recall} (${o.comparedSymbols} compared, ${o.skippedOraclePartial} skipped: oracle-partial)`)}if(r.topDisagreements.length>0){console.log(`
535
- Top disagreements (debugging targets):`);for(let o of r.topDisagreements)console.log(` ${o.symbol} [${o.question}]`),o.cheapOnly.length>0&&console.log(` cheap-only: ${o.cheapOnly.join(", ")}`),o.oracleOnly.length>0&&console.log(` oracle-only: ${o.oracleOnly.join(", ")}`)}}),Qf=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",agent:k("How accurate are the fast evidence paths on a sample?","sample coverage, agreement scores, and disagreements",[],"sampled","repository"),options:I([p("--samples <n>","Number of symbols to sample",x,50),p("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:$("Health",["scip-query self-audit --samples 100"]),handler:nC},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",agent:k("How structurally complex and connected is this symbol?","LOC, branch, complexity, callee, fan-in, and fan-out counts",["symbol"],"bounded"),options:I([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Health"),handler:tC}];var rC=me(({db:e,args:t,opts:n})=>{let r=O(t,0),i=_a(e,r,{maxDepth:P(n,"maxDepth",5),scope:w(n,"scope")});if(S(n,"json")){E("affected",t,n,we(e,r,i,"affected"));return}if(i.length===0)return A.empty(le(e,r,"No affected symbols found."));ce(e,r);let o=-1;for(let s of i)s.depth!==o&&(console.log(`
536
- \u2500\u2500 Depth ${s.depth} \u2500\u2500`),o=s.depth),console.log(` ${s.file} ${s.shortName}`);console.log(`
537
- ${i.length} affected symbol(s) across ${new Set(i.map(s=>s.file)).size} files.`)}),iC=Z("co-change",({db:e,args:t,opts:n,budget:r})=>{let i=t[0]===void 0?void 0:O(t,0),o=S(n,"full"),s=qa(e,i,{minTogether:P(n,"minTogether",4),limit:F(n,"limit",30),includeLinked:n.all===!0,scanLimit:r.scanLimit,historyMode:o?"full":"bounded"});if(S(n,"json")){E("co-change",t,n,s,{analysisBudget:r.analysisBudget});return}if(!s.available)return A.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return A.empty(i?`No co-change partners found for ${i} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);Ae("co-change candidates"),console.log(i?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
538
- `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
539
- `),i&&s.findings.some(a=>a.structurallyLinked||a.declaredCouplingSuggestion)&&console.log(`note: file mode lists all historical partners; [dep edge]/[declared] pairs are excluded from hidden-coupling findings.
540
- `);for(let a of s.findings){let c=a.structurallyLinked?" [dep edge]":"",l=` [${a.partnerClass}]`,d=` [${a.commitScope}/${a.recency}]`;console.log(` ${a.together}x (${Math.round(a.confidence*100)}%) ${a.fileA} <-> ${a.fileB}${l}${d}${c}`),console.log(` history: ${a.focusedTogether} focused, ${a.broadTogether} broad-sweep (${Math.round(a.broadCommitRatio*100)}% broad), ${a.recentTogether} recent; last ${oC(a.lastTogetherAt)}`),console.log(` subjects: ${sC(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
541
- ${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function oC(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function sC(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}var aC=Z("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=Ba(e,O(t,0),{semantic:r.semantic});if(S(n,"json")){E("change-surface",t,n,i,{analysisBudget:r.analysisBudget});return}if(!i)return A.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
542
- `),A.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${ae(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),cC=Z("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=Za(e,{base:w(n,"base"),minContainment:P(n,"minContainment",.7),maxHelpers:Q(n,"maxHelpers"),limit:F(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(S(n,"json")){E("incomplete-migration",t,n,i,{analysisBudget:r.analysisBudget}),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return A.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return A.empty(`No changes vs ${i.base}.`);console.log(`Incomplete migrations vs ${i.base}: ${i.changedFiles.length} changed file(s), ${i.helpersChecked} new helper(s) scored.`),i.note&&console.log(` note: ${i.note}`);for(let o of i.skipped)console.log(` skipped ${o.helperShortName} (${o.helperFile}): ${o.reason}`);if(i.findings.length===0){console.log(`
543
- No incomplete migrations detected.`);return}Ae("incomplete migration candidates");for(let o of i.findings){console.log(`
544
- ${o.helperShortName} (${o.helperFile})`),console.log(` helper shape: ${o.helperShape} (${o.specificHelperCalleeCount}/${o.helperCalleeCount} specific callees)`),console.log(` wired into: ${o.migratedFiles.join(", ")}`);for(let s of o.leftovers)console.log(` un-migrated: ${Math.round(s.containment*100)}% helper / ${Math.round(s.siteCoverage*100)}% site [${s.migrationScope}] ${s.shortName} (${s.file})`),console.log(` scope: ${s.migrationScopeReasons.join("; ")}`),s.uniqueSiteCalleeCount>0&&console.log(` extra site callees: ${s.uniqueSiteCalleeCount}`),console.log(` shared: ${s.sharedCallees.join(", ")}`)}console.log(`
545
- ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function lC(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!fi.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${fi.join(", ")}`),process.exit(1)),t}var dC=me(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&rr(Lt()))return;let r=S(t,"full"),i=rl(e,"diff-gate",r,{quiet:n||S(t,"json")}),o={base:w(t,"base"),minTogether:P(t,"minTogether",6),maxEchoChecks:Q(t,"maxEchoChecks"),maxHelpers:Q(t,"maxHelpers"),includeBaseline:S(t,"baseline"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:r?"full":"bounded",skip:lC(t.skip)},s=$t(e,o),a=Gn(s.findings),c=Un(s),l=s.recordCompatibility?Ze("Committed suppression",s.recordCompatibility.suppressions):void 0,d=pr(e,s,{replayGate:f=>$t(e,{...o,base:f})});if(d.warning&&console.error(`note: ${d.warning}`),!n&&S(t,"json")){let f=a.length>0||c?1:0;E("diff-gate",[],t,{exitCode:f,...c?{gateError:"git diff unavailable - zero checks ran; the gate fails closed"}:{},advisoryFindingCount:s.findings.length-a.length,...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},...s},{analysisBudget:i.analysisBudget,coverage:r&&!c?{complete:!0,totalKnown:!0,returned:s.findings.length,total:s.findings.length,omitted:0}:{complete:!1,totalKnown:!1,returned:s.findings.length},agentResult:{outcome:f===0?"pass":"fail",exitCode:f,changedFileCount:s.changedFiles.length,changedSymbolCount:s.changedSymbols,checksRun:s.checksRun,skippedChecks:s.skipped,blockingFindings:a.map(h=>({id:h.id,check:h.check,severity:h.severity,file:h.file,symbol:h.symbol,message:h.message,remediation:h.remediation})),advisoryFindingCount:s.findings.length-a.length}}),(a.length>0||c)&&(process.exitCode=1);return}if(n){let{ledger:f,observed:h,now:b}=d;if(c){console.error("diff gate FAILED CLOSED: could not compute the git diff (diff too large, bad --base, or git error) - zero checks ran. Investigate with: scip-query diff-gate"),process.exitCode=2;return}if(l&&console.error(`note: ${l}`),a.length===0)return;let y=vc(f,h,b),v=Rc(f,s.checksRun),R=il(i.analysisBudget),T=[...y?[y]:[],cn(s),...v,...R?[R]:[]];console.error(T.join(`
546
- `)),process.exitCode=2;return}if(c){console.error("FAIL (gate error): could not compute the git diff - zero checks ran; the gate fails closed. Check --base and repository state."),process.exitCode=1;return}if(l&&console.log(`WARN: ${l}`),s.changedFiles.length===0)return A.empty(s.note??`No changes vs ${s.base}.`);console.log(`Diff gate vs ${s.base}: ${s.changedFiles.length} file(s), ${s.changedSymbols} symbol(s) changed.`);let u=s.attributionNotes.filter(f=>f.method==="unattributed");if(u.length>0)for(let f of[...new Set(u.map(h=>h.file))]){let h=u.filter(b=>b.file===f).length;console.log(`note: ${h} changed line-range(s) in ${f} belong to no indexed symbol`)}console.log(`Checks: ${s.checksRun.join(", ")}
547
- `);for(let f of s.skipped)console.log(` skipped ${f.check}: ${f.reason}`);if(s.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}Ae("diff gate candidates");let m=s.rootCauseGroups?.filter(f=>f.count>1)??[];if(m.length>0){console.log(`Root-cause groups (${m.length}):`);for(let f of m){console.log(` [${f.check}] ${f.count} finding(s), ${f.severity}${f.actionTier?`, tier: ${f.actionTier}`:""}`),(f.sourceAnalyzer||f.rootCauseKey)&&console.log(` source: ${f.sourceAnalyzer??f.check}${f.rootCauseKey?` root cause: ${f.rootCauseKey}`:""}`);let h=[...new Set([...f.files,...f.relatedFiles])].slice(0,6);h.length>0&&console.log(` files: ${h.join(", ")}`),console.log(` -> ${f.remediation}`)}console.log("")}for(let f of s.findings){if(console.log(` [${f.check}]${f.advisory?" (advisory)":""} ${f.message}`),f.partnerClass){console.log(` partner class: ${f.partnerClass}`);for(let h of f.partnerClassReasons??[])console.log(` reason: ${h}`)}f.citationKind&&console.log(` citation kind: ${f.citationKind}${f.actionTier?` (tier: ${f.actionTier})`:""}`);for(let h of f.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${Yn(h)}`);f.declaredCouplingSuggestion&&console.log(` declare coupling: ${f.declaredCouplingSuggestion.name} (${f.declaredCouplingSuggestion.reason})`),console.log(` -> ${f.remediation}`)}if(a.length===0){console.log(`
548
- PASS (advisory only): ${s.findings.length} advisory finding(s) recorded \u2014 none block this diff.`);return}let g=s.findings.length-a.length;console.log(`
549
- FAIL: ${a.length} finding(s)${g>0?` (+${g} advisory)`:""}, ${s.rootCauseGroups?.length??s.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),Xf=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",agent:k("Which downstream symbols could break if this symbol changes?","affected symbol identities, files, and traversal depths",["symbol"],"bounded"),options:I([p("--max-depth <n>","Maximum traversal depth",x,5),p("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:$("Impact"),handler:rC},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",agent:k("What public surface and consumers make this file risky to change?","defined symbols, external consumer counts, and risk levels",["file"],"bounded"),options:I([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:$("Impact"),handler:aC},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: architecture regressions plus echo, migration, coordination, doc-drift, unused-param, and new-dead candidates; exit 1 on blocking findings",options:[p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-together <n>","Minimum historical co-changes for the partner check",x,6),p("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",x),p("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",x),p("--baseline","Also run the full health-baseline ratchet"),p("--full","Run unbounded semantic and git-history analysis on large indexes"),p("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, twin-partner, coverage-contract, architecture, doc-reference, unused-params, new-dead, baseline",ut,[]),p("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),p("--json","Output as JSON for programmatic consumption"),p("--compact","Emit minified one-line JSON (use with --json)")],heuristic:{label:"diff gate candidates"},agent:{answers:["Does my current diff introduce something this repo blocks on?","What must I fix or explicitly accept before reporting the work done?"],returns:["blocking findings with check id, message, and remediation","advisory findings","root-cause groups","changed file and symbol counts","process exit status (1 when blocking findings exist)"],inputs:[],scope:"diff",coverage:"bounded",contrasts:[{command:"diff-impact",distinction:"diff-impact reports what the diff touches downstream; diff-gate judges the diff against repo policy and exits non-zero."}]},renderShape:"custom",docs:$("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:dC},{id:"incomplete-migration",command:"incomplete-migration",description:"Partially-completed extraction candidates: new helpers in the diff wired into some sites while similar un-migrated sites remain",agent:k("Did this diff leave a helper extraction only partly migrated?","new helpers and similar unmigrated call sites",[],"bounded","diff"),options:I([p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",Se,.7),p("--max-helpers <n>","Maximum new helpers to score (default: all)",x),p("-n, --limit <n>","Maximum findings to report",x,20),p("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:$("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:cC},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",agent:k("Which files repeatedly change together without a declared dependency?","file pairs, co-change counts, confidence, and history context",["file"],"bounded","repository"),options:I([p("--min-together <n>","Minimum commits where both files changed",x,4),p("-n, --limit <n>","Maximum pairs to report",x,30),p("--all","Include pairs that already have a dependency edge"),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:$("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:iC}];function uC(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${V(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
550
- `).map((s,a)=>` ${We(i.startLine+a)} ${s}`).join(`
551
- `))}let n=[],r="";for(let i of e.referencedBy)i.relativePath!==r&&(r&&n.push(""),n.push(` ${i.relativePath}`),r=i.relativePath),n.push(` line ${We(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var pC=fe("imports",{query:({db:e,args:t,budget:n})=>ca(e,O(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} \u2190 ${e.fromFile}`,emptyMessage:()=>"No imports found (indexer may not emit role=2 for this language)."}),mC=Z("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=O(t,0),o=gc(e,i,{semantic:r.semantic});if(S(n,"json")){E("dataflow",t,n,we(e,i,o,"dataflow"),{analysisBudget:r.analysisBudget});return}if(!o)return A.empty(le(e,i,"No dataflow found."));if(ce(e,i),console.log(`${o.shortName} (${o.relativePath})
552
- `),o.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of o.definitionSites)console.log(` ${s.file}:${We(s.line)}`)}if(o.usageSites.length>0){console.log(`
553
- \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of o.usageSites)console.log(` ${s.file}:${We(s.line)} in ${s.enclosingShort}`)}if(o.producers.length>0){console.log(`
554
- \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let s of o.producers)console.log(` ${s.file} ${s.shortName}`)}if(o.consumers.length>0){console.log(`
555
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),fC=Z("slice",({db:e,args:t,opts:n,budget:r})=>{let i=O(t,0),o=S(n,"forward")?"forward":"backward",s=hc(e,i,{direction:o,maxDepth:P(n,"depth",3),semantic:r.semantic});if(S(n,"json")){E("slice",t,n,we(e,i,s,"slice"),{analysisBudget:r.analysisBudget});return}if(!s)return A.empty(le(e,i,"No slice found."));if(ce(e,i),console.log(`${s.direction} slice of ${s.shortName}
556
- `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}A.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
557
- ${a.relationship}`),console.log(`
558
- ${s.connectedSymbols.length} connected symbol(s).`)}),Yf=[...bl,Oe({id:"files",command:"files <pattern>",description:"Find files matching a pattern",agent:k("Which indexed files match this text pattern?","matching file paths",["pattern"],"complete"),docs:$("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>Zs(e,O(t,0)),format:e=>e.relativePath}),Oe({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",agent:k("Which methods belong to this class?","method names and line ranges",["symbol"],"complete"),docs:$("Navigation"),query:({db:e,args:t})=>ea(e,O(t,0)),format:e=>` ${ae(e.startLine,e.endLine)} ${e.name}`}),Vr({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[p("--full","Run unbounded semantic analysis on large indexes"),vi()],budget:"semantic",agent:{answers:["Where is this symbol defined, and everywhere is it referenced?"],returns:["definition sites with source and signature","referencing files with line numbers"],inputs:["symbol"],coverage:"bounded",contrasts:[{command:"refs",distinction:"refs returns reference sites only; trace adds the definition and its source."},{command:"call-graph",distinction:"trace lists reference sites flat; call-graph separates incoming callers from outgoing callees."}]},docs:$("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>ta(e,O(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?le(t,O(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>ce(t,O(n,0)),toJson:(e,{db:t,args:n})=>({...sn(t,O(n,0)),...e}),coverage:(e,{budget:t})=>{let n=e.definitions.length+e.referencedBy.length;return t.analysisBudget?{complete:!1,totalKnown:!1,returned:n}:{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}},agentResult:e=>({definitionCount:e.definitions.length,referenceCount:e.referencedBy.length,definitionIdentities:e.definitions.map(t=>`${t.relativePath}:${t.startLine}-${t.endLine}`),referenceIdentities:e.referencedBy.map(t=>`${t.relativePath}:${t.line}`)}),sections:uC}),Oe({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",agent:k("Which internal files does this file depend on?","dependency file paths",["file"],"complete"),docs:$("Navigation"),query:({db:e,args:t})=>na(e,O(t,0)),format:e=>e.relativePath}),Oe({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",agent:k("Which internal files depend on this file?","reverse-dependency file paths",["file"],"complete"),docs:$("Navigation"),query:({db:e,args:t})=>ra(e,O(t,0)),format:e=>e.relativePath}),Xm({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",options:[vi()],agent:{answers:["What is in this module?","What does this module depend on, and what depends on it?"],returns:["module file paths","exported symbols with line ranges","internal dependencies","reverse dependencies"],inputs:["module"],coverage:"complete",contrasts:[{command:"surface",distinction:"system lists everything the module exports; surface lists only what consumers actually use."},{command:"outline",distinction:"system is module-scoped; outline covers a single file."}]},docs:$("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>ia(e,O(t,0)),coverage:e=>{let t=e.files.length+e.symbols.length+e.dependsOn.length+e.dependedOnBy.length;return{complete:!0,totalKnown:!0,returned:t,total:t,omitted:0}},agentResult:e=>({counts:{files:e.files.length,symbols:e.symbols.length,dependencies:e.dependsOn.length,consumers:e.dependedOnBy.length},files:e.files,dependsOn:e.dependsOn,dependedOnBy:e.dependedOnBy,detail:{location:"result",symbolUnits:"result.symbols contains every exported symbol with its line range"}}),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${ae(t.startLine,t.endLine)} ${t.shortName}`)},{title:"DEPENDS ON (internal)",rows:e.dependsOn.map(t=>` ${t}`)},{title:"DEPENDED ON BY",rows:e.dependedOnBy.map(t=>` ${t}`)}]}),Oe({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",agent:k("Which exported symbols do external consumers actually use?","consumer paths and consumed symbol identities",["module"],"complete"),docs:$("Navigation"),query:({db:e,args:t})=>oa(e,O(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",agent:k("Which symbols does this file import?","imported symbol identities and source files",["file"],"bounded"),options:[p("--full","Run unbounded semantic analysis on large indexes"),p("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:$("Navigation"),handler:pC},Oe({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",agent:k("Which files import this symbol?","importing file paths",["symbol"],"complete"),docs:$("Navigation"),query:({db:e,args:t})=>la(e,O(t,0)),format:e=>` ${e.fromFile}`}),Oe({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",agent:k("Which members or nested symbols belong to this symbol?","child symbol identities, kinds, and ranges",["symbol"],"complete"),docs:$("Navigation"),query:({db:e,args:t})=>ua(e,O(t,0)),format:e=>` ${ae(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>ce(t,O(n,0)),emptyMessage:({db:e,args:t})=>le(e,O(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>we(t,O(n,0),e,"members")}),Oe({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",agent:k("Which symbols have this SCIP kind?","symbol identities, kinds, files, and ranges",["pattern"],"bounded"),options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,100),p("--full","Run unbounded analysis on large indexes")],docs:$("Navigation"),query:({db:e,args:t,opts:n})=>xa(e,O(t,0),{scope:w(n,"scope"),limit:F(n,"limit",100)}),format:e=>` ${V(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${O(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
559
- ${e.length} symbol(s)`)}),qr({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",agent:k("How many indexed symbols exist for each kind?","symbol-kind counts",[],"complete","repository"),options:[p("-s, --scope <path>","Limit to files matching path")],docs:$("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>ka(e,{scope:w(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Oe({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",agent:k("What lexical ownership chain contains this symbol?","ancestor symbol identities and depths",["symbol"],"complete"),docs:$("Navigation"),query:({db:e,args:t})=>$a(e,O(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>ce(t,O(n,0)),emptyMessage:({db:e,args:t})=>le(e,O(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>we(t,O(n,0),e,"hierarchy")}),{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",agent:k("What defines, uses, produces, and consumes this symbol?","definition sites, usage sites, producer symbols, and consumer symbols",["symbol"],"bounded"),options:I([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:mC},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",agent:k("What transitively affects this symbol, or what does it affect?","connected symbols with relationship and depth",["symbol"],"bounded"),options:I([p("--forward","Forward slice (what does this affect). Default is backward."),p("--depth <n>","Max transitive depth for backward slice",x,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:fC}];var gC=Z("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=F(n,"limit",20),o=qe(e.config.projectRoot).gitContext?.headCommit,s=yc(e,O(t,0),{semantic:r.semantic,impactDepth:P(n,"impactDepth",3),sliceDepth:P(n,"sliceDepth",3),scope:w(n,"scope"),...o?{gitHead:o}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(S(n,"json")){E("plan-context",t,n,{...sn(e,O(t,0)),...s},{analysisBudget:r.analysisBudget,coverage:Zf(s),agentResult:eg(s)});return}return A.empty(le(e,O(t,0)))}if(S(n,"json")){E("plan-context",t,n,s.matched.symbol?{...sn(e,O(t,0)),...s}:s,{analysisBudget:r.analysisBudget,coverage:Zf(s),agentResult:eg(s)});return}s.matched.symbol&&ce(e,O(t,0));let a=[{title:"TARGET",rows:yC(s)},{title:"DEFINITIONS",rows:bC(s,i),skipIfEmpty:!0},{title:"REFERENCES",rows:SC(s,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:vC(s,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:RC(s,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:xC(s,i),skipIfEmpty:!0},{title:"SURFACE",rows:kC(s,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:wC(s,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:$C(s,i),skipIfEmpty:!0},{title:"HISTORY",rows:CC(s),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:PC(s),skipIfEmpty:!0}];A.sectionedReport(a)}),tg=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:ll([p("--impact-depth <n>","Maximum affected traversal depth",x,3),p("--slice-depth <n>","Maximum backward slice depth",x,3),p("-s, --scope <path>","Limit downstream impact to files matching path"),p("-n, --limit <n>","Rows per section",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",agent:{answers:["What must I know before editing this target?","Who consumes it, and what breaks if I change it?","Has this target historically changed together with anything else?"],returns:["definitions and references","callers and callees","dataflow producers and consumers","backward and forward slices","affected symbols","change-surface risk","dependencies and reverse dependencies","module files and exports","external surface use","complexity","churn","co-change partners","active suppressions"],inputs:[["symbol","file","module"]],coverage:"bounded",contrasts:[{command:"change-surface",distinction:"change-surface is the exports/consumers/risk briefing alone; plan-context embeds it alongside flow, slices, history, and reuse signals."}]},renderShape:"custom",docs:$("Planning",["scip-query plan-context parseSymbol"]),handler:gC}];function Zf(e){return{complete:!1,totalKnown:!1,returned:hC(e)}}function hC(e){return e.trace.definitions.length+e.trace.referencedBy.length+(e.callGraph?.callers.length??0)+(e.callGraph?.callees.length??0)+(e.dataflow?.producers.length??0)+(e.dataflow?.consumers.length??0)+(e.dataflow?.usageSites.length??0)+(e.backwardSlice?.connectedSymbols.length??0)+(e.forwardSlice?.connectedSymbols.length??0)+e.affected.length+e.deps.length+e.rdeps.length+e.system.files.length+e.system.symbols.length+e.system.dependsOn.length+e.system.dependedOnBy.length+e.surface.length}function eg(e){return{target:e.target,matched:e.matched,counts:{definitions:e.trace.definitions.length,references:e.trace.referencedBy.length,callers:e.callGraph?.callers.length??0,callees:e.callGraph?.callees.length??0,producers:e.dataflow?.producers.length??0,consumers:e.dataflow?.consumers.length??0,backwardSlice:e.backwardSlice?.connectedSymbols.length??0,forwardSlice:e.forwardSlice?.connectedSymbols.length??0,affected:e.affected.length,dependencies:e.deps.length,reverseDependencies:e.rdeps.length,moduleFiles:e.system.files.length,externalSurfaceUses:e.surface.length,coChangePartners:e.history.coChangePartners.length},warnings:e.warnings,changeSurface:e.changeSurface?{file:e.changeSurface.file,totalExternalConsumers:e.changeSurface.totalExternalConsumers,riskCounts:{high:e.changeSurface.symbols.filter(t=>t.riskLevel==="high").length,medium:e.changeSurface.symbols.filter(t=>t.riskLevel==="medium").length,low:e.changeSurface.symbols.filter(t=>t.riskLevel==="low").length}}:null,history:e.history}}function yC(e){return[`Target: ${e.target}`,`Matched: symbol=${Qo(e.matched.symbol)} file=${Qo(e.matched.file)} module=${Qo(e.matched.module)}`]}function bC(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${V(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
560
- `).map((o,s)=>` ${String(We(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${ae(r.startLine,r.endLine)} ${r.shortName}`)),st(n,t).rows}function SC(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${We(r.line)} in ${r.enclosingShort}`);return bt(st(n,t))}function vC(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(i=>` caller ${i.file} ${i.shortName}`),r=e.callGraph.callees.map(i=>` callee ${i.file} ${i.shortName}`);return bt(st([...n,...r],t))}function RC(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(o=>` producer ${o.file} ${o.shortName}`),r=e.dataflow.consumers.map(o=>` consumer ${o.file} ${o.shortName}`),i=e.dataflow.usageSites.map(o=>` usage ${o.file}:${We(o.line)} in ${o.enclosingShort}`);return bt(st([...n,...r,...i],t))}function xC(e,t){let n=[...e.deps.map(r=>` file depends on ${r.relativePath}`),...e.rdeps.map(r=>` file depended on by ${r.relativePath}`),...e.system.dependsOn.map(r=>` module depends on ${r}`),...e.system.dependedOnBy.map(r=>` module used by ${r}`)];return bt(st(n,t))}function kC(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${ae(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return bt(st(n,t))}function wC(e,t){let n=[],r=-1;for(let i of e.affected)i.depth!==r&&(n.push(` -- Depth ${i.depth} --`),r=i.depth),n.push(` ${i.file} ${i.shortName}`);return bt(st(n,t))}function $C(e,t){let n=[];return e.changeSurface&&(n.push(` File: ${e.changeSurface.file}`),n.push(` External consumers: ${e.changeSurface.totalExternalConsumers}`),n.push(...e.changeSurface.symbols.map(r=>{let i=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"";return` ${ae(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${V(e.complexity.relativePath,e.complexity.startLine,e.complexity.endLine)} ${e.complexity.shortName}`),n.push(` LOC: ${e.complexity.loc}`),n.push(` Branches: ${e.complexity.branches}`),n.push(` Cyclomatic estimate: ${e.complexity.cyclomaticEstimate}`),n.push(` Callees: ${e.complexity.calleeCount}`),n.push(` Fan-in: ${e.complexity.fanIn}`),n.push(` Fan-out: ${e.complexity.fanOut}`)),bt(st(n,t))}function CC(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let r=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${r}`)}for(let r of t.coChangePartners)n.push(` Usually changes with: ${r.file} (${r.together}x, ${Math.round(r.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function PC(e){let t=e.warnings.map(r=>` ${r}`);return e.history.coChangePartners.length>0&&t.push(" Check the HISTORY co-change partners \u2014 editing this file usually means editing them too."),(e.changeSurface?.symbols.filter(r=>r.riskLevel==="high")??[]).length>0&&t.push(" Inspect high-risk consumers before editing public behavior."),e.affected.length>0&&t.push(" Validate downstream consumers at the shallowest affected depths first."),t}function st(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function bt(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function Qo(e){return e?"yes":"no"}import{existsSync as Tn}from"fs";import{existsSync as GC,mkdtempSync as JC,rmSync as zC}from"fs";import{tmpdir as KC}from"os";import{dirname as Zo,join as es}from"path";import{performance as lg}from"perf_hooks";import{spawnSync as QC}from"child_process";import{createHash as ig,randomUUID as TC}from"crypto";import{closeSync as Kr,createReadStream as IC,existsSync as EC,fsyncSync as jC,mkdirSync as AC,openSync as Yo,renameSync as LC,unlinkSync as OC,writeSync as DC}from"fs";import{homedir as FC}from"os";import{dirname as og,join as Xo}from"path";var MC=3e5,NC=256*1024*1024;function sg(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?Xo(t.XDG_CACHE_HOME,"scip-query"):Xo(FC(),".cache","scip-query"));return Xo(n,e)}var Y=class extends Error{constructor(n,r,i={}){super(r,i.cause===void 0?void 0:{cause:i.cause});this.kind=n;this.name="VerifiedBinaryFetchError"}kind};async function ag(e){let{cachePath:t,url:n,expectedSha256:r}=e,i=e.timeoutMs??MC,o=e.maxBytes??NC,s=e.lockWaitMs??i;_C(i,o,s);let a=BC(n,i,e.signal);try{let c=await ng(t,r,o,a.controller.signal);if(c)return{status:"cached",path:t,sha256:c};AC(og(t),{recursive:!0});let l=await _c(`${t}.fetch.lock`,{waitMs:s,pollMs:25,signal:a.controller.signal});if(!l)throw new Y("lock-timeout",`timed out waiting ${s}ms for verified binary cache ownership at ${t}`);try{let d=await ng(t,r,o,a.controller.signal);return d?{status:"cached",path:t,sha256:d}:await qC(e,a.controller,o)}finally{l.release()}}catch(c){throw a.controller.signal.aborted?Ht(a.controller.signal,n):c instanceof Y?c:new Y("stream",`failed to download ${n}: ${cg(c)}`,{cause:c})}finally{clearTimeout(a.timeout),a.detachExternalAbort(),a.controller.signal.aborted||a.controller.abort()}}function _C(e,t,n){if(!Number.isFinite(e)||e<=0)throw new TypeError("timeoutMs must be a positive finite number.");if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("maxBytes must be a positive safe integer.");if(!Number.isFinite(n)||n<0)throw new TypeError("lockWaitMs must be a non-negative finite number.")}function BC(e,t,n){let r=new AbortController,i=()=>{r.abort(new Y("aborted",`download of ${e} was aborted`,{cause:n?.reason}))};n?.addEventListener("abort",i,{once:!0}),n?.aborted&&i();let o=setTimeout(()=>{r.abort(new Y("timeout",`download of ${e} timed out after ${t}ms`))},t);return o.unref(),{controller:r,timeout:o,detachExternalAbort:()=>n?.removeEventListener("abort",i)}}async function ng(e,t,n,r){if(!EC(e))return null;let i=ig("sha256"),o=0;try{for await(let a of IC(e,{signal:r})){let c=Buffer.isBuffer(a)?a:Buffer.from(a);if(o+=c.length,o>n)return null;i.update(c)}}catch{if(r.aborted)throw Ht(r,e);return null}let s=i.digest("hex");return s===t?s:null}async function qC(e,t,n){let r=e.fetchImpl??fetch,i;try{i=await rg(r(e.url,{signal:t.signal}),t.signal)}catch(l){throw t.signal.aborted?Ht(t.signal,e.url):new Y("stream",`failed to download ${e.url}: ${cg(l)}`,{cause:l})}if(!i.ok){let l=new Y("http",`failed to download ${e.url}: HTTP ${i.status}`);throw t.abort(l),l}let o=VC(i,n,e.url);if(!i.body)throw new Y("stream",`downloaded ${e.url} response has no readable body`);let s=`${e.cachePath}.tmp-${process.pid}-${TC()}`,a,c=!1;try{a=Yo(s,"wx",384),c=!0;let l=i.body.getReader(),d=ig("sha256"),u=0;for(;;){let{done:g,value:f}=await rg(l.read(),t.signal);if(g)break;if(!(f instanceof Uint8Array))throw new Y("stream",`downloaded ${e.url} produced a non-byte stream chunk`);if(u+=f.byteLength,u>n||o!==void 0&&u>o){let b=new Y("length",`downloaded ${e.url} exceeded its ${o??n} byte limit`);throw t.abort(b),b}let h=Buffer.from(f.buffer,f.byteOffset,f.byteLength);d.update(h),Ds(a,h,{writeFile:e.writeImpl??DC},"verified binary staging")}if(o!==void 0&&u!==o)throw new Y("length",`downloaded ${e.url} length mismatch: declared ${o} bytes, received ${u}`);let m=d.digest("hex");if(m!==e.expectedSha256)throw new Y("checksum",`downloaded ${e.url} checksum mismatch: expected ${e.expectedSha256}, got ${m}`);Kr(a),a=void 0;try{WC(s,e.cachePath,e.renameImpl??LC,e.syncImpl??jC)}catch(g){throw new Y("install",`failed to install verified binary at ${e.cachePath}`,{cause:g})}return c=!1,{status:"downloaded",path:e.cachePath,sha256:m}}catch(l){throw t.signal.aborted?Ht(t.signal,e.url):l instanceof Y?l:new Y("install",`failed to stage verified binary at ${e.cachePath}`,{cause:l})}finally{if(a!==void 0)try{Kr(a)}catch{}if(c)try{OC(s)}catch{}}}function VC(e,t,n){let r=e.headers?.get("content-length");if(r==null)return;if(!/^\d+$/.test(r))throw new Y("length",`downloaded ${n} has an invalid Content-Length header`);let i=Number(r);if(!Number.isSafeInteger(i)||i<0)throw new Y("length",`downloaded ${n} has an invalid Content-Length header`);if(i>t)throw new Y("length",`downloaded ${n} declares ${i} bytes, above the ${t} byte limit`);return i}function WC(e,t,n,r){HC(e,r),n(e,t),UC(og(t),r)}function HC(e,t){let n=Yo(e,"r");try{t(n)}finally{Kr(n)}}function UC(e,t){let n;try{n=Yo(e,"r")}catch(r){if(ci(r,process.platform))return;throw r}try{t(n)}catch(r){if(!ci(r,process.platform))throw r}finally{Kr(n)}}function rg(e,t){return t.aborted?Promise.reject(Ht(t,"operation")):new Promise((n,r)=>{let i=()=>{t.removeEventListener("abort",i),r(Ht(t,"operation"))};t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),n(o)},o=>{t.removeEventListener("abort",i),r(o)})})}function Ht(e,t){return e.reason instanceof Error?e.reason:new Y("aborted",`verified binary operation for ${t} was aborted`)}function cg(e){return e instanceof Error?e.message:String(e)}var XC=12e4,pg="v1.8.0",YC=`https://github.com/tlaplus/tlaplus/releases/download/${pg}/tla2tools.jar`,ZC="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Xr(e){let t=e.spawn??QC,n=eP(e,t);if(n.missing)return{checker:n.checker,status:"skipped",command:n.command,durationMs:0,exitCode:null,signal:null,timedOut:!1,diagnostics:[{severity:"warning",message:n.missing}],stdout:"",stderr:""};let r=e.timeoutMs??XC,i=lg.now(),o;try{o=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:r,killSignal:"SIGKILL",maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])zC(l,{recursive:!0,force:!0})}let s=Math.round(lg.now()-i),a=o.error?.name==="ETIMEDOUT"||o.signal==="SIGTERM"&&s>=r,c=a?"timed-out":o.status===0?"passed":"failed";return{checker:n.checker,status:c,command:n.command,durationMs:s,exitCode:o.status,signal:o.signal,timedOut:a,diagnostics:tP(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function eP(e,t){let n=e.checker;if(n==="none")return{checker:"none",command:["<none>"],cwd:e.projectRoot,missing:"model checker skipped by --checker none"};if(n==="apalache"||n==="auto"&&Ne(dg(e),t)){let o=dg(e);return Ne(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:Zo(e.specPath)}:Qr("apalache",`Apalache binary is not available: ${o}`)}let r=ts(e),i=Ne("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return Qr(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return Qr(n==="sany"?"sany":"tlc","java is not available on PATH");let o=n==="sany"?"sany":n==="tlc"||e.configPath?"tlc":"sany";if(o==="sany")return{checker:o,command:["java","-cp",r,"tla2sany.SANY",e.specPath],cwd:Zo(e.specPath)};let s=e.metaDir??JC(es(KC(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:Zo(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Qr("none",`unknown checker mode: ${n}`)}function dg(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function ts(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,mg(t),es(e.projectRoot,"tla2tools.jar"),es(e.projectRoot,"tools","tla2tools.jar")].filter(r=>typeof r=="string"&&r.length>0).find(r=>GC(r))??null}function mg(e=process.env){return sg("tla2tools.jar",e)}async function fg(e={}){let t=e.cachePath??mg(e.env),n=e.expectedSha256??ZC,r=e.version??pg,i=e.url??YC;return{...await ag({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,maxBytes:e.maxBytes,signal:e.signal}),version:r,url:i}}function tP(e,t,n){if(e==="passed")return[{severity:"info",message:"model checker completed successfully"}];if(e==="timed-out")return[{severity:"error",message:"model checker timed out"}];let r=[...ug(n),...ug(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function ug(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Qr(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as nP}from"crypto";import{readFileSync as hg}from"fs";import{join as yg}from"path";var bg=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),Sg=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),vg=new Set(["readFileSync","existsSync","statSync"]),rP=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,iP=/^\s*SELECT\b/i;function Rg(e){return rP.test(e)?"write":iP.test(e)?"read":null}var oP=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function sP(e,t){let n=e.match(oP);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${Me(t)}\\b`).test(r)}function xg(e,t,n,r=[],i=[]){let o=[],s=lP(e,t,o),a=s.aliases,c=dP(t),l=uP(t),d=pP(t),u=gP(e,t,o),m=yP(e,t,o);n&&bP(t,n,i,o);let g=new Map((n?.actions??[]).map(v=>[v.name,v])),f=new Set(u.flatMap(v=>v.referents.map(R=>R.match?.symbol).filter(Boolean))),h=new Set((m?.referents??[]).map(v=>v.match?.symbol).filter(Boolean)),b=SP(e,t,u,a,c,l,d,f,h,o,g),y=xP(e,u,a,c,l,d,o,g);return wP(e,u,o),$P(t,r,o),{modelParse:n?.modelParse??"unavailable",modelVariables:n?.variables??[],modelOperators:n?.operators??[],modelActionFacts:n?.actions??[],mappedVariables:Object.keys(t.variables).length,mappedActions:Object.keys(t.actions).length,resolvedReferents:rs(u.flatMap(v=>v.referents))+rs(s.referents)+rs(m?.referents??[]),staticWrites:b,staticReads:y,waivers:UP(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:aP(o)}}function aP(e){let t=new Map;for(let n of e){let r=`${n.category}:${n.modelElement??"-"}`,i=t.get(r);i||(i={groupKey:r,category:n.category,modelElement:n.modelElement,severity:n.severity,count:0,findingIds:[]},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=cP(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||Yr(r.severity)-Yr(n.severity)||n.groupKey.localeCompare(r.groupKey))}function cP(e,t){return Yr(t)>Yr(e)?t:e}function Yr(e){return e==="error"?2:e==="warning"?1:0}function lP(e,t,n){let r=[],i=[];for(let[o,s]of Object.entries(t.variables)){let a=new Set(s.aliases),c=!!s.waive;for(let l of s.code){let d=ti(e,l,n,o);i.push(d);let u=d.match;if(!u){c||n.push(J("missing-referent","error","compiler-symbol",{modelElement:o,codeRef:l,message:`TLA+ variable ${o} maps to missing TypeScript referent ${l}.`,why:["The mapping contract must point at live compiler-indexed code before conformance can be checked."],remediation:`Update variables.${o}.code to a live symbol, or remove the variable from the model mapping.`}));continue}_P(e,o,l,u,n,c),s.aliases.length===0&&a.add(ks(u.symbol))}for(let l of a)r.push({variable:o,alias:l})}return{aliases:HP(r),referents:i}}function dP(e){let t=[];for(let[n,r]of Object.entries(e.variables))r.resource&&t.push({variable:n,path:r.resource.path});return t}function uP(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.statements??[])t.push({variable:n,pattern:i.pattern,regex:new RegExp(i.pattern)});return t}function pP(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=Uo(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function mP(e,t,n,r,i,o){return kg(e,t,(s,a,c)=>St(e,s,a,c,n,r,i,o))}function fP(e,t,n,r,i,o){return kg(e,t,(s,a,c)=>ei(e,s,a,c,n,r,i,o))}function kg(e,t,n){let r=tn(e,t,{semantic:!1});if(!r)return[];let i=[],o=new Set;for(let s of r.callees){if(o.has(s.symbol))continue;o.add(s.symbol);let a=Mn(e,s.symbol).match;if(a)for(let c of n(a.relativePath,a.startLine,a.endLine))i.push({...c,via:s.shortName})}return i}function gP(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=Go(s),c="error"in a?s:a.ref,d=ti(e,c,n,r).match;return d?(BP(e,r,s,d,n),"error"in a||!a.window?{ref:s,match:d}:hP(a.window,d)?(n.push(J("invalid-line-window","error","compiler-symbol",{modelElement:r,codeRef:s,file:d.relativePath,startLine:d.startLine,endLine:d.endLine,message:`TLA+ action ${r} codeRef line window L${a.window.startLine}-L${a.window.endLine} falls outside ${ee(d.symbol)}'s actual span L${d.startLine+1}-L${d.endLine+1} in ${d.relativePath}.`,why:[`${s} resolves to ${ee(d.symbol)} at ${d.relativePath}:${d.startLine+1}-${d.endLine+1}.`,"The requested window does not fall entirely inside that span."],remediation:`Update the @L${a.window.startLine}-L${a.window.endLine} window in actions.${r}.code to fall within L${d.startLine+1}-L${d.endLine+1}, or drop the window to cover the whole function.`})),{ref:s,match:null}):{ref:s,match:d,window:{startLine:a.window.startLine-1,endLine:a.window.endLine-1}}):(n.push(J("missing-referent","error","compiler-symbol",{modelElement:r,codeRef:s,message:`TLA+ action ${r} maps to missing TypeScript referent ${s}.`,why:["The action cannot be compared to code because the mapped symbol did not resolve in the SCIP index."],remediation:`Update actions.${r}.code to a live function or method symbol.`})),{ref:s,match:null})});return{name:r,mapping:i,referents:o}})}function hP(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function yP(e,t,n){let r=t.init;if(!r)return;let i=!!r.waive,o=r.codeRefs.map(s=>{let a=ti(e,s,n,"Init"),c=a.match;return c?qP(e,s,c,n,i):i||n.push(J("missing-referent","error","compiler-symbol",{modelElement:"Init",codeRef:s,message:`TLA+ Init maps to missing TypeScript referent ${s}.`,why:["The Init mapping must point at live compiler-indexed code before conformance can be checked."],remediation:"Update init.codeRefs to a live function or method symbol, or remove the stale entry."})),a});return{mapping:r,referents:o}}function bP(e,t,n,r){let i=new Set(t.variables),o=new Set(t.operators),s=new Set(n);for(let a of Object.keys(e.variables))i.has(a)||r.push(J("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ variable ${a} is not declared in the module.`,why:["The mapping names a model variable, but the TLA+ module text does not declare it with VARIABLE(S)."],remediation:`Declare ${a} in the TLA+ module or remove it from the mapping.`}));for(let a of Object.keys(e.actions))o.has(a)||r.push(J("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ action ${a} is not defined in the module.`,why:["The mapping names a model action, but the TLA+ module text has no matching operator definition."],remediation:`Define ${a} == ... in the TLA+ module or update the mapping action name.`}));for(let a of t.actions){let c=e.actions[a.name];c&&(gg({action:a.name,field:"writes",modelValues:a.writes,mappingValues:c.writes,missingInMappingCategory:"model-mapping-write",missingInModelCategory:"model-mapping-write",findings:r,file:t.path,isWaived:l=>!!c.waive?.writes.includes(l)}),gg({action:a.name,field:"reads",modelValues:a.reads,mappingValues:c.reads,missingInMappingCategory:"model-mapping-read",missingInModelCategory:"model-mapping-read",findings:r,file:t.path}))}for(let a of e.invariants)s.has(a)||r.push(J("missing-invariant","warning","model-text",{modelElement:a,file:t.path,message:`Mapping lists invariant ${a}, but the checker config does not include it.`,why:["The model mapping names an invariant that was not found in INVARIANT lines of the selected config."],remediation:`Add INVARIANT ${a} to the config used for this run, or remove it from the mapping invariants list.`}))}function gg(e){let t=new Set(e.modelValues),n=new Set(e.mappingValues),r=e.isWaived??(()=>!1);for(let i of t)n.has(i)||r(i)||e.findings.push(J(e.missingInMappingCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`TLA+ action ${e.action} ${e.field==="writes"?"writes":"reads"} ${i}, but the mapping does not declare that ${e.field.slice(0,-1)}.`,why:[`SANY-derived model facts list ${i} in ${e.action}.${e.field}, while the mapping omits it.`],remediation:`Add ${i} to actions.${e.action}.${e.field}, or update the TLA+ model if the ${e.field.slice(0,-1)} is unintended.`}));for(let i of n)t.has(i)||r(i)||e.findings.push(J(e.missingInModelCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`Mapping declares ${e.action}.${e.field} includes ${i}, but the SANY model facts do not.`,why:[`The mapping says ${e.action} ${e.field==="writes"?"writes":"reads"} ${i}, but the parsed TLA+ action does not show that model-side fact.`],remediation:`Update the TLA+ action to ${e.field==="writes"?"prime":"reference"} ${i}, remove the mapping declaration, or add a waiver if static evidence cannot represent the model boundary.`}))}function SP(e,t,n,r,i,o,s,a,c,l,d){let u=[];for(let g of n){let f=[];for(let h of g.referents){if(!h.match)continue;let b=h.window??{startLine:h.match.startLine,endLine:h.match.endLine},y=St(e,h.match.relativePath,b.startLine,b.endLine,r,i,o,s);f.push(...y),u.push(...y);let v=new Set(g.mapping.writes),R=mP(e,h.match.symbol,r,i,o,s).filter(T=>v.has(T.variable));f.push(...R),u.push(...R)}RP(g,f,l,d.get(g.name))}let m=t.unmappedWriteScope==="actions"?[]:FP(e,t);for(let g of m)for(let f of St(e,g,0,Number.POSITIVE_INFINITY,r,i,o,s))u.push(f),vP(f)&&(f.enclosingSymbol&&(a.has(f.enclosingSymbol)||c.has(f.enclosingSymbol))||l.push(J("unmapped-write","error","static-action",{modelElement:f.variable,codeRef:f.enclosingSymbol??`${f.file}:${f.line+1}`,file:f.file,startLine:f.line,endLine:f.line,message:`Modeled variable ${f.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${f.target} at ${f.file}:${f.line+1}.`,f.enclosingShort?`The write is inside ${f.enclosingShort}, which is not mapped as a model action.`:"The write is outside an indexed callable definition."],remediation:`Map the enclosing code to a TLA+ action, remove the write, or remove ${f.variable} from the modeled slice if it is intentionally out of scope.`})));return ss(u)}function vP(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function RP(e,t,n,r){let i=new Set(e.mapping.writes),o=new Set(t.map(a=>a.variable)),s=new Set(r?.writes??[]);for(let a of t)r&&!s.has(a.variable)&&!Cn(e,"write",a.variable)&&n.push(J("model-code-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} writes ${a.variable}, but the SANY model action does not prime it.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Zr(a.via)}.`,`SANY-derived model facts for ${e.name} list writes: ${r.writes.join(", ")||"none"}.`],remediation:`Prime ${a.variable} in the TLA+ action, remove the code write from this action, or remap the code to the correct action.`})),!i.has(a.variable)&&!Cn(e,"write",a.variable)&&n.push(J("undeclared-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} writes modeled variable ${a.variable}, but the mapping does not declare that write.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Zr(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.writes, update the model action, or change the code so it no longer mutates that modeled variable.`}));for(let a of i)!o.has(a)&&!Cn(e,"write",a)&&n.push(J("missing-write-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a write to ${a}, but no direct source write was found.`,why:["The write may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the write sink as a mapped action referent, provide a trace, or waive actions.${e.name}.writes.${a} with a specific reason.`}))}function xP(e,t,n,r,i,o,s,a){let c=[];for(let l of t){let d=[];for(let u of l.referents){if(!u.match)continue;let m=u.window??{startLine:u.match.startLine,endLine:u.match.endLine},g=ei(e,u.match.relativePath,m.startLine,m.endLine,n,r,i,o);d.push(...g),c.push(...g);let f=new Set(l.mapping.reads),h=fP(e,u.match.symbol,n,r,i,o).filter(b=>f.has(b.variable));d.push(...h),c.push(...h)}kP(l,d,s,a.get(l.name))}return as(c)}function kP(e,t,n,r){let i=new Set(e.mapping.reads),o=new Set(t.map(a=>a.variable)),s=new Set(r?.reads??[]);for(let a of t)r&&!s.has(a.variable)&&n.push(J("model-code-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} reads ${a.variable}, but the SANY model action does not reference it.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Zr(a.via)}.`,`SANY-derived model facts for ${e.name} list reads: ${r.reads.join(", ")||"none"}.`],remediation:`Reference ${a.variable} in the TLA+ action, remove the code read from this action, or remap the code to the correct action.`})),!i.has(a.variable)&&!Cn(e,"read",a.variable)&&n.push(J("undeclared-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} reads modeled variable ${a.variable}, but the mapping does not declare that read.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Zr(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.reads, update the model action, or waive the read with a specific reason if it is intentionally outside the model step.`}));for(let a of i)!o.has(a)&&!Cn(e,"read",a)&&n.push(J("missing-read-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a read of ${a}, but no direct source read was found.`,why:["The read may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the read source as a mapped action referent, provide a trace, or waive actions.${e.name}.reads.${a} with a specific reason.`}))}function wP(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>ti(e,s,n,r.name));for(let s of i)s.match||n.push(J("missing-referent","error","compiler-symbol",{modelElement:r.name,codeRef:s.ref,message:`actions.${r.name}.calls contains missing TypeScript referent ${s.ref}.`,why:["Declared call checks require the expected callee to resolve in the SCIP index."],remediation:`Update actions.${r.name}.calls to a live symbol or remove the stale call expectation.`}));let o=new Set(i.map(s=>s.match?.symbol).filter(Boolean));for(let s of r.referents){if(!s.match)continue;let a=tn(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of o)c.has(l)||n.push(J("missing-call","error","compiler-symbol",{modelElement:r.name,codeRef:s.ref,file:s.match.relativePath,startLine:s.match.startLine,endLine:s.match.endLine,message:`TLA+ action ${r.name} no longer calls ${ee(l)} from ${s.ref}.`,why:["The mapping declares a call dependency that is absent from the current compiler-resolved call graph."],remediation:`Update actions.${r.name}.calls, update the TLA+ action, or restore the code path if the call is required.`}))}}}function $P(e,t,n){for(let[r,i]of t.entries()){let o=e.actions[i.action];if(!o){n.push(J("trace","error","trace",{modelElement:i.action,codeRef:i.code,message:`Trace step ${r} uses action ${i.action}, which is not mapped.`,why:["Every observed trace action must map to a TLA+ action before trace conformance can be checked."],remediation:`Add actions.${i.action} to the mapping, or fix the trace action name.`}));continue}let s=WP(i),a=new Set(o.writes);for(let c of s)a.has(c)||n.push(J("trace","error","trace",{modelElement:i.action,codeRef:i.code,message:`Trace step ${r} changed ${c}, but action ${i.action} does not declare that write.`,why:["The runtime trace observed a state change outside the action write set."],remediation:`Update actions.${i.action}.writes, update the TLA+ model, or investigate the code path that changed ${c}.`}))}}function St(e,t,n,r,i,o=[],s=[],a=[]){let c=CP(e,t,n,r,i,o,s,a);return c||OP(e,t,n,r,i,o,s,a)}function ei(e,t,n,r,i,o=[],s=[],a=[]){let c=PP(e,t,n,r,i,o,s,a);return c||DP(e,t,n,r,i,o,s,a)}function CP(e,t,n,r,i,o=[],s=[],a=[]){let c=ai(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){TP(e,t,u,i,l),wg(e,t,u,o,"write",l),$g(e,t,u,s,"write",l),Cg(e,t,u,a,"write",l);for(let m of u.children)d(m)}};return d(c.rootNode),ss(l)}function PP(e,t,n,r,i,o=[],s=[],a=[]){let c=ai(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){jP(e,t,u,i,l),wg(e,t,u,o,"read",l),$g(e,t,u,s,"read",l),Cg(e,t,u,a,"read",l);for(let m of u.children)d(m)}};return d(c.rootNode),as(l)}function TP(e,t,n,r,i){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&$n(e,t,o,"assignment",r,i);return}if(n.type!=="variable_declarator"){if(n.type==="pair"){let o=n.childForFieldName("key")??n.namedChild(0);o&&$n(e,t,o,"object-field",r,i);return}if(n.type==="update_expression"){let o=n.namedChildren.find(s=>s.type!=="++"&&s.type!=="--")??n.namedChild(0);o&&$n(e,t,o,"update",r,i);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&$n(e,t,o,"delete",r,i);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!Tg(o))return;$n(e,t,o,"mutation-call",r,i)}}}function wg(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?is(s):null;if(!a||!(i==="write"?Sg:vg).has(a))return;let d=n.childForFieldName("arguments")?.namedChild(0);if(!d)return;let u=d.text;for(let m of r){if(!u.includes(m.path))continue;let g=De(e,t,n.startPosition.row);o.push({variable:m.variable,alias:m.path,file:t,line:n.startPosition.row,target:`${a}(${u})`,kind:"resource",enclosingSymbol:g?.symbol,enclosingShort:g?ee(g.symbol):void 0})}}function is(e){if(e.type==="identifier")return e.text;if(e.type==="member_expression"){let t=e.namedChild(e.namedChildCount-1);return t?t.text:null}return null}function $g(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("arguments");if(s)for(let a of s.namedChildren){let c=IP(a);if(c!==null&&Rg(c)===i)for(let l of r){if(!l.regex.test(c))continue;let d=De(e,t,n.startPosition.row),u=n.childForFieldName("function")??n.namedChild(0),m=(u&&is(u))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${m}(${EP(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?ee(d.symbol):void 0})}}}function IP(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function EP(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function Cg(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?is(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let d=l.text.trim();for(let u of r){if(!Pg(u,a,d,i))continue;let m=De(e,t,n.startPosition.row);o.push({variable:u.variable,alias:u.table,file:t,line:n.startPosition.row,target:`${a}(${d})`,kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?ee(m.symbol):void 0})}}function Pg(e,t,n,r){return n!==e.table?!1:r==="write"?e.writeMethods.has(t):e.readMethods.has(t)||t==="from"&&e.readMethods.has("select")}function jP(e,t,n,r,i){if(!(!AP(n)||LP(n)))for(let o of r){if(n.text!==o.alias)continue;let s=De(e,t,n.startPosition.row);i.push({variable:o.variable,alias:o.alias,file:t,line:n.startPosition.row,target:n.text,kind:"identifier",enclosingSymbol:s?.symbol,enclosingShort:s?ee(s.symbol):void 0})}}function AP(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function LP(e){let t=e.parent;for(;t;){if(t.type==="assignment_expression"||t.type==="augmented_assignment_expression"){let n=t.childForFieldName("left")??t.namedChild(0);return!!(n&&ns(n,e))}if(t.type==="update_expression"||t.type==="unary_expression"&&/^\s*delete\b/.test(t.text))return!0;if(t.type==="pair"){let n=t.childForFieldName("key")??t.namedChild(0);return!!(n&&ns(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&Tg(n)&&ns(n,e))return!0}if(t.type.endsWith("statement")||t.type==="function_declaration"||t.type==="method_definition")return!1;t=t.parent}return!1}function ns(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function Tg(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&bg.has(t.text))}function $n(e,t,n,r,i,o){for(let s of i){if(!VP(s.alias,n.text))continue;let a=De(e,t,n.startPosition.row);o.push({variable:s.variable,alias:s.alias,file:t,line:n.startPosition.row,target:n.text,kind:r,enclosingSymbol:a?.symbol,enclosingShort:a?ee(a.symbol):void 0})}}function OP(e,t,n,r,i,o=[],s=[],a=[]){let l=hg(yg(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],u=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=u;m+=1){let g=l[m]??"";for(let f of i){if(sP(g,f.alias))continue;let h=Me(f.alias);if(!new RegExp(`(?:\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${h}\\b\\s*\\.\\s*(?:${[...bg].join("|")})\\s*\\(|\\b${h}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(g))continue;let y=De(e,t,m);d.push({variable:f.variable,alias:f.alias,file:t,line:m,target:g.trim(),kind:"source-scan",enclosingSymbol:y?.symbol,enclosingShort:y?ee(y.symbol):void 0})}Ig(e,t,m,g,o,Sg,d),Eg(e,t,m,g,s,"write",d),jg(e,t,m,g,a,"write",d)}return ss(d)}function DP(e,t,n,r,i,o=[],s=[],a=[]){let l=hg(yg(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],u=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=u;m+=1){let g=l[m]??"";for(let f of i){let h=Me(f.alias);if(!new RegExp(`\\b${h}\\b`).test(g)||new RegExp(`\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(g))continue;let b=De(e,t,m);d.push({variable:f.variable,alias:f.alias,file:t,line:m,target:g.trim(),kind:"source-scan",enclosingSymbol:b?.symbol,enclosingShort:b?ee(b.symbol):void 0})}Ig(e,t,m,g,o,vg,d),Eg(e,t,m,g,s,"read",d),jg(e,t,m,g,a,"read",d)}return as(d)}function Ig(e,t,n,r,i,o,s){if(i.length!==0)for(let a of o){let c=r.indexOf(`${a}(`);if(c===-1)continue;let l=r.slice(c+a.length);for(let d of i){if(!l.includes(d.path))continue;let u=De(e,t,n);s.push({variable:d.variable,alias:d.path,file:t,line:n,target:r.trim(),kind:"resource",enclosingSymbol:u?.symbol,enclosingShort:u?ee(u.symbol):void 0})}}}function Eg(e,t,n,r,i,o,s){if(i.length!==0&&Rg(r)===o)for(let a of i){if(!a.regex.test(r))continue;let c=De(e,t,n);s.push({variable:a.variable,alias:a.pattern,file:t,line:n,target:r.trim(),kind:"statement",enclosingSymbol:c?.symbol,enclosingShort:c?ee(c.symbol):void 0})}}function jg(e,t,n,r,i,o,s){if(i.length!==0)for(let a of r.matchAll(/\.([A-Za-z_$][\w$]*)\s*\(\s*([^,)\s][^,)]*?)\s*\)/g)){let c=a[1],l=a[2].trim();for(let d of i){if(!Pg(d,c,l,o))continue;let u=De(e,t,n);s.push({variable:d.variable,alias:d.table,file:t,line:n,target:r.trim(),kind:"orm-call",enclosingSymbol:u?.symbol,enclosingShort:u?ee(u.symbol):void 0})}}}function FP(e,t){let n=t.scope??[];return n.length===0?[]:e.all("SELECT relative_path FROM documents ORDER BY relative_path").map(i=>i.relative_path).filter(i=>n.some(o=>i.includes(o)))}function ti(e,t,n,r){let i=Mn(e,t),o=i.match??(t.includes("#")?Mn(e,t.replace("#","/")).match:null);return i.match&&i.total>1&&!MP(t)&&n.push(J("ambiguous-referent","warning","compiler-symbol",{modelElement:r,codeRef:t,file:i.match.relativePath,startLine:i.match.startLine,endLine:i.match.endLine,message:`Mapping referent ${t} resolved ambiguously to ${ee(i.match.symbol)}.`,why:[`${i.total} indexed definitions share this lookup shape.`,NP(i.candidates)].filter(Boolean),remediation:`Qualify ${t} with a path or fuller symbol name so the mapping cannot drift to another definition.`})),{ref:t,match:o}}function MP(e){return/[/#:]/.test(e)}function NP(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function _P(e,t,n,r,i,o=!1){let s=os(e,r);if(s===null||GP.has(s)||o)return;let a=cs.has(s);i.push(J("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${Xt(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${ee(r.symbol)} with SCIP kind ${Xt(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function BP(e,t,n,r,i){let o=os(e,r);o===null||Ag.has(o)||cs.has(o)&&i.push(J("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${ee(r.symbol)} with SCIP kind ${Xt(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function qP(e,t,n,r,i){let o=os(e,n);o===null||Ag.has(o)||i||cs.has(o)&&r.push(J("invalid-referent-kind","error","compiler-symbol",{modelElement:"Init",codeRef:t,file:n.relativePath,startLine:n.startLine,endLine:n.endLine,message:"TLA+ Init referent is a type; map the runtime initialization code it describes.",why:[`${t} resolves to ${ee(n.symbol)} with SCIP kind ${Xt(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function os(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function De(e,t,n){return Fn(e,t).filter(i=>i.startLine<=n&&i.endLine>=n).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine))[0]??null}function VP(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Me(e)}([^A-Za-z0-9_$]|$)`).test(t)}function WP(e){return!e.before||!e.after?[]:[...new Set([...Object.keys(e.before),...Object.keys(e.after)])].filter(n=>JSON.stringify(e.before?.[n])!==JSON.stringify(e.after?.[n]))}function ss(e){let t=new Set,n=[];for(let r of e){let i=`${r.variable}:${r.file}:${r.line}:${r.target}:${r.enclosingSymbol??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function as(e){let t=new Set,n=[];for(let r of e){let i=`${r.variable}:${r.file}:${r.line}:${r.target}:${r.enclosingSymbol??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function HP(e){let t=new Set;return e.filter(n=>{let r=`${n.variable}:${n.alias}`;return t.has(r)?!1:(t.add(r),!0)})}function rs(e){return e.filter(t=>t.match).length}function Zr(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function Cn(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function UP(e){let t=Object.entries(e.actions).flatMap(([o,s])=>{let a=s.waive;return a?[...(a.reads??[]).map(c=>({action:o,kind:"read",variable:c,reason:a.reason,legacy:a.legacy===!0})),...(a.writes??[]).map(c=>({action:o,kind:"write",variable:c,reason:a.reason,legacy:a.legacy===!0}))]:[]}),n=Object.entries(e.variables).flatMap(([o,s])=>{let a=s.waive;return a?[{kind:"referent",variable:o,reason:a.reason,legacy:!1}]:[]}),r=e.init?.waive,i=r?[{kind:"referent",variable:"Init",reason:r.reason,legacy:!1}]:[];return[...t,...n,...i]}var cs=new Set(Ps()),Ag=new Set(Cs()),GP=new Set(Ts());function J(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${nP("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{readFileSync as JP}from"fs";import{basename as zP,join as Lg}from"path";var ls=/^[A-Za-z_][A-Za-z0-9_]*$/;function Og(e,t,n={}){let r=[],i=Fn(e,t,{includeClassMemberFallbacks:!0});if(i.length===0)throw new Error(`no indexed definitions found for ${t}; run 'scip-query reindex' or check the path`);let s=JP(Lg(e.config.projectRoot,t),"utf8").split(/\r?\n/),a=j=>j.symbol.trimEnd().endsWith("()."),c=i.filter(j=>!a(j)&&!j.isTypeLike&&j.parentTypeName===null&&ls.test(j.leaf)),l=c.map(j=>({variable:j.leaf,alias:j.leaf})),d=l.length>0?St(e,t,0,Number.POSITIVE_INFINITY,l):[],u=new Set(d.map(j=>j.variable)),m=c.filter(j=>u.has(j.leaf)?!0:XP(s,j)),g=null,f;if(m.length>0)f=i.filter(j=>a(j)&&j.parentTypeName===null);else{if(g=KP(e,t,i,a),!g){let j=i.some(M=>!a(M)&&!M.isTypeLike&&M.parentTypeName!==null&&ls.test(M.leaf));throw new Error(`no mutable state discovered in ${t} \u2014 the static write scan found no writes to top-level variables, no top-level let declarations exist, and `+(j?"no class in this file has an instance field the write scan can confirm is mutated by one of its own methods.":"no class instance-field definitions were exposed for this file at all \u2014 the indexer emitted no member rows (neither a primary defn_enclosing_ranges row nor a role=1 mention) for any class in this file, so there is nothing for getDefinitionsForFile to surface even with class-member fallbacks included (docs/plans/2026-07-02-catalog-class-members.md).")+" Pick a file that owns runtime state.")}m=g.fields,f=g.methods,r.push(`state scoped to class ${g.className} (${t}): scaffolded actions are drawn only from its own methods \u2014 other classes or top-level functions in this file are not considered.`)}let h=m.map(j=>YP(j,s,t,r,g?.className)),b=h.map(j=>({variable:j.name,alias:j.leaf})),y=[],v=new Set;for(let j of f){let M=St(e,t,j.startLine,j.endLine,b);if(M.length===0)continue;let K=ei(e,t,j.startLine,j.endLine,b),N=nT(Dg(j.leaf),v);y.push({name:N,leaf:j.leaf,codeRef:QP(t,j,g?.className),startLine:j.startLine,writes:[...new Set(M.map(G=>G.variable))].sort(),reads:[...new Set(K.map(G=>G.variable))].sort()})}y.length===0&&r.push("no top-level callable writes the discovered state; the generated Next relation is empty and the model cannot step. State may be mutated through methods, callbacks, or other files \u2014 narrow or widen the target.");let R=n.moduleName??rT(t),T=n.specDir??Lg("specs",R),D=iT(R,h,y,t),C=oT(),U=sT(R,T,t,h,y);return{moduleName:R,file:t,variables:h,actions:y,warnings:r,spec:D,cfg:C,map:U}}function KP(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!ls.test(s.leaf))continue;let a=i.get(s.parentTypeName);a?a.push(s):i.set(s.parentTypeName,[s])}let o=null;for(let[s,a]of i){let c=n.filter(m=>r(m)&&m.parentTypeName===s),l=a.map(m=>({variable:m.leaf,alias:m.leaf})),d=new Set;for(let m of c)for(let g of St(e,t,m.startLine,m.endLine,l))d.add(g.variable);let u=a.filter(m=>d.has(m.leaf));u.length!==0&&(!o||u.length>o.fields.length)&&(o={className:s,fields:u,methods:c})}return o}function QP(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function XP(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function YP(e,t,n,r,i){let o=ZP(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=eT(e.leaf,o);return a||r.push(`variable ${e.leaf} (${n}:${e.startLine+1}): domain not inferable from the declared type \u2014 fill in the TODO domain before model checking.`),l||r.push(`variable ${e.leaf} (${n}:${e.startLine+1}): initial value not inferable \u2014 fill in the TODO in Init.`),{name:s,leaf:e.leaf,codeRef:i?`${n}/${i}#${e.leaf}`:`${n}/${e.leaf}`,declarationLine:e.startLine,initTla:l,domainTla:a,domainBasis:c}}function ZP(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function eT(e,t){let r=t.match(new RegExp(`\\b${aT(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=tT(r);l?(s=`{${l.map(d=>`"${d}"`).join(", ")}}`,a="union-literal"):/^boolean\b/.test(r)?(s="BOOLEAN",a="boolean"):(/\[\]\s*$/.test(r)||/^(Array|ReadonlyArray)</.test(r))&&(a="sequence",s=null)}let c=null;if(o){let l=o.match(/^['"]([^'"]*)['"]/);l?c=`"${l[1]}"`:/^(true|false)\b/.test(o)?c=o.startsWith("true")?"TRUE":"FALSE":/^-?\d+\b/.test(o)?c=o.match(/^-?\d+/)[0]:/^\[\s*\]/.test(o)&&(c="<<>>")}return{domainTla:s,domainBasis:a,initTla:c}}function tT(e){let t=e.split("|").map(r=>r.trim());if(t.length<2)return null;let n=[];for(let r of t){let i=r.match(/^['"]([^'"]*)['"]$/);if(!i)return null;n.push(i[1])}return n}function Dg(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function nT(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function rT(e){let n=zP(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return Dg(n||"Model")}function iT(e,t,n,r){let i=t.map(s=>s.name),o=[];o.push(`---- MODULE ${e} ----`),o.push(`\\* Scaffolded by 'scip-query tla scaffold ${r}'.`),o.push("\\* Draft evidence tier: state from the static write scan, domains from"),o.push("\\* declared types, actions from top-level callables that write state."),o.push("\\* Review every TODO before trusting a green model-check run."),o.push("EXTENDS Naturals, Sequences, TLC"),o.push(""),o.push(`VARIABLES ${i.join(", ")}`),o.push(""),o.push(`vars == <<${i.join(", ")}>>`),o.push("");for(let s of t){if(s.domainBasis==="sequence")continue;let a=s.domainTla??'{ "TODO" } \\* TODO: declare the domain';o.push(`${s.name}Domain == ${a}`)}o.push(""),o.push("Init ==");for(let s of t){let a=s.initTla??`${s.name}Domain \\* TODO: replace with the concrete initial value (\\in used)`;o.push(s.initTla!==null?` /\\ ${s.name} = ${s.initTla}`:` /\\ ${s.name} \\in ${a}`)}o.push("");for(let s of n){let a=i.filter(c=>!s.writes.includes(c));o.push(`\\* Derived from ${s.codeRef} (writes: ${s.writes.join(", ")||"none"})`),o.push(`${s.name} ==`),o.push(` /\\ TRUE \\* TODO guard: encode the enabling condition of ${s.leaf}()`);for(let c of s.writes){let d=t.find(u=>u.name===c)?.domainBasis==="sequence"?'Seq({"TODO"})':`${c}Domain`;o.push(` /\\ ${c}' \\in ${d} \\* TODO: tighten to the concrete transition`)}a.length>0&&o.push(` /\\ UNCHANGED <<${a.join(", ")}>>`),o.push("")}if(o.push("Next =="),n.length===0)o.push(" FALSE \\* TODO: no state-writing callables were discovered");else for(let[s,a]of n.entries())o.push(` \\/ ${a.name}`);o.push(""),o.push("Spec == Init /\\ [][Next]_vars"),o.push(""),o.push("TypeOK ==");for(let s of t)s.domainBasis==="sequence"?o.push(` /\\ ${s.name} \\in Seq({"TODO"}) \\* TODO: element domain`):o.push(` /\\ ${s.name} \\in ${s.name}Domain`);return o.push("===="),o.push(""),o.join(`
561
- `)}function oT(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
562
- `)}function sT(e,t,n,r,i){let o={module:`${t}/${e}.tla`,config:`${t}/${e}.cfg`,scope:[n],derived:{generatedBy:"scip-query tla scaffold",basis:"static-scan",generatedFrom:n},variables:Object.fromEntries(r.map(s=>[s.name,{code:[s.codeRef],aliases:[s.leaf]}])),actions:Object.fromEntries(i.map(s=>[s.name,{code:[s.codeRef],reads:s.reads,writes:s.writes,calls:[]}])),invariants:["TypeOK"],traces:[]};return`${JSON.stringify(o,null,2)}
563
- `}function aT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fg(e,t){let n=Object.keys(t.variables),r=Object.entries(t.actions).map(([i,o])=>{let s=o.code[0]??"",a=s?$s(e,s):null;return{action:i,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:cT(n),wiring:r,variables:n}}function cT(e){return`/**
564
- * Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
565
- *
566
- * Usage inside a mapped action (record the model-visible slice around the
567
- * mutation):
568
- *
569
- * import { tlaRecord } from './scip-tla-recorder.js';
570
- * export function enqueue(job: string) {
571
- * const before = snapshot();
572
- * queue.push(job);
573
- * tlaRecord('Enqueue', before, snapshot());
574
- * }
575
- *
576
- * where snapshot() projects the mapped variables to JSON scalars \u2014 fill in
577
- * each field with the real runtime value, e.g.
578
- * const snapshot = () => ({ ${e.map(t=>`${t}: undefined`).join(", ")} }); // fill in each field
579
- *
580
- * Recording is enabled only when SCIP_TLA_TRACE names an output path, so the
581
- * wiring is safe to leave in place. The output is a JSON array compatible
582
- * with 'scip-query tla trace-check --trace <path>'.
583
- */
584
- import { readFileSync, writeFileSync } from 'node:fs';
585
-
586
- interface TlaTraceStep {
587
- action: string;
588
- before: Record<string, unknown>;
589
- after: Record<string, unknown>;
590
- }
591
-
592
- const tracePath = process.env['SCIP_TLA_TRACE'];
593
-
594
- export function tlaRecord(action: string, before: Record<string, unknown>, after: Record<string, unknown>): void {
595
- if (!tracePath) return;
596
- let steps: TlaTraceStep[] = [];
597
- try {
598
- steps = JSON.parse(readFileSync(tracePath, 'utf8')) as TlaTraceStep[];
599
- if (!Array.isArray(steps)) steps = [];
600
- } catch {
601
- steps = [];
602
- }
603
- steps.push({ action, before, after });
604
- writeFileSync(tracePath, JSON.stringify(steps, null, 2));
605
- }
606
- `}import{copyFileSync as lT,mkdtempSync as dT,readdirSync as uT,rmSync as pT,writeFileSync as Mg}from"fs";import{tmpdir as mT}from"os";import{basename as fT,dirname as gT,join as Pn}from"path";function ni(e,t){let n=new Map;for(let r of t)n.set(r.action,(n.get(r.action)??0)+1);return e.map(r=>({action:r,stepsObserved:n.get(r)??0}))}function hT(e,t,n,r="Next"){if(n.length===0)return{error:"trace has no steps"};let i=[],o=n[0];if(!o.before)return{error:"trace step 0 must include a full `before` state"};let s=[],a={...o.before},c=h=>{let b={};for(let[y,v]of Object.entries(h)){if(!t.includes(y))continue;let R=bT(v);R!==void 0&&(b[y]=R)}return b};s.push(c(a));for(let h of n){if(h.before)for(let[b,y]of Object.entries(h.before))b in a||(a[b]=y);Object.assign(a,h.after??{}),s.push(c(a))}let l=t.filter(h=>s.every(b=>h in b)),d=t.filter(h=>!l.includes(h));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};d.length>0&&i.push(`variables not pinned by the trace (missing or non-scalar values): ${d.join(", ")} \u2014 divergence in these variables is NOT checked.`);let u=`${e}Trace`,m=s.map(h=>` [${l.map(b=>`${b} |-> ${_g(h[b])}`).join(", ")}]`).join(`,
607
- `),g=[`---- MODULE ${u} ----`,"\\* Generated trace-validation harness. Checks that the recorded execution",`\\* is a behavior of ${e}!${r}. TLC deadlocks at the first`,"\\* divergent step; a clean run means the model accepts the trace.",`EXTENDS ${e}, Naturals, Sequences`,"","VARIABLE traceIdx","","TraceStates ==","<<",m,">>","","TraceInit =="," /\\ traceIdx = 1",...l.map(h=>` /\\ ${h} = TraceStates[1].${h}`),"","TraceStep =="," /\\ traceIdx < Len(TraceStates)"," /\\ traceIdx' = traceIdx + 1",` /\\ ${r}`,...l.map(h=>` /\\ ${h}' = TraceStates[traceIdx + 1].${h}`),"","TraceDone =="," /\\ traceIdx = Len(TraceStates)"," /\\ UNCHANGED <<vars, traceIdx>>","","TraceNext == TraceStep \\/ TraceDone","","TraceSpec == TraceInit /\\ [][TraceNext]_<<vars, traceIdx>>","","\\* Reaching the last pinned state means the model accepted every step.","TraceProgress == traceIdx \\in 1..Len(TraceStates)","====",""].join(`
608
- `),f=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
609
- `);return{moduleName:u,moduleText:g,cfgText:f,variables:l,skippedVariables:d,states:s.length,warnings:i}}function Ng(e){let t=e.mappedActions??[],n=hT(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:ni(t,[])};let r=dT(Pn(mT(),"scip-tla-trace-"));try{let i=gT(e.specPath);for(let d of uT(i))d.endsWith(".tla")&&lT(Pn(i,d),Pn(r,d));let o=Pn(r,`${n.moduleName}.tla`),s=Pn(r,`${n.moduleName}.cfg`);Mg(o,n.moduleText),Mg(s,n.cfgText);let a=Xr({...e.toolOptions,specPath:o,configPath:s,checker:"tlc"});if(a.status==="skipped")return{status:"unavailable",states:n.states,detail:a.diagnostics[0]?.message??"model checker unavailable",checker:a,generation:n,actionCoverage:ni(t,[])};if(a.status==="passed")return{status:"accepted",states:n.states,detail:`TLC accepted all ${n.states} pinned states under ${e.baseModuleName}!${e.nextOperator??"Next"}.`,checker:a,generation:n,actionCoverage:ni(t,e.steps)};let c=yT(a.stdout,e.steps),l=c?e.steps.slice(0,c.divergedStep.index):[];return{status:"diverged",states:n.states,...c??{},detail:c?`trace diverges entering state ${c.divergedAtState+1} (step ${c.divergedStep.index}: ${c.divergedStep.action}) \u2014 the model's ${e.nextOperator??"Next"} relation does not accept the recorded transition.`:"TLC rejected the trace but the divergent step could not be parsed from its output; see checker stdout.",checker:a,generation:n,actionCoverage:ni(t,l)}}finally{pT(r,{recursive:!0,force:!0})}}function yT(e,t){let n=null;for(let o of e.matchAll(/\btraceIdx = (\d+)/g)){let s=Number.parseInt(o[1],10);(n===null||s>n)&&(n=s)}if(n===null||!/deadlock/i.test(e))return null;let r=n-1,i=t[r];return{divergedAtState:n,divergedStep:{index:r,action:i?.action??"unknown"}}}function bT(e){if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isInteger(e))return e;if(Array.isArray(e)){let t=[];for(let n of e)if(typeof n=="string"||typeof n=="boolean")t.push(n);else if(typeof n=="number"&&Number.isInteger(n))t.push(n);else return;return t}}function _g(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>_g(t)).join(", ")}>>`}function Bg(e){return fT(e).replace(/\.tla$/i,"")}import{mkdirSync as Vg,writeFileSync as Wg}from"fs";import{dirname as ST,join as Ut}from"path";var vT=async(...e)=>{let{args:t,opts:n}=yl(e),r=O(t,0);if(r==="fetch-tools"){let o=await fg();if(S(n,"json")){E("tla",t,n,o);return}console.log(`tla2tools.jar ${o.status}: ${o.path}`),console.log(`Version: ${o.version}`),console.log(`SHA-256: ${o.sha256}`);return}if(r==="scaffold"){let o=H(t,1);if(!o)throw new Error("tla scaffold requires a target source file");pe(s=>RT(s,t,n,o));return}if(r==="instrument"){let o=H(t,1);pe(s=>xT(s,t,n,o));return}if(r==="trace-check"){let o=H(t,1);if(!o)throw new Error("tla trace-check requires a spec path");pe(s=>kT(s,t,n,o));return}if(r!=="verify")throw new Error(`unknown tla operation: ${r}. Supported operations: verify, scaffold, instrument, trace-check, fetch-tools`);let i=H(t,1);if(!i)throw new Error("tla verify requires a spec path");pe(o=>CT(o,t,n,i))};function RT(e,t,n,r){let i=e.config.projectRoot,o=Og(e,r,{moduleName:w(n,"moduleName"),specDir:w(n,"out")}),s=w(n,"out")??Ut("specs",o.moduleName),a=ge(i,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=S(n,"force"),l=[{path:Ut(a,`${o.moduleName}.tla`),body:o.spec},{path:Ut(a,`${o.moduleName}.cfg`),body:o.cfg},{path:Ut(a,`${o.moduleName}.scip-tla.json`),body:o.map}];for(let d of l)if(!c&&Tn(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);Vg(a,{recursive:!0});for(let d of l)Wg(d.path,d.body);if(S(n,"json")){E("tla",t,n,{operation:"scaffold",moduleName:o.moduleName,target:r,written:l.map(d=>d.path),variables:o.variables,actions:o.actions,warnings:o.warnings});return}console.log(`Scaffolded ${o.moduleName} from ${r} (draft \u2014 review every TODO):`);for(let d of l)console.log(` wrote ${d.path}`);console.log(`Variables (${o.variables.length}): ${o.variables.map(d=>`${d.name}${d.domainTla?"":" [TODO domain]"}`).join(", ")}`),console.log(`Actions (${o.actions.length}): ${o.actions.map(d=>`${d.name}(writes: ${d.writes.join(",")||"-"})`).join("; ")}`);for(let d of o.warnings)console.log(`WARNING: ${d}`);console.log(`Next: fill the TODO guards/domains, then run 'scip-query tla verify ${Ut(s,`${o.moduleName}.tla`)}'.`)}function xT(e,t,n,r){let i=e.config.projectRoot,o=w(n,"map")??(r?Gr(r):void 0);if(!o)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=Ur(i,o);if(!s.loaded)throw new Error(s.errors.join(`
610
- `));let{contract:a,mapDir:c}=s.loaded,l=Fg(e,a),d=w(n,"out")??Ut(c,"scip-tla-recorder.ts"),u=ge(i,d);if(!u)throw new Error(`instrument output escapes the project root: ${d}`);if(!S(n,"force")&&Tn(u))throw new Error(`refusing to overwrite ${u} (pass --force to replace the recorder)`);if(Vg(ST(u),{recursive:!0}),Wg(u,l.recorderSource),S(n,"json")){E("tla",t,n,{operation:"instrument",recorder:u,variables:l.variables,wiring:l.wiring});return}console.log(`Wrote trace recorder: ${u}`),console.log("Wire tlaRecord(...) into each mapped action (1 line per action), then run your tests with"),console.log("SCIP_TLA_TRACE=<trace.json> set, and check the result with 'scip-query tla trace-check'."),console.log("Wiring sites:");for(let m of l.wiring){let g=m.file?`${m.file}:${m.line}`:`UNRESOLVED (${m.codeRef})`;console.log(` - ${m.action} -> ${g} writes: ${m.writes.join(", ")||"-"}`)}}function kT(e,t,n,r){let i=e.config.projectRoot,o=ge(i,r);if(!o||!Tn(o))throw new Error(`TLA+ spec not found: ${r}`);let s=w(n,"map")??Gr(r),a=Ur(i,s);if(!a.loaded)throw new Error(a.errors.join(`
611
- `));let{contract:c}=a.loaded,l=Et(n,"trace"),u=zo(i,[...c.traces,...l]).flatMap(f=>Jo(i,f).steps);if(u.length===0)throw new Error("no trace steps found: pass --trace <file> (repeatable) or list traces in the mapping contract");let m=Ng({specPath:o,baseModuleName:Bg(o),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:u,nextOperator:w(n,"next"),toolOptions:{projectRoot:i,tlaToolsJar:w(n,"tlaTools"),timeoutMs:Q(n,"timeoutMs")}}),g=m.status==="accepted"||m.status==="unavailable"&&S(n,"allowUnknown")?0:1;if(S(n,"json")){E("tla",t,n,{operation:"trace-check",...m,exitCode:g}),process.exitCode=g;return}if(console.log(`TLA+ trace-check: ${o}`),console.log(`Trace: ${u.length} step(s) -> ${m.states} pinned state(s)`),m.generation){console.log(`Pinned variables: ${m.generation.variables.join(", ")}`);for(let f of m.generation.warnings)console.log(`WARNING: ${f}`)}console.log(`${m.status.toUpperCase()}: ${m.detail}`),S(n,"coverage")&&wT(m.actionCoverage),process.exitCode=g}function wT(e){if(e.length===0)return;let t=e.filter(r=>r.stepsObserved>0),n=e.filter(r=>r.stepsObserved===0);console.log(`Action coverage: ${t.length}/${e.length} mapped action(s) exercised by this trace.`);for(let r of t)console.log(` - ${r.action}: ${r.stepsObserved} step(s)`);n.length>0&&console.log(` Unexercised: ${n.map(r=>r.action).join(", ")} \u2014 classify each as a pure modeling abstraction (no code twin, expected) or a real coverage gap (record another trace).`)}function $T(e,t,n,r){let i=w(r,"map");if(i)return{mapArg:i};let o=Gr(t),s=ge(e,o);if(s&&Tn(s))return{mapArg:o};let a=gf(e,n);if(a.status==="ambiguous")throw new Error(`multiple *.scip-tla.json files declare module "${a.moduleName}": ${a.candidates.join(", ")} \u2014 pass --map to disambiguate`);return a.status==="found"?{mapArg:a.mapPath,mappingDiscoveredBy:"module-field"}:{mapArg:o}}function CT(e,t,n,r){let i=e.config.projectRoot,o=ge(i,r);if(!o||!Tn(o))throw new Error(`TLA+ spec not found: ${r}`);let{mapArg:s,mappingDiscoveredBy:a}=$T(i,r,o,n),c=Ur(i,s);if(!c.loaded)throw new Error(c.errors.join(`
612
- `));let{contract:l,mapPath:d,mapDir:u}=c.loaded,m=w(n,"config")??l.config,g=df(i,u,m),f=TT(w(n,"checker")??"auto"),h=w(n,"tlaTools"),b=PT(i,r,o,h)??uf(i,r),y=mf(g),v=Et(n,"trace"),T=zo(i,[...l.traces,...v]).map(N=>({tracePath:N,...Jo(i,N)})),D=T.flatMap(N=>N.steps),C=new Set(v),U=T.filter(N=>C.has(N.tracePath)).flatMap(N=>N.errors),j=xg(e,l,b,D,y);for(let N of[...c.errors,...U])j.findings.push({id:`TLA-CONTRACT-${j.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:N,why:["The verifier can only make accurate claims after the mapping and trace inputs are valid."],remediation:"Fix the mapping or trace input and rerun scip-query tla verify."});let M=Xr({projectRoot:i,specPath:o,configPath:g??void 0,checker:f,tlaToolsJar:h,apalacheBin:w(n,"apalache"),length:P(n,"length",10),timeoutMs:Q(n,"timeoutMs")});M.status==="skipped"&&f!=="none"&&j.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:M.diagnostics.map(N=>N.message).join("; "),why:["The TLA+ model was not checked by SANY, TLC, or Apalache in this run."],remediation:"Install the requested checker, run 'scip-query tla fetch-tools', set TLA_TOOLS_JAR, pass --apalache, or rerun with --checker none intentionally."});let K={operation:"verify",specPath:o,mapPath:d,...a?{mappingDiscoveredBy:a}:{},...g?{configPath:g}:{},checker:M,conformance:j,exitCode:IT(M,j,S(n,"allowUnknown"))};if(S(n,"json")){E("tla",t,n,K),process.exitCode=K.exitCode;return}ET(K,S(n,"full")),process.exitCode=K.exitCode}function PT(e,t,n,r){let i=ts({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=Zm({specPath:n,jarPath:i});return o?pf(e,t,o):null}var Hg=[{id:"tla",command:"tla <operation> [spec]",description:"TLA+ model workflow: verify a model and mapping contract, scaffold a draft model from indexed code, generate a trace recorder, or check a recorded trace against the next-state relation",agent:k("Does this TLA+ model and code mapping agree, or can the requested model artifact be generated?","checker status, conformance findings, trace coverage, or generated artifact paths",["action","path"],"bounded","repository"),options:I([p("--map <file>","scip-query TLA mapping JSON file"),p("--config <file>","TLA+ checker config file"),p("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),p("--tla-tools <jar>","Path to tla2tools.jar"),p("--apalache <binary>","Path to apalache-mc binary"),p("--length <n>","Bounded checker length for Apalache",x,10),p("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",He),p("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",ut,[]),p("--next <operator>","trace-check: next-state operator the harness requires between states (default Next; use for dual-spec models, e.g. NextCurrent)",void 0,"Next"),p("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),p("--allow-unknown","Exit zero when only unknown findings remain"),p("--out <path>","Output directory (scaffold) or file (instrument)"),p("--module-name <name>","Module name for scaffolded specs"),p("--force","Overwrite existing scaffold/instrument output"),p("--full","verify: print every finding ungrouped instead of (category, modelElement) groups with 3 exemplars each")]),renderShape:"custom",docs:$("Formal Models",["scip-query tla verify specs/Queue.tla --map specs/Queue.scip-tla.json","scip-query tla scaffold src/queue/store.ts","scip-query tla trace-check specs/Queue.tla --trace traces/run1.json --coverage","scip-query tla trace-check specs/Queue.tla --trace traces/run1.json --trace traces/run2.json --coverage","scip-query tla trace-check specs/DualSpec.tla --trace traces/run1.json --next NextCurrent","scip-query tla verify specs/Queue.tla --timeout-ms 300000","scip-query tla verify specs/Queue.tla --full","scip-query tla fetch-tools"]),handler:vT}];function TT(e){if(!lf(e))throw new Error(`unknown checker mode: ${e}`);return e}function IT(e,t,n){return e.status==="failed"||e.status==="timed-out"||t.findings.some(r=>r.severity==="error")||!n&&t.findings.some(r=>r.evidence==="unknown")?1:0}var qg=3;function ET(e,t){console.log(`TLA+ verify: ${e.specPath}`),console.log(`Mapping: ${e.mapPath}${e.mappingDiscoveredBy==="module-field"?" (matched by module field)":""}`),e.configPath&&console.log(`Config: ${e.configPath}`),console.log(`Checker: ${e.checker.checker} ${e.checker.status} (${e.checker.durationMs}ms, exit ${e.checker.exitCode??e.checker.signal??"n/a"})`);for(let o of e.checker.diagnostics)console.log(` [${o.severity}] ${o.message}`);let n=e.conformance.findings.filter(o=>o.severity==="error"),r=e.conformance.findings.filter(o=>o.evidence==="unknown"),i=AT(e);console.log(`
613
- Conformance: ${e.conformance.mappedVariables} variable(s), ${e.conformance.mappedActions} action(s), ${e.conformance.resolvedReferents} resolved referent(s).`),console.log(`Proof: ${i}`);for(let o of LT(e))console.log(`WARNING: ${o}`);if(e.conformance.waivers.length>0){console.log("Waivers:");for(let o of e.conformance.waivers){let s=o.legacy?" legacy":"",a=o.action?`${o.action} ${o.kind}`:`variable ${o.kind}`;console.log(` - ${a} ${o.variable}:${s} ${o.reason}`)}}if(e.conformance.findings.length===0){console.log(e.conformance.waivers.length===0?`PASS: model, mapping, and checked code evidence agree (model parsed by: ${e.conformance.modelParse}).`:`PASS: model checker and unwaived conformance checks passed (model parsed by: ${e.conformance.modelParse}); see waived facts above.`);return}if(console.log(`Findings: ${n.length} error(s), ${r.length} unknown(s), ${e.conformance.findings.length} total.`),t){for(let o of e.conformance.findings)Ug(o);return}jT(e.conformance)}function jT(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
614
- Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
615
- [${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let i of n.findingIds.slice(0,qg)){let o=t.get(i);o&&Ug(o)}let r=n.count-qg;r>0&&console.log(` ... and ${r} more in this group (use --full to show all)`)}}function AT(e){let t=`${e.checker.checker} ${e.checker.status==="passed"?"PASS":e.checker.status.toUpperCase()}`,n=e.conformance.waivers.filter(s=>s.kind==="write").length,r=e.conformance.waivers.filter(s=>s.kind==="read").length,i=e.conformance.waivers.filter(s=>s.kind==="referent").length,o=e.conformance.findings.filter(s=>s.category==="missing-call").length;return[`checker: ${t}`,`model parsed by: ${e.conformance.modelParse}`,`writes: ${e.conformance.staticWrites.length} verified, ${n} waived`,`reads: ${e.conformance.staticReads.length} verified, ${r} waived`,`calls: ${o===0?"checked":`${o} missing`}`,`traces: ${e.conformance.traceStepsChecked} steps (key-diff; 'tla trace-check' proves acceptance)`,...i>0?[`referents: ${i} waived`]:[]].join(" | ")}function LT(e){let t=[],n=e.conformance.waivers.filter(i=>i.kind==="write").length,r=e.conformance.waivers.filter(i=>i.kind==="read").length;return n>0&&e.conformance.staticWrites.length===0&&t.push("NOTHING PROVEN ABOUT WRITES: every write fact found in this run was waived or unobserved."),r>0&&e.conformance.staticReads.length===0&&t.push("NOTHING PROVEN ABOUT READS: every read fact found in this run was waived or unobserved."),t}function Ug(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${V(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
616
- [${e.severity}] ${e.category} (${e.evidence})${t}`),console.log(` ${e.message}`);for(let n of e.why)console.log(` why: ${n}`);console.log(` fix: ${e.remediation}`)}var Gg=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","architecture","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","similar-chains","extract-candidates","locality-candidates","affected","change-surface","cleanup-plan","cleanup-apply","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","incomplete-migration","tla","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","duplicate-bodies","twin-drift","twin-ab","not-implemented","decorative-checkers","test-quality","similar-signatures"],OT=[zf,Yf,Kf,zr,Xf,tg,Hg,Qf],Jg=OT.flat(),DT=new Map(Jg.map(e=>[e.id,e]));for(let e of Jg)if(!Gg.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Gt=Gg.map(e=>FT(e));function FT(e){let t=DT.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var MT=Gt.slice(0,ds("plan-context")),NT=Gt.slice(ri("drift"),ds("self-audit")),_T=Gt.slice(ri("convergence"),ds("slice")),BT=Gt.slice(ri("redundant-reexports")),gN=[{id:"reindex",command:"reindex",agent:k("Can the repository index be refreshed, and which language shards succeeded?","index generation, shard statuses, reuse diagnostics, and failures",[],"complete","repository"),description:"Index the codebase and convert to SQLite",options:[p("-l, --language <lang>","Index only this language (can be repeated)",ut,[]),p("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),p("--force","Rebuild even if source inputs are unchanged"),p("--allow-partial","Write an incomplete index when one or more detected languages fail"),p("--indexer-concurrency <n>","Number of language indexers to run at once",He),p("--json","Output as JSON, including per-shard reuse diagnostics")],renderShape:"custom",docs:$("Indexing",["scip-query reindex"]),handler:hm},{id:"augment-sources",command:"augment-sources",agent:k("Can source files omitted by upstream indexers be added to the index?","added document counts and augmentation status",[],"complete","repository"),description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:$("Indexing"),handler:ym},{id:"augment-vue",command:"augment-vue",agent:k("Can Vue SFC references be compiler-resolved and added to the index?","Vue augmentation counts, project, and diagnostics",[],"complete","repository"),description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[p("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:$("Indexing"),handler:bm},...MT,{id:on,command:on,description:"Internal diff-impact batch worker",hidden:!0,options:[p("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Sm},{id:"diff-impact",command:"diff-impact",agent:k("Which symbols changed in this diff and which downstream consumers are affected?","changed symbols, downstream consumer identities, and impact paths",[],"bounded","diff"),description:"Compute changed symbols and downstream consumers from current git diff",options:I([p("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:$("Impact"),handler:vm},...NT,{id:rn,command:rn,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:Rm},{id:"health",command:"health",agent:k("What are the highest-priority verified health problems in this codebase?","health score, findings, priorities, baselines, and coverage notes",[],"bounded","repository"),description:"Composite codebase health report with prioritized action list",options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes"),p("--json","Output as JSON for programmatic consumption"),p("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),p("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:$("Health",["scip-query health --json","scip-query health --baseline"]),handler:xm},{id:"bench",command:"bench",agent:k("How fast are indexing and selected commands under this benchmark matrix?","timings, command outcomes, environment, and optional profiles",[],"sampled","repository"),description:"Benchmark indexing and command runtimes for this repository",options:[p("--json","Output as JSON for programmatic consumption"),p("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),p("--include-heavy","Include expensive full-detector commands in the command matrix"),p("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",ut,[]),p("--timeout-ms <n>","Per-command timeout in milliseconds",He,18e4),p("--progress","Print benchmark command start/finish progress to stderr"),p("--profile","Enable low-overhead phase profiling in benchmarked commands"),p("--profile-out <path>","Append benchmark and phase profile events as JSONL")],renderShape:"custom",docs:$("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:km},{id:"work-audit",command:"work-audit <profile>",agent:k("Which repeated computations in this profile waste the most measured time?","ranked repeated-work groups, counts, and avoidable duration",["path"],"bounded"),description:"Rank exact repeated computations in a profiling JSONL file by measured avoidable time",options:[p("--top <n>","Maximum repeated-work groups to show",He,20),p("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",docs:$("Maintenance",["scip-query work-audit profile.jsonl","scip-query work-audit profile.jsonl --json"]),handler:wm},{id:"typescript-semantic-compare",command:"typescript-semantic-compare",description:"Compare tsserver reference answers against the ts-morph baseline",hidden:!0,options:[p("-s, --scope <path>","Limit compared definitions to files matching path"),p("--limit <n>","Maximum definitions to compare unless --full is set",He),p("--max-mismatches <n>","Maximum mismatch details to include in output",It),p("--full","Compare every indexed TypeScript-like definition"),p("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:$m},..._T,{id:"install-skills",command:"install-skills",agent:k("Which scip-query skills were installed, updated, skipped, or conflicted?","skill target paths and install outcomes",[],"complete","repository"),description:`Install skills (${hr.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:$("Maintenance"),handler:Tm},{id:"setup-hooks",command:"setup-hooks",agent:k("Were project-local agent hooks installed or removed safely?","hook config targets, changes, skips, and warnings",[],"complete","repository"),description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[p("--shared","Deprecated compatibility flag; hooks remain checkout-local and untracked"),p("--remove","Remove managed project hooks and remember the opt-out"),p("--force","Reinstall hooks even after a previous --remove opt-out"),p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:Im},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:Sd},{id:"hook-pretool",command:"hook-pretool",description:"Internal Claude PreToolUse evidence-integrity guard",hidden:!0,renderShape:"custom",handler:vd},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:xd},{id:"check-deps",command:"check-deps",agent:k("Which scip-query and language-indexer dependencies are runnable?","dependency readiness statuses and remediation",[],"complete","repository"),description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:$("Maintenance"),handler:Em},{id:"capabilities",command:"capabilities",agent:k("Which evidence and verification capabilities are available here?","capability matrix with availability and reasons",[],"complete","repository"),description:"Report which evidence and verification capabilities are available in this project",options:[p("--matrix","Render the project capability matrix (default output)"),p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:jm},{id:"capability-matrix",command:"capability-matrix",agent:k("Which evidence and verification capabilities are available here?","deprecated alias of the capability matrix",[],"complete","repository"),description:"Deprecated alias for capabilities --matrix",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:Am},...BT,{id:"init",command:"init",agent:k("Can a starter scip-query configuration be created for this project?","configuration path and creation outcome",[],"complete","repository"),description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:$("Maintenance"),handler:Om},{id:"config-validate",command:"config-validate",agent:k("Is this project configuration valid and internally consistent?","validation diagnostics with config paths",[],"complete","repository"),description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query config-validate"]),handler:Dm},{id:"suppress",command:"suppress <id>",agent:k("Can this accepted finding be recorded with an auditable reason?","suppression identity, path, scope, and expiry",["finding"],"complete"),description:"Record an accepted finding as a file under .scipquery/suppressions/ with a required reason",options:I([p("--reason <text>","Required human reason for accepting the finding"),p("--check <check>","Optional detector/check name to narrow the suppression"),p("--file <path>","Optional file path to narrow the suppression"),p("--expires-at <iso>","Optional ISO date after which the suppression expires"),p("--replace <revision>","Replace a different existing decision only when it still has this reported SHA-256 revision")]),renderShape:"custom",docs:$("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:Fm},{id:"effectiveness",command:"effectiveness",agent:k("Which diff-gate checks catch actionable findings with verified outcomes?","per-check caught, fixed, suppressed, unresolved, and precision counts",[],"complete","repository"),description:"Per-check effectiveness from the committed outcome ledger: caught, comparison-verified fixes, suppressed, unverified disappearances, and precision",options:I([p("--since <window>","Only count findings first caught in this window (30d, 12w, or an ISO date)"),p("--check <check>","Restrict to one diff-gate check")]),renderShape:"custom",docs:$("Maintenance",["scip-query effectiveness --since 30d","scip-query effectiveness --check echo --json"]),handler:Mm},{id:"doctor",command:"doctor",agent:k("Why is scip-query unhealthy or unavailable in this project?","config, freshness, dependency, and capability diagnostics",[],"complete","repository"),description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:Nm},{id:"setup",command:"setup",agent:k("Can scip-query be bootstrapped end to end in this project?","setup step outcomes, files, capabilities, smoke tests, and warnings",[],"complete","repository"),description:"Bootstrap this project: enable automatic indexing, install agent skills, refresh the index, verify capabilities, and report health",options:I([p("--guided","Open the interactive checklist (the default in a terminal)"),p("--yes","Accept recommended setup defaults without prompting"),p("--git-hook","Also install a git pre-commit hook that runs diff-gate"),p("--no-hooks","Skip Codex and Claude Code lifecycle hook installation"),p("--no-skills","Skip user-level agent skill installation"),p("--no-parsers","Skip Tree-sitter AST parser installation and repair"),p("--no-health","Skip the optional full health audit and dossier"),p("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:$("Maintenance",["scip-query setup","scip-query setup --json"]),handler:qm},{id:"setup-agent",command:"setup-agent",agent:k("Can project agent guidance and optional git enforcement be seeded?","written, unchanged, and skipped agent files or hooks",[],"complete","repository"),description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[p("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:Bm},{id:"setup-ci",command:"setup-ci",agent:k("Can a CI workflow enforce reindex and diff-gate on pull requests?","workflow path, rendered content, and write outcome",[],"complete","repository"),description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[p("--force","Overwrite an existing workflow"),p("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-ci"]),handler:Vm},{id:"uninstall",command:"uninstall",agent:k("Which scip-query-owned integrations can be removed without touching user-owned files?","removed, retained, skipped, and dry-run targets",[],"complete","repository"),description:"Remove scip-query-owned skill links, project hooks, and managed agent setup blocks",options:I([p("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),p("--project","Remove project-local hooks and managed AGENTS.md/CLAUDE.md blocks"),p("--dry-run","List what would be removed without changing files")]),renderShape:"custom",docs:$("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:Wm},{id:"watch",command:"watch",agent:k("What is the watcher doing, or can its background service be started or stopped?","watcher/service state, generation, activity, and errors",[],"complete","repository"),description:"Watch in the foreground or manage the per-project background refresh service",options:I([p("--daemon","Ensure the demand-started background service is running"),p("--status","Show background/foreground watcher state"),p("--stop","Stop the watcher or background service for this project"),p("--debounce <ms>","Ms to wait after last change (default: 250)",It),p("--cooldown <ms>","Min ms between reindexes; 0 disables spacing (default: 0)",It),p("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",It),p("--idle-timeout <ms>","Ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",It)]),renderShape:"custom",docs:$("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:Hm},{id:"status",command:"status",agent:k("Is the index fresh, complete, and usable for this project?","freshness, generation, language shards, watcher, and optional capabilities",[],"complete","repository"),description:"Show index status for this project",options:[p("--json","Output as JSON for programmatic consumption"),p("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:$("Maintenance"),handler:Jm}];function ri(e){let t=Gt.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function ds(e){return ri(e)+1}export{gN as commandDescriptors};
617
- //# sourceMappingURL=command-descriptors-SJDZ7QGR.js.map