scip-query 0.18.0 → 0.19.1

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 (300) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +1 -0
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/{chunk-2DBY4MO7.js → chunk-24ET4VLC.js} +2 -2
  5. package/dist/chunk-2NA6TYP4.js +120 -0
  6. package/dist/{chunk-XKWEMFHP.js → chunk-2WCXKANA.js} +2 -2
  7. package/dist/{chunk-LL5NQB5V.js → chunk-34MLC6UI.js} +2 -2
  8. package/dist/chunk-35NLDRZC.js +2 -0
  9. package/dist/{chunk-MNRKD3WP.js → chunk-3WLRW5TC.js} +2 -2
  10. package/dist/{chunk-SW7LKHRU.js → chunk-4BU54UJG.js} +2 -2
  11. package/dist/{chunk-T4P27T6S.js → chunk-4CZJ4YJB.js} +2 -2
  12. package/dist/{chunk-3CJXFMR5.js → chunk-4FMT4HPC.js} +2 -2
  13. package/dist/{chunk-J7IMQRCU.js → chunk-53SUJOJA.js} +2 -2
  14. package/dist/{chunk-27YDE22N.js → chunk-5GOBZI34.js} +2 -2
  15. package/dist/{chunk-4FLF7BHJ.js → chunk-5OZCNAVM.js} +2 -2
  16. package/dist/chunk-5TEUKVSM.js +2 -0
  17. package/dist/{chunk-GTANVH72.js → chunk-5W2VAEVR.js} +2 -2
  18. package/dist/{chunk-43QUXX3E.js → chunk-63P42UR6.js} +2 -2
  19. package/dist/{chunk-OQFPCIXO.js → chunk-64QITTX7.js} +2 -2
  20. package/dist/{chunk-P4L5QQT5.js → chunk-6O5JOS7T.js} +2 -2
  21. package/dist/chunk-6PKO2TNZ.js +2 -0
  22. package/dist/{chunk-OSBLECSI.js → chunk-7SGOWD2Y.js} +2 -2
  23. package/dist/chunk-7TJJY2C3.js +2 -0
  24. package/dist/{chunk-K3UVTL3J.js → chunk-AEM24WSF.js} +2 -2
  25. package/dist/{chunk-PV3GKBO5.js → chunk-AGTATREV.js} +2 -2
  26. package/dist/chunk-AOSFSYEA.js +20 -0
  27. package/dist/{chunk-VCRMI56V.js → chunk-APLNTJPJ.js} +2 -2
  28. package/dist/{chunk-7XP7ZRSI.js → chunk-AYRHVJXW.js} +2 -2
  29. package/dist/chunk-B2WQKQKP.js +3 -0
  30. package/dist/{chunk-SWJEREML.js → chunk-BBBKPOIT.js} +2 -2
  31. package/dist/{chunk-OTTHMUMV.js → chunk-BCMOTIB6.js} +2 -2
  32. package/dist/chunk-BMTBVMA3.js +10 -0
  33. package/dist/{chunk-J7WYG63U.js → chunk-C3KCSAQ4.js} +2 -2
  34. package/dist/{chunk-5CJ6AQN7.js → chunk-CAKPEQZB.js} +2 -2
  35. package/dist/{chunk-UWR52GNZ.js → chunk-CIYUFF24.js} +2 -2
  36. package/dist/{chunk-ABDXTPCT.js → chunk-CKFMZE77.js} +2 -2
  37. package/dist/chunk-DCDOGW32.js +2 -0
  38. package/dist/{chunk-ODH4FT3P.js → chunk-DFQNE73Y.js} +2 -2
  39. package/dist/chunk-DO775SYA.js +2 -0
  40. package/dist/chunk-DRH3AD7W.js +4 -0
  41. package/dist/chunk-DZXFZAZO.js +16 -0
  42. package/dist/chunk-E3KWOHH7.js +5 -0
  43. package/dist/chunk-EMIIOOTM.js +38 -0
  44. package/dist/chunk-ESNRT7QN.js +927 -0
  45. package/dist/{chunk-AWYKDRYV.js → chunk-FB6IKAKZ.js} +2 -2
  46. package/dist/{chunk-BGUYAA3Q.js → chunk-FBUNGRKI.js} +2 -2
  47. package/dist/{chunk-M2TRDR25.js → chunk-FC5K7T35.js} +1 -1
  48. package/dist/{chunk-GWCW25ON.js → chunk-FHLYJVXF.js} +2 -2
  49. package/dist/{chunk-IG6X65MG.js → chunk-FRXB74RQ.js} +2 -2
  50. package/dist/{chunk-IKMOYFUM.js → chunk-FTRNGQGR.js} +2 -2
  51. package/dist/{chunk-NX2YAXVQ.js → chunk-FUFNRZFJ.js} +2 -2
  52. package/dist/{chunk-JLZUM476.js → chunk-GAE7WCBK.js} +2 -2
  53. package/dist/chunk-GIHVWNKQ.js +18 -0
  54. package/dist/{chunk-MPBN5DO4.js → chunk-HCS5LB6U.js} +2 -2
  55. package/dist/{chunk-6JSTKSZH.js → chunk-HFBNIIZX.js} +2 -2
  56. package/dist/{chunk-JHK2DMUQ.js → chunk-HGFDYOVB.js} +1 -1
  57. package/dist/chunk-IOOCKVUA.js +6 -0
  58. package/dist/{chunk-4L4X66GE.js → chunk-J4MYRIYT.js} +2 -2
  59. package/dist/{chunk-TAB7AWKO.js → chunk-J5XJWCB3.js} +2 -2
  60. package/dist/{chunk-POGZSZPX.js → chunk-JBZXJXIS.js} +2 -2
  61. package/dist/chunk-JJZRS2OP.js +5 -0
  62. package/dist/chunk-KC2IFAAU.js +3 -0
  63. package/dist/{chunk-3M2UCPFS.js → chunk-KHE7J5ZN.js} +1 -1
  64. package/dist/{chunk-4XTPZ5CR.js → chunk-KMOMNTB4.js} +2 -2
  65. package/dist/chunk-KMUFGAIK.js +2 -0
  66. package/dist/chunk-LF5CIKWZ.js +26 -0
  67. package/dist/chunk-LM72NQ7T.js +3 -0
  68. package/dist/{chunk-QPF7CS5W.js → chunk-LQUDSHLB.js} +2 -2
  69. package/dist/chunk-MP43RX4O.js +67 -0
  70. package/dist/{chunk-D5OXYOJP.js → chunk-MQ2B33LQ.js} +1 -1
  71. package/dist/{chunk-WA64GKWB.js → chunk-NH7WNNQC.js} +3 -3
  72. package/dist/{chunk-HOZ3IXZ5.js → chunk-NTOBQK5H.js} +2 -2
  73. package/dist/{chunk-SUYCF4SX.js → chunk-OLG2YPLS.js} +2 -2
  74. package/dist/{chunk-O5Y3ISO3.js → chunk-OOUJBAKJ.js} +2 -2
  75. package/dist/{chunk-U244OVE6.js → chunk-OQ6TCHBB.js} +2 -2
  76. package/dist/{chunk-5GAUXLOE.js → chunk-PNESKY2Z.js} +2 -2
  77. package/dist/chunk-PYMZU5EG.js +2 -0
  78. package/dist/chunk-Q2WEWIKX.js +4 -0
  79. package/dist/chunk-QHKXGMOI.js +3 -0
  80. package/dist/{chunk-VXDMXZKC.js → chunk-RPEA7P5Z.js} +2 -2
  81. package/dist/{chunk-K65T4TJS.js → chunk-SJ6XSCG7.js} +2 -2
  82. package/dist/{chunk-LADYDOS5.js → chunk-SSXEYWN3.js} +2 -2
  83. package/dist/chunk-SYGAA54M.js +2 -0
  84. package/dist/{chunk-H4T2AST4.js → chunk-TYEGFDOP.js} +2 -2
  85. package/dist/chunk-UJKZQLDB.js +2 -0
  86. package/dist/{chunk-PZV2PGBR.js → chunk-US44MEVU.js} +2 -2
  87. package/dist/{chunk-EJ65IVPV.js → chunk-V5WBVF6K.js} +2 -2
  88. package/dist/{chunk-AV54WZUK.js → chunk-V7J4A3AH.js} +2 -2
  89. package/dist/{chunk-45QWQSWS.js → chunk-VIKEPD4D.js} +2 -2
  90. package/dist/{chunk-TLTLJ4SW.js → chunk-WAU7HVDI.js} +2 -2
  91. package/dist/chunk-WCZAABYF.js +2 -0
  92. package/dist/{chunk-FMD46HAG.js → chunk-WFRET75Z.js} +2 -2
  93. package/dist/chunk-WWCZCH7W.js +3 -0
  94. package/dist/chunk-XBN5VO53.js +2 -0
  95. package/dist/{chunk-35TZERMO.js → chunk-XCPE3G75.js} +2 -2
  96. package/dist/chunk-XYBNOILR.js +2 -0
  97. package/dist/{chunk-BAMVG4WQ.js → chunk-XZXUMGAA.js} +2 -2
  98. package/dist/{chunk-MN54AGZ3.js → chunk-YCSTKIYU.js} +2 -2
  99. package/dist/{chunk-CMLHZWRS.js → chunk-YGQBJUS6.js} +2 -2
  100. package/dist/{chunk-7ROLM67J.js → chunk-YILKXTIY.js} +2 -2
  101. package/dist/{chunk-YMFHC5J2.js → chunk-ZJGZCBYT.js} +2 -2
  102. package/dist/{chunk-D5F3IQYP.js → chunk-ZNK6K3LB.js} +2 -2
  103. package/dist/cli.js +2 -2
  104. package/dist/{command-descriptors-AQWWJNTT.js → command-descriptors-3EJHQLQZ.js} +173 -167
  105. package/dist/{config-types-70s7NxKB.d.ts → config-types-BA3xLCfG.d.ts} +28 -1
  106. package/dist/{db-BBmJ0v3b.d.ts → db-CzA-9_rL.d.ts} +6 -18
  107. package/dist/direct-navigation-C2A44KFT.js +3 -0
  108. package/dist/{health-CWpFL_6z.d.ts → health-DYy13GAe.d.ts} +3 -1
  109. package/dist/index.d.ts +23 -41
  110. package/dist/index.js +1 -1
  111. package/dist/postinstall.js +1 -1
  112. package/dist/queries/affected.d.ts +2 -2
  113. package/dist/queries/affected.js +1 -1
  114. package/dist/queries/architecture.d.ts +83 -0
  115. package/dist/queries/architecture.js +2 -0
  116. package/dist/queries/bottlenecks.d.ts +2 -2
  117. package/dist/queries/bottlenecks.js +1 -1
  118. package/dist/queries/by-kind.d.ts +2 -2
  119. package/dist/queries/by-kind.js +1 -1
  120. package/dist/queries/call-graph.d.ts +2 -2
  121. package/dist/queries/call-graph.js +1 -1
  122. package/dist/queries/change-surface.d.ts +2 -2
  123. package/dist/queries/change-surface.js +1 -1
  124. package/dist/queries/cleanup-plan.d.ts +2 -2
  125. package/dist/queries/cleanup-plan.js +1 -1
  126. package/dist/queries/co-change.d.ts +2 -2
  127. package/dist/queries/co-change.js +1 -1
  128. package/dist/queries/code.d.ts +2 -2
  129. package/dist/queries/code.js +1 -1
  130. package/dist/queries/complexity-hotspots.d.ts +2 -2
  131. package/dist/queries/complexity-hotspots.js +1 -1
  132. package/dist/queries/complexity.d.ts +2 -2
  133. package/dist/queries/complexity.js +1 -1
  134. package/dist/queries/convergence.d.ts +2 -2
  135. package/dist/queries/convergence.js +1 -1
  136. package/dist/queries/coupling.d.ts +2 -2
  137. package/dist/queries/coupling.js +1 -1
  138. package/dist/queries/cycles.d.ts +2 -2
  139. package/dist/queries/cycles.js +1 -1
  140. package/dist/queries/dataflow.d.ts +2 -2
  141. package/dist/queries/dataflow.js +1 -1
  142. package/dist/queries/dead.d.ts +2 -2
  143. package/dist/queries/dead.js +1 -1
  144. package/dist/queries/decorative-checkers.d.ts +2 -2
  145. package/dist/queries/decorative-checkers.js +1 -1
  146. package/dist/queries/deep-chains.d.ts +2 -2
  147. package/dist/queries/deep-chains.js +1 -1
  148. package/dist/queries/deps.d.ts +2 -2
  149. package/dist/queries/deps.js +1 -1
  150. package/dist/queries/diff-gate.d.ts +5 -3
  151. package/dist/queries/diff-gate.js +1 -1
  152. package/dist/queries/diff-impact.d.ts +2 -2
  153. package/dist/queries/diff-impact.js +1 -1
  154. package/dist/queries/doc-drift.d.ts +2 -2
  155. package/dist/queries/doc-drift.js +1 -1
  156. package/dist/queries/drift.d.ts +27 -10
  157. package/dist/queries/drift.js +1 -1
  158. package/dist/queries/duplicate-bodies.d.ts +2 -2
  159. package/dist/queries/duplicate-bodies.js +1 -1
  160. package/dist/queries/extract-candidates.d.ts +2 -2
  161. package/dist/queries/extract-candidates.js +1 -1
  162. package/dist/queries/fan.d.ts +2 -2
  163. package/dist/queries/fan.js +1 -1
  164. package/dist/queries/files.d.ts +2 -2
  165. package/dist/queries/health.d.ts +3 -3
  166. package/dist/queries/health.js +1 -1
  167. package/dist/queries/hierarchy.d.ts +2 -2
  168. package/dist/queries/hierarchy.js +1 -1
  169. package/dist/queries/hotspots.d.ts +2 -2
  170. package/dist/queries/hotspots.js +1 -1
  171. package/dist/queries/imports.d.ts +2 -2
  172. package/dist/queries/imports.js +1 -1
  173. package/dist/queries/incomplete-migration.d.ts +2 -2
  174. package/dist/queries/incomplete-migration.js +1 -1
  175. package/dist/queries/index.d.ts +5 -4
  176. package/dist/queries/index.js +1 -1
  177. package/dist/queries/isolated.d.ts +2 -2
  178. package/dist/queries/isolated.js +1 -1
  179. package/dist/queries/locality-candidates.d.ts +2 -2
  180. package/dist/queries/locality-candidates.js +1 -1
  181. package/dist/queries/members.d.ts +2 -2
  182. package/dist/queries/members.js +1 -1
  183. package/dist/queries/methods.d.ts +2 -2
  184. package/dist/queries/methods.js +1 -1
  185. package/dist/queries/not-implemented.d.ts +2 -2
  186. package/dist/queries/not-implemented.js +1 -1
  187. package/dist/queries/outline.d.ts +2 -2
  188. package/dist/queries/outline.js +1 -1
  189. package/dist/queries/passthrough-candidates.d.ts +2 -2
  190. package/dist/queries/passthrough-candidates.js +1 -1
  191. package/dist/queries/plan-context.d.ts +2 -2
  192. package/dist/queries/plan-context.js +1 -1
  193. package/dist/queries/react-component-duplicates.d.ts +2 -2
  194. package/dist/queries/react-component-duplicates.js +1 -1
  195. package/dist/queries/react-hook-candidates.d.ts +2 -2
  196. package/dist/queries/react-hook-candidates.js +1 -1
  197. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  198. package/dist/queries/react-large-component-pressure.js +1 -1
  199. package/dist/queries/recent-duplicates.d.ts +2 -2
  200. package/dist/queries/recent-duplicates.js +1 -1
  201. package/dist/queries/redundant-reexports.d.ts +2 -2
  202. package/dist/queries/redundant-reexports.js +1 -1
  203. package/dist/queries/refs.d.ts +2 -2
  204. package/dist/queries/refs.js +1 -1
  205. package/dist/queries/self-audit.d.ts +2 -2
  206. package/dist/queries/self-audit.js +1 -1
  207. package/dist/queries/similar-chains.d.ts +2 -2
  208. package/dist/queries/similar-chains.js +1 -1
  209. package/dist/queries/similar-files.d.ts +2 -2
  210. package/dist/queries/similar-files.js +1 -1
  211. package/dist/queries/similar-signatures.d.ts +2 -2
  212. package/dist/queries/similar-signatures.js +1 -1
  213. package/dist/queries/similar.d.ts +2 -2
  214. package/dist/queries/similar.js +1 -1
  215. package/dist/queries/slice.d.ts +2 -2
  216. package/dist/queries/slice.js +1 -1
  217. package/dist/queries/stale-abstractions.d.ts +2 -2
  218. package/dist/queries/stale-abstractions.js +1 -1
  219. package/dist/queries/stats.d.ts +2 -2
  220. package/dist/queries/surface.d.ts +2 -2
  221. package/dist/queries/surface.js +1 -1
  222. package/dist/queries/symbols.d.ts +2 -2
  223. package/dist/queries/symbols.js +1 -1
  224. package/dist/queries/system.d.ts +2 -2
  225. package/dist/queries/system.js +1 -1
  226. package/dist/queries/test-quality.d.ts +2 -2
  227. package/dist/queries/test-quality.js +1 -1
  228. package/dist/queries/trace.d.ts +2 -2
  229. package/dist/queries/trace.js +1 -1
  230. package/dist/queries/twin-ab.d.ts +2 -2
  231. package/dist/queries/twin-ab.js +1 -1
  232. package/dist/queries/twin-drift.d.ts +2 -2
  233. package/dist/queries/twin-drift.js +1 -1
  234. package/dist/queries/unused-imports.d.ts +2 -2
  235. package/dist/queries/unused-imports.js +1 -1
  236. package/dist/queries/unused-params.d.ts +2 -2
  237. package/dist/queries/unused-params.js +1 -1
  238. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  239. package/dist/queries/vue-component-duplicates.js +1 -1
  240. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  241. package/dist/queries/vue-composable-candidates.js +1 -1
  242. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  243. package/dist/queries/vue-large-view-pressure.js +1 -1
  244. package/dist/queries/wrapper-candidates.d.ts +2 -2
  245. package/dist/queries/wrapper-candidates.js +1 -1
  246. package/dist/reindex-worker.js +24 -24
  247. package/dist/reindex.d.ts +12 -10
  248. package/dist/reindex.js +38 -38
  249. package/dist/runtime.d.ts +10 -9
  250. package/dist/runtime.js +2 -1
  251. package/dist/rust-semantic-session-server.js +1 -1
  252. package/dist/rust-semantic-session-worker.js +1 -1
  253. package/dist/rust-semantic-worker.js +1 -1
  254. package/dist/{scip-cli-CoMzb7Zu.d.ts → scip-cli-1bVKJgXi.d.ts} +1 -1
  255. package/dist/watch-server.js +7 -6
  256. package/docs/AI_FAILURE_MODES.md +1 -0
  257. package/docs/COMMAND_REFERENCE.md +3 -2
  258. package/docs/DETECTOR_GUIDE.md +5 -3
  259. package/docs/analyzer-inventory.md +16 -6
  260. package/docs/analyzer-validation-ledger.md +12 -1
  261. package/docs/architecture-coherence-vision.md +219 -0
  262. package/package.json +5 -1
  263. package/skills/_shared/SKILL.md +4 -3
  264. package/skills/scip-conductor/SKILL.md +1 -1
  265. package/skills/scip-directory-architecture/SKILL.md +116 -2
  266. package/skills/scip-maintainability/SKILL.md +3 -3
  267. package/skills/scip-query/SKILL.md +1 -1
  268. package/skills/scip-twin-drift/SKILL.md +1 -1
  269. package/skills/scip-verify/SKILL.md +1 -1
  270. package/dist/chunk-2GX3TNOW.js +0 -38
  271. package/dist/chunk-45XOH33S.js +0 -2
  272. package/dist/chunk-4MFMTEJ4.js +0 -5
  273. package/dist/chunk-BECOMXAL.js +0 -2
  274. package/dist/chunk-BJJHBKEC.js +0 -2
  275. package/dist/chunk-DDGO34I2.js +0 -26
  276. package/dist/chunk-DUKRAHV2.js +0 -2
  277. package/dist/chunk-EMEXMHOP.js +0 -7
  278. package/dist/chunk-GWNE2WJN.js +0 -3
  279. package/dist/chunk-H4JNB7RT.js +0 -3
  280. package/dist/chunk-L2RE5P3X.js +0 -2
  281. package/dist/chunk-L2TSLMPT.js +0 -5
  282. package/dist/chunk-NQBMGFFD.js +0 -2
  283. package/dist/chunk-O5A7BTMA.js +0 -3
  284. package/dist/chunk-OINSINYW.js +0 -2
  285. package/dist/chunk-OM6JHEW3.js +0 -16
  286. package/dist/chunk-OUXPJ4H5.js +0 -3
  287. package/dist/chunk-OWXNDSG3.js +0 -2
  288. package/dist/chunk-Q4UM4JJP.js +0 -2
  289. package/dist/chunk-QEIGJJBC.js +0 -20
  290. package/dist/chunk-R4VPIS4D.js +0 -10
  291. package/dist/chunk-RDX6WWHN.js +0 -4
  292. package/dist/chunk-RUQE7DZT.js +0 -2
  293. package/dist/chunk-S43DIBME.js +0 -18
  294. package/dist/chunk-SALRDXWM.js +0 -121
  295. package/dist/chunk-SMBIGBGN.js +0 -67
  296. package/dist/chunk-VQWDZ34M.js +0 -928
  297. package/dist/chunk-W3557RPL.js +0 -3
  298. package/dist/chunk-W3SKYOTF.js +0 -2
  299. package/dist/chunk-XEEQX5X3.js +0 -3
  300. package/dist/direct-navigation-K3CTVVBU.js +0 -3
@@ -1,49 +1,49 @@
1
1
  #!/usr/bin/env node
2
- import{b as vc}from"./chunk-W3557RPL.js";import{a as rt,b as v,c as _e,d as ge,e as kt,f as p,g as dc,h as C,i as $,j as se,k as ae,l as ve,m as Vt,n as Sc}from"./chunk-VXDMXZKC.js";import{$ as Nr,$a as js,$b as wa,A as Lo,Aa as cs,Ab as ta,Ac as tt,Ad as K,B as hn,Ba as qt,Bb as na,Bc as qa,Bd as uc,C as Ao,Ca as ls,Cb as ra,Cc as Ba,Cd as pc,D as Do,Da as ds,Db as ia,Dc as nt,Dd as mc,E as yn,Ea as us,Eb as oa,Ec as Oe,Ed as it,Fa as bt,Fb as sa,Fc as Ne,Fd as fc,G as et,Ga as ps,Gb as aa,Gd as Se,H as gt,Ha as ms,Hb as ca,Hc as Va,Hd as gc,I as Oo,Ib as la,Ic as Ha,Id as ue,J as No,Ja as fs,Jb as da,Jc as Wa,Jd as Dn,K as Fo,Ka as gs,Kb as ua,Kc as Ga,Kd as hc,L as Mo,La as hs,Lb as pa,Lc as Ua,Ld as L,M as _o,Ma as ys,Mb as ma,Mc as Ja,Md as B,N as qo,Na as bs,Nb as Br,Nc as za,Nd as w,O as bn,Oa as Ss,Ob as St,Oc as Ka,Od as U,P as Sn,Pa as vs,Pb as Tn,Pc as Qa,Pd as b,Q as Bo,Qa as xs,Qb as In,Qc as Ya,Qd as wt,R as ht,Ra as Rs,Rb as fa,Rc as Xa,Rd as P,S as yt,Sa as ks,Sb as ga,Sc as Za,Sd as A,T as Vo,Tb as ha,Tc as En,Td as yc,U as Ho,Ua as ws,Ub as ya,Uc as ec,Ud as I,V as vn,Va as $s,Vb as ba,Vc as tc,Vd as bc,W as Wo,Wa as Ps,Wb as Sa,Wc as jn,Wd as G,X as xn,Xa as Cs,Xb as va,Xc as nc,Y as Go,Ya as Ts,Yb as xa,Yc as Vr,Z as Rn,Za as Is,Zb as Ra,Zc as rc,_a as Es,_b as ka,_c as Hr,aa as Uo,ab as Ls,ac as $a,ad as Y,ba as Jo,bb as As,bc as Pa,c as pn,ca as zo,cb as Ds,cc as re,cd as Fe,d as me,da as Ko,db as Os,dc as Ca,dd as Rt,e as mn,eb as Ns,ec as Ta,ed as ic,f as q,fb as Fs,fc as Ia,g as J,ga as Qo,gb as Bt,gc as Ea,gd as le,ha as kn,hb as Ms,hc as ja,ia as Fr,ib as _s,ic as La,id as Ue,ja as wn,jb as qs,jd as Wr,ka as Yo,kb as Bs,kc as Aa,kd as Me,la as Mr,lb as Vs,lc as Da,ld as oe,m as Nt,ma as Xo,mb as Hs,mc as Oa,md as M,n as Ft,na as Zo,nb as Ws,nc as Ae,nd as Ln,o as Mt,oa as es,ob as Gs,oc as vt,od as E,p as Le,pa as ts,pb as Us,pc as Na,pd as Gr,q as Po,qa as _t,qb as Js,qc as fe,qd as Ur,r as fn,ra as ns,rb as zs,rc as xt,rd as Ce,s as Co,sa as rs,sb as Ks,sc as Pe,sd as oc,t as Or,ta as $n,tb as Qs,td as sc,u as To,ua as is,ub as Ys,ud as An,v as Io,va as os,vb as Xs,vd as ac,w as Eo,wa as Pn,wb as _r,wc as De,wd as cc,x as jo,xa as ss,xb as qr,xc as Fa,xd as lc,y as gn,ya as Cn,yb as Zs,yc as Ma,z as Q,za as as,zb as ea,zc as _a,zd as de}from"./chunk-VQWDZ34M.js";import{execFileSync as rl,spawn as Cg}from"child_process";import{existsSync as ct,mkdirSync as ai,readFileSync as il,rmSync as Tg,writeFileSync as Wn}from"fs";import{homedir as Ig}from"os";import{dirname as Gn,isAbsolute as Eg,join as Jt,resolve as jg}from"path";import{execFileSync as Yf}from"child_process";import{createRequire as hf}from"module";var yf=hf(import.meta.url);function xc(e,t=[]){let n=bf(),r=rs(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 bf(){try{return yf.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as $t,spawnSync as vf}from"child_process";import{existsSync as xe,mkdtempSync as $c,readFileSync as xf,readdirSync as Rf,rmSync as Pc,symlinkSync as kf,writeFileSync as wf}from"fs";import{tmpdir as Cc}from"os";import{join as ce}from"path";import{spawnSync as Sf}from"child_process";function qe(e,t=Sf){try{return t(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}var $f=3e5,Pf=12;function Kr(e,t,n={}){let r=Qr(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:Jr(e),batches:[]};let i=Ef(t,r),o=n.timeoutMs??$f,s=Of(e,t),a=Jr(e),c=$c(ce(Cc(),"scip-cleanup-verify-")),l=[],d=new Map;try{$t("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore"}),Nf(e,c);for(let u of r)d.set(u.label,kc(u,c,o).rawErrors);for(let u of t.batches){Ic(c,u);let m=null;for(let f of r){let g=kc(f,c,o),h=Cf(g,d.get(f.label)??[],g.rawErrors);if(h.status==="failed"){let y=h.errors.length>0?h.errors:g.outputTail;m={depth:u.depth,status:"failed",reason:`${f.label}: ${h.reason}`,errors:y.slice(0,Pf)};break}}if(!m)l.push({depth:u.depth,status:"verified"});else{l.push(m);break}}}finally{try{$t("git",["-C",e,"worktree","remove","--force",c],{stdio:"ignore"})}catch{Pc(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 Cf(e,t,n){let r=Tf(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 Tf(e,t){let n=If(e),r=new Map,i=[];for(let o of t){let s=Tc(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function If(e){let t=new Map;for(let n of e){let r=Tc(n);t.set(r,(t.get(r)??0)+1)}return t}function Ef(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 Tc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Rc=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],jf=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Qr(e){let t=[];if(xe(ce(e,"tsconfig.json"))){let n=ce(e,"node_modules",".bin","tsc");t.push(xe(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Rc,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Rc,strength:"reference-aware"})}if(xe(ce(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=>xe(ce(e,n)))){let n=Lf();n&&t.push(n)}if(jf.some(n=>xe(ce(e,n)))){let n=Af(e);n&&t.push(n)}for(let n of Df(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:ce(e,n,"..","target")}});return t}function Lf(){return qe("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"}:qe("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function Af(e){let t=ce(e,"node_modules",".bin","clj-kondo");return xe(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...mn],strength:"reference-aware"}:qe("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...mn],strength:"reference-aware"}:qe("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...mn],strength:"reference-aware"}:null}function Df(e){let t=[];if(xe(ce(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Rf(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||xe(ce(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function Of(e,t){let n=new Set(Jr(e));return[...new Set(t.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function Jr(e){let t;try{t=$t("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}return t.split(`
3
- `).map(n=>n.slice(3).trim()).filter(n=>n!=="").sort()}function Nf(e,t){for(let n of["node_modules"]){let r=ce(e,n),i=ce(t,n);if(xe(r)&&!xe(i))try{kf(r,i,"junction")}catch{}}}function Ic(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=ce(e,r);xe(o)&&wf(o,Ff(xf(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function Yr(e,t){for(let n of t)Ic(e,n)}function Ec(e,t){let n=$c(ce(Cc(),"scip-cleanup-patch-"));try{return $t("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),Yr(n,t),$t("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{$t("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{Pc(n,{recursive:!0,force:!0})}}}function Xr(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 Zr(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 Ff(e,t,n={}){let r=e.split(`
4
- `),i=(n.rust===!0?Mf(e):Po(e)).split(`
5
- `),o=new Set;for(let s of t){let a=_f(r,s.start),c=Bf(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 Mf(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 _f(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 qf=200;function Bf(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>qf)break}return n}function kc(e,t,n){let r=vf(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,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:wc(i)};let o=Vf(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(Qf),diagnostics:s,parseBasis:o.parseBasis,outputTail:wc(i)}}function Vf(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:Hf(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:Wf(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=Gf(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:Uf(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:Jf(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:zf(t),parseBasis:"clj-kondo-json"}:{diagnostics:Kf(t),parseBasis:"heuristic"}}function Hf(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 Wf(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 Gf(e){let t=jc(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 Uf(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 Jf(e){let t=[];for(let n of e.split(`
8
- `)){if(!n.trim().startsWith("{"))continue;let r=zr(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 zf(e){let t=jc(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 Kf(e){return e.split(`
9
- `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function Qf(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 jc(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return zr(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?zr(t.slice(n)):null}function zr(e){try{return JSON.parse(e)}catch{return null}}function wc(e,t=10){return e.split(`
10
- `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Dc={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"]},Xf={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"},Zf={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 he(e,t){let n=t.languages??tt(e),r=n.map(a=>{let c=bn(et(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=ag(e,n,t),o=ei({semantics:i},"typescript"),s=Qr(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:dg(e)}}function Je(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=>ig(e,c,{hasIndexedGraph:og(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.`},...eg(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 eg(e){return tg(e).map(t=>{let n=ei(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${ng(t)} semantic provider`,status:r,evidence:"semantic",reason:rg(t,n)}})}function tg(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of Nc(e))t.add(n.language);return[...t].sort((n,r)=>Lc(n)-Lc(r))}function Lc(e){return e==="typescript"?0:1}function ng(e){return e==="typescript"?"TypeScript":"Rust"}function rg(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 ig(e,t,n){let r=e.indexers.find(d=>d.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=sg(t,n.runtimeProbe),a=cg(e,t),c=lg(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 ${Dc[t].join(", ")} files.`}}}function og(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function sg(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)??Ac(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=Oc(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)??Ac(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 Ac(e){let t=Xf[e];return t?fn(t):Oc(e)==="regex-only"?"regex":"unavailable"}function Oc(e){let t=Zf[e],n=t?jo(t):null;return n?.imports??n?.exports??n?.reExports??null}function ag(e,t,n){let r=[];return t.includes("typescript")&&r.push({language:"typescript",...xc(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&r.push({language:"rust",...Bo(e)}),r}function Nc(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function ei(e,t){return Nc(e).find(n=>n.language===t)}function cg(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 lg(e,t){let n=new Set(Dc[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function dg(e){try{return Yf("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as ug,existsSync as Pt,readFileSync as Ct,rmSync as _c,writeFileSync as ni}from"fs";import{join as st}from"path";var ot="<!-- scip-query:agent-setup:begin -->",On="<!-- scip-query:agent-setup:end -->",ti="# scip-query:agent-setup";function Ht(){if(process.stdin.isTTY)return"";try{return Ct(0,"utf-8")}catch{return""}}function Nn(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function Wt(e){let t=In(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 Fn(e,t={}){let n={written:[],unchanged:[],skipped:[]};return pg(e,n),t.gitHook&&mg(e,n),n}function qc(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Mc(e,"AGENTS.md",t,n),Mc(e,"CLAUDE.md",t,n),fg(e,t,n),n}function pg(e,t){let n=[ot,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- 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 non-trivial implementation requests: plan first (`scip-concrete-plan` skill, anchored by `scip-query plan-context <target>`), then implement.","- After the change, run the check matching what you did: extracted a helper -> `scip-query incomplete-migration`; new helper -> `scip-query recent-duplicates`; new params -> `scip-query unused-params`; new wrapper -> `scip-query wrapper-candidates`; schema/config change -> `scip-query co-change <file>`; deleted code -> `scip-query cleanup-plan --verify`.","- Before declaring the work done: `scip-query reindex && scip-query diff-gate` \u2014 fix findings or state why each is accepted.","- 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.",On].join(`
12
- `);Fc(e,"AGENTS.md",n,t);let r=Pt(st(e,"CLAUDE.md"))?Ct(st(e,"CLAUDE.md"),"utf-8"):"";if(r.includes("@AGENTS.md")&&!r.includes(ot)){t.unchanged.push("CLAUDE.md");return}let i=[ot,"@AGENTS.md",On].join(`
13
- `);Fc(e,"CLAUDE.md",i,t)}function Fc(e,t,n,r){let i=st(e,t),o=Pt(i)?Ct(i,"utf-8"):"",s;if(o.includes(ot)){let a=new RegExp(`${ot}[\\s\\S]*?${On}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
2
+ import{c as bc,d as zr,e as Fn,f as Sc,g as vc,h as xc,j as Rc}from"./chunk-DRH3AD7W.js";import{a as ot,b as v,c as qe,d as fe,e as $t,f as u,g as cc,h as P,i as $,j as oe,k as se,l as ve,m as Ut,n as yc}from"./chunk-RPEA7P5Z.js";import{$ as $n,$a as Ds,$b as Ca,$c as nc,A as Oo,Aa as ls,Ab as oa,Ac as Ne,Ad as pc,B as Sn,Bb as sa,Bd as Se,C as Fo,Ca as ds,Cb as aa,Cc as qa,Cd as mc,D as No,Da as us,Db as ca,Dc as Ba,Dd as de,E as vn,Ea as ps,Eb as la,Ec as Va,Ed as On,Fa as ms,Fb as da,Fc as Ha,Fd as fc,G as Bt,Ga as fs,Gb as Vr,Gc as Wa,Gd as L,H as Mo,Ha as gs,Hb as xt,Hc as Ga,Hd as B,I as _o,Ia as hs,Ib as In,Ic as Ua,Id as k,J as qo,Ja as ys,Jb as jn,Jc as Ja,Jd as U,K as Ae,Ka as bs,Kb as ua,Kc as za,Kd as b,L as Ue,La as Ss,Lb as pa,Lc as Ka,Ld as Ct,M as Bo,Mb as ma,Mc as Qa,Md as C,N as yt,Na as vs,Nb as fa,Nc as Ya,Nd as A,O as xn,Oa as xs,Ob as ga,Oc as En,Od as gc,P as Rn,Pa as Rs,Pb as ha,Pc as Xa,Pd as I,Q as Vo,Qa as ks,Qb as ya,Qc as Za,Qd as hc,R as Ho,Ra as ws,Rb as ba,Rc as Ln,Rd as G,S as Wo,Sa as $s,Sb as Sa,Sc as ec,T as kn,Ta as Cs,Tb as va,Tc as Hr,U as Go,Ua as Ps,Ub as xa,Uc as tc,V as bt,Va as Ts,Vb as be,Vc as Wr,W as St,Wa as Is,Wb as Ra,X as Uo,Xa as js,Xb as Gt,Xc as Y,Y as Jo,Ya as Es,Yb as ka,Z as wn,Za as Ls,Zb as wa,Zc as Me,_ as zo,_a as As,_b as $a,_c as wt,aa as Ko,ab as Wt,ac as Pa,ba as Cn,bb as Os,bc as Ta,bd as ce,c as gn,cb as Fs,cc as Ia,d as pe,da as Qo,db as Ns,dc as ja,dd as Je,e as hn,ea as Yo,eb as Ms,ed as Gr,f as q,fa as Pn,fb as _s,fc as Ea,fd as _e,g as J,ga as qr,gb as qs,gc as La,gd as ie,hb as Bs,hc as Aa,hd as M,ia as Xo,ib as Vs,id as An,ja as nt,jb as Hs,jd as j,kb as Ws,kd as Ur,lb as Gs,lc as De,ld as Jr,m as Mt,ma as Vt,mb as Us,mc as Oe,md as Pe,n as _t,na as Zo,nb as Js,nc as Rt,nd as rc,o as qt,oa as es,ob as zs,oc as Da,od as ic,p as Le,pa as ts,pb as Ks,pc as me,pd as Dn,q as Io,qa as ns,qb as Br,qc as kt,qd as oc,r as yn,ra as Ht,rb as Qs,rc as Ce,rd as sc,s as jo,sa as rs,sb as Ys,sc as Oa,sd as ac,t as _r,ta as is,tb as Xs,tc as Fa,u as Eo,ua as Tn,ub as Zs,uc as Na,ud as le,v as Lo,va as os,vb as ea,vc as rt,vd as K,w as Ao,wa as ss,wb as ta,wc as Ma,wd as lc,x as Do,xa as as,xb as na,xc as _a,xd as dc,y as bn,ya as vt,yb as ra,yc as it,yd as uc,z as Q,za as cs,zb as ia,zc as Fe,zd as ze}from"./chunk-ESNRT7QN.js";import{execFileSync as il,spawn as Ag}from"child_process";import{existsSync as dt,mkdirSync as li,readFileSync as ol,rmSync as Dg,writeFileSync as Un}from"fs";import{homedir as Og}from"os";import{dirname as Jn,isAbsolute as Fg,join as Qt,resolve as Ng}from"path";import{execFileSync as ng}from"child_process";import{existsSync as kc,readdirSync as bf}from"fs";import{isAbsolute as Sf,join as Kr,resolve as vf}from"path";var xf={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:yt.language,indexerBinary:yt.indexerBinary,checkCommand:`${yt.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:yt.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:yt.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",Sf(r)?r:vf(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",wc(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",wc(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=Kr(e,"vendor","bin","scip-php"),r=Kr(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",kc(r)?r:kc(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function st(e){return xf[e]}function wc(e,t){let n;try{n=bf(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Kr(e,i);return null}import{createRequire as Rf}from"module";var kf=Rf(import.meta.url);function $c(e,t=[]){let n=wf(),r=is(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 wf(){try{return kf.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Pt,spawnSync as $f}from"child_process";import{existsSync as xe,mkdtempSync as Ic,readFileSync as Cf,readdirSync as Pf,rmSync as jc,symlinkSync as Tf,writeFileSync as If}from"fs";import{tmpdir as Ec}from"os";import{join as ae}from"path";var jf=3e5,Ef=12;function Xr(e,t,n={}){let r=Zr(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:Qr(e),batches:[]};let i=Of(t,r),o=n.timeoutMs??jf,s=qf(e,t),a=Qr(e),c=Ic(ae(Ec(),"scip-cleanup-verify-")),l=[],d=new Map;try{Pt("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore"}),Bf(e,c);for(let p of r)d.set(p.label,Pc(p,c,o).rawErrors);for(let p of t.batches){Ac(c,p);let m=null;for(let f of r){let g=Pc(f,c,o),h=Lf(g,d.get(f.label)??[],g.rawErrors);if(h.status==="failed"){let y=h.errors.length>0?h.errors:g.outputTail;m={depth:p.depth,status:"failed",reason:`${f.label}: ${h.reason}`,errors:y.slice(0,Ef)};break}}if(!m)l.push({depth:p.depth,status:"verified"});else{l.push(m);break}}}finally{try{Pt("git",["-C",e,"worktree","remove","--force",c],{stdio:"ignore"})}catch{jc(c,{recursive:!0,force:!0})}}return{checkers:r.map(p=>p.label),uncoveredFiles:i,baselineErrors:[...d.values()].reduce((p,m)=>p+m.length,0),dirtyOverlap:s,dirtyWorkingTree:a,batches:l}}function Lf(e,t,n){let r=Af(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 Af(e,t){let n=Df(e),r=new Map,i=[];for(let o of t){let s=Lc(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function Df(e){let t=new Map;for(let n of e){let r=Lc(n);t.set(r,(t.get(r)??0)+1)}return t}function Of(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 Lc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Cc=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],Ff=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Zr(e){let t=[];if(xe(ae(e,"tsconfig.json"))){let n=ae(e,"node_modules",".bin","tsc");t.push(xe(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Cc,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Cc,strength:"reference-aware"})}if(xe(ae(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=>xe(ae(e,n)))){let n=Nf();n&&t.push(n)}if(Ff.some(n=>xe(ae(e,n)))){let n=Mf(e);n&&t.push(n)}for(let n of _f(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:ae(e,n,"..","target")}});return t}function Nf(){return Ae("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"}:Ae("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function Mf(e){let t=ae(e,"node_modules",".bin","clj-kondo");return xe(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...hn],strength:"reference-aware"}:Ae("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...hn],strength:"reference-aware"}:Ae("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...hn],strength:"reference-aware"}:null}function _f(e){let t=[];if(xe(ae(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Pf(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||xe(ae(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function qf(e,t){let n=new Set(Qr(e));return[...new Set(t.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function Qr(e){let t;try{t=Pt("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}return t.split(`
3
+ `).map(n=>n.slice(3).trim()).filter(n=>n!=="").sort()}function Bf(e,t){for(let n of["node_modules"]){let r=ae(e,n),i=ae(t,n);if(xe(r)&&!xe(i))try{Tf(r,i,"junction")}catch{}}}function Ac(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=ae(e,r);xe(o)&&If(o,Vf(Cf(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function ei(e,t){for(let n of t)Ac(e,n)}function Dc(e,t){let n=Ic(ae(Ec(),"scip-cleanup-patch-"));try{return Pt("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),ei(n,t),Pt("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{Pt("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{jc(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 ni(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 Vf(e,t,n={}){let r=e.split(`
4
+ `),i=(n.rust===!0?Hf(e):Io(e)).split(`
5
+ `),o=new Set;for(let s of t){let a=Wf(r,s.start),c=Uf(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 Hf(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 Wf(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 Gf=200;function Uf(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>Gf)break}return n}function Pc(e,t,n){let r=$f(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,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:Tc(i)};let o=Jf(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(tg),diagnostics:s,parseBasis:o.parseBasis,outputTail:Tc(i)}}function Jf(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:zf(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:Kf(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=Qf(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:Yf(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:Xf(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:Zf(t),parseBasis:"clj-kondo-json"}:{diagnostics:eg(t),parseBasis:"heuristic"}}function zf(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 Kf(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 Qf(e){let t=Oc(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 Yf(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 Xf(e){let t=[];for(let n of e.split(`
8
+ `)){if(!n.trim().startsWith("{"))continue;let r=Yr(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(p=>!!p&&typeof p=="object"&&p.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 Zf(e){let t=Oc(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 eg(e){return e.split(`
9
+ `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function tg(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 Oc(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return Yr(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?Yr(t.slice(n)):null}function Yr(e){try{return JSON.parse(e)}catch{return null}}function Tc(e,t=10){return e.split(`
10
+ `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Mc={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"]},rg={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"},ig={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 ge(e,t){let n=t.languages??rt(e),r=n.map(a=>{let c=kn(st(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=pg(e,n,t),o=ri({semantics:i},"typescript"),s=Zr(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:gg(e)}}function Ke(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=>lg(e,c,{hasIndexedGraph:dg(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.`},...og(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 og(e){return sg(e).map(t=>{let n=ri(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${ag(t)} semantic provider`,status:r,evidence:"semantic",reason:cg(t,n)}})}function sg(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of qc(e))t.add(n.language);return[...t].sort((n,r)=>Fc(n)-Fc(r))}function Fc(e){return e==="typescript"?0:1}function ag(e){return e==="typescript"?"TypeScript":"Rust"}function cg(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 lg(e,t,n){let r=e.indexers.find(d=>d.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=ug(t,n.runtimeProbe),a=mg(e,t),c=fg(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 ${Mc[t].join(", ")} files.`}}}function dg(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function ug(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)??Nc(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=_c(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)??Nc(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 Nc(e){let t=rg[e];return t?yn(t):_c(e)==="regex-only"?"regex":"unavailable"}function _c(e){let t=ig[e],n=t?Do(t):null;return n?.imports??n?.exports??n?.reExports??null}function pg(e,t,n){let r=[];return t.includes("typescript")&&r.push({language:"typescript",...$c(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&r.push({language:"rust",...Go(e)}),r}function qc(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function ri(e,t){return qc(e).find(n=>n.language===t)}function mg(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=ri(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 fg(e,t){let n=new Set(Mc[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function gg(e){try{return ng("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as hg,existsSync as Tt,readFileSync as It,rmSync as Hc,writeFileSync as oi}from"fs";import{join as ct}from"path";var at="<!-- scip-query:agent-setup:begin -->",Nn="<!-- scip-query:agent-setup:end -->",ii="# scip-query:agent-setup";function Jt(){if(process.stdin.isTTY)return"";try{return It(0,"utf-8")}catch{return""}}function Mn(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function zt(e){let t=jn(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 _n(e,t={}){let n={written:[],unchanged:[],skipped:[]};return yg(e,n),t.gitHook&&bg(e,n),n}function Wc(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Vc(e,"AGENTS.md",t,n),Vc(e,"CLAUDE.md",t,n),Sg(e,t,n),n}function yg(e,t){let n=[at,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- 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 non-trivial implementation requests: plan first (`scip-concrete-plan` skill, anchored by `scip-query plan-context <target>`), then implement.","- After the change, run the check matching what you did: extracted a helper -> `scip-query incomplete-migration`; new helper -> `scip-query recent-duplicates`; new params -> `scip-query unused-params`; new wrapper -> `scip-query wrapper-candidates`; schema/config change -> `scip-query co-change <file>`; deleted code -> `scip-query cleanup-plan --verify`.","- Before declaring the work done: `scip-query reindex && scip-query diff-gate` \u2014 fix findings or state why each is accepted.","- 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.",Nn].join(`
12
+ `);Bc(e,"AGENTS.md",n,t);let r=Tt(ct(e,"CLAUDE.md"))?It(ct(e,"CLAUDE.md"),"utf-8"):"";if(r.includes("@AGENTS.md")&&!r.includes(at)){t.unchanged.push("CLAUDE.md");return}let i=[at,"@AGENTS.md",Nn].join(`
13
+ `);Bc(e,"CLAUDE.md",i,t)}function Bc(e,t,n,r){let i=ct(e,t),o=Tt(i)?It(i,"utf-8"):"",s;if(o.includes(at)){let a=new RegExp(`${at}[\\s\\S]*?${Nn}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
14
14
 
15
15
  `)}${n}
16
16
  `:`${n}
17
- `;s===o?r.unchanged.push(t):(ni(i,s),r.written.push(t))}function Mc(e,t,n,r){let i=st(e,t);if(!Pt(i)){r.unchanged.push(t);return}let o=Ct(i,"utf-8");if(!o.includes(ot)){r.unchanged.push(t);return}let s=new RegExp(`${ot}[\\s\\S]*?${On}`),a=o.replace(s,"").replace(/\n{3,}/g,`
17
+ `;s===o?r.unchanged.push(t):(oi(i,s),r.written.push(t))}function Vc(e,t,n,r){let i=ct(e,t);if(!Tt(i)){r.unchanged.push(t);return}let o=It(i,"utf-8");if(!o.includes(at)){r.unchanged.push(t);return}let s=new RegExp(`${at}[\\s\\S]*?${Nn}`),a=o.replace(s,"").replace(/\n{3,}/g,`
18
18
 
19
- `).trim();r.removed.push(t),!n.dryRun&&(a.length===0?_c(i,{force:!0}):ni(i,`${a}
20
- `))}function mg(e,t){let n=st(e,".git","hooks");if(!Pt(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=st(n,"pre-commit"),i=["#!/bin/sh",ti,"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
- `);if(Pt(r)){let o=Ct(r,"utf-8");if(o.includes(ti)){if(o===i){t.unchanged.push(".git/hooks/pre-commit");return}}else{t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"});return}}ni(r,i),ug(r,493),t.written.push(".git/hooks/pre-commit")}function fg(e,t,n){let r=st(e,".git","hooks","pre-commit");if(!Pt(r)){n.unchanged.push(".git/hooks/pre-commit");return}if(!Ct(r,"utf-8").includes(ti)){n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"});return}n.removed.push(".git/hooks/pre-commit"),t.dryRun||_c(r,{force:!0})}import{createHash as gg}from"crypto";import{existsSync as _n,mkdirSync as hg,readFileSync as qn,readdirSync as yg,rmSync as Bc,writeFileSync as Vc}from"fs";import{join as Be}from"path";var Bn=Be(".scipquery","events"),bg=Be(".scipquery","ledger"),Hc="events.jsonl";function Wc(e){return Be(e,bg)}function ri(e){return Be(Wc(e),Hc)}function Gc(e,t,n,r,i,o={}){let s=new Map(e.map(l=>[re(l.check,l.findingId),l])),a=[],c=(l,d)=>{let u=n.get(l.findingId),m=d==="resolved"?o.verifiedAgainstByFinding?.get(re(l.check,l.findingId)):void 0;a.push({ts:i,check:l.check,findingId:l.findingId,event:d,commit:r,...o.comparisonBaseCommit?{comparisonBaseCommit:o.comparisonBaseCommit}:{},...m?{verifiedAgainstCommit:m}:{},...u?{symbol:u}:{}})};for(let l of t){let d=s.get(re(l.check,l.findingId));if(!d){c(l,"caught"),l.outcome==="suppressed"&&c(l,"suppressed");continue}d.outcome!==l.outcome&&(l.outcome==="resolved"?c(l,"resolved"):l.outcome==="suppressed"?c(l,"suppressed"):l.outcome==="still-open"&&c(l,"reopened"))}return a}function Uc(e){return ii(e,"HEAD")}function ii(e,t){try{let n=qr(e,["rev-parse","--verify",`${t}^{commit}`]).trim();return/^[0-9a-f]{40}$/.test(n)?n:null}catch{return null}}function Jc(e){try{return qr(e,["status","--porcelain=v1","--untracked-files=all"]).trim()===""}catch{return!1}}function zc(e,t){let n=ri(e),r=_n(n),i=[...r?Kc(n):[],...t];if(i.length>0){let o=Be(e,Bn);hg(o,{recursive:!0});for(let s of i)Sg(o,s)}r&&vg(e)}function Sg(e,t){let n=`${JSON.stringify({ts:t.ts,check:t.check,findingId:t.findingId,event:t.event,commit:t.commit,...t.comparisonBaseCommit?{comparisonBaseCommit:t.comparisonBaseCommit}:{},...t.verifiedAgainstCommit?{verifiedAgainstCommit:t.verifiedAgainstCommit}:{},...t.symbol?{symbol:t.symbol}:{}},null,2)}
22
- `,r=gg("sha256").update(n).digest("hex").slice(0,16).toUpperCase(),i=Be(e,`${t.ts}-${r}.json`);try{Vc(i,n,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o;if(qn(i,"utf-8")!==n)throw new Error(`outcome event filename collision: ${i}`,{cause:o})}}function vg(e){Bc(ri(e));let t=Be(Wc(e),".gitattributes");if(!_n(t))return;let n=qn(t,"utf-8").split(`
23
- `).filter(r=>r.trim()!==`${Hc} merge=union`).join(`
24
- `).replace(/^\n+|\n+$/g,"");n===""?Bc(t):Vc(t,`${n}
25
- `)}function Vn(e){let t=[],n=Be(e,Bn);if(_n(n))for(let i of yg(n).sort()){if(!i.endsWith(".json"))continue;let o=Qc(qn(Be(n,i),"utf-8"));o&&t.push(o)}let r=ri(e);return _n(r)&&t.push(...Kc(r)),xg(t)}function Kc(e){let t=[];for(let n of qn(e,"utf-8").split(`
26
- `)){let r=Qc(n);r&&t.push(r)}return t}function Qc(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}return kg(t)?t:null}function xg(e){let t=new Map;for(let n of e){let r=`${n.check}\0${n.findingId}\0${n.event}\0${n.commit??""}`,i=t.get(r);(!i||Mn(n)>Mn(i)||Mn(n)===Mn(i)&&n.ts<i.ts)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.ts-r.ts)}function Gt(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n?.event==="caught"||n?.event==="reopened")return n}}function Mn(e){return+(e.comparisonBaseCommit!==void 0)+ +(e.verifiedAgainstCommit!==void 0)*2}var Rg=["caught","resolved","suppressed","reopened"];function kg(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.ts=="number"&&typeof t.check=="string"&&typeof t.findingId=="string"&&Rg.includes(t.event)&&(t.commit===null||typeof t.commit=="string")&&(t.comparisonBaseCommit===void 0||typeof t.comparisonBaseCommit=="string")&&(t.verifiedAgainstCommit===void 0||t.event==="resolved"&&typeof t.verifiedAgainstCommit=="string")&&(t.symbol===void 0||typeof t.symbol=="string")}function Hn(e,t,n={}){let r=(n.now??Date.now)(),i=$g(t),o=Ca(e),s=e.config.projectRoot,a=(n.headCommit??Uc)(s),c=(n.resolveCommit??ii)(s,t.base),l=wg({previous:o,observed:i,result:t,projectRoot:s,commit:a,comparisonBaseCommit:c,runtime:n}),d=Ta(e,l.ledgerObserved,l.checksRun,r,l.retainedKeys);try{let u=new Map;for(let f of t.findings)f.symbol&&u.set(f.id,f.symbol);for(let f of t.suppressed)f.finding.symbol&&u.set(f.finding.id,f.finding.symbol);for(let[f,g]of l.replaySymbols)u.set(f,g);let m=Gc(o,d,u,a,r,{...c?{comparisonBaseCommit:c}:{},verifiedAgainstByFinding:l.verifiedAgainstByFinding});return(n.appendEvents??zc)(s,m),{ledger:d,observed:i,now:r,...l.warning?{warning:l.warning}:{}}}catch(u){return{ledger:d,observed:i,now:r,warning:[l.warning,`outcome event ledger not updated: ${u instanceof Error?u.message:String(u)}`].filter(Boolean).join("; ")}}}function wg(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(h=>re(h.check,h.findingId))),a=new Set(e.result.checksRun),c=e.result.changedFiles.length===0&&!Tn(e.result)&&e.commit!==null&&e.comparisonBaseCommit!==null,l=e.previous.filter(h=>h.outcome!=="resolved"&&(a.has(h.check)||c)&&!s.has(re(h.check,h.findingId)));if(at(`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??Vn)(e.projectRoot)}catch(h){for(let y of l)r.add(re(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${h instanceof Error?h.message:String(h)}`}}let u=new Map;for(let h of d){let y=re(h.check,h.findingId),S=u.get(y)??[];S.push(h),u.set(y,S)}let m=new Map;for(let h of l){let y=re(h.check,h.findingId),S=Gt(u.get(y)??[]),x=S?.comparisonBaseCommit??S?.commit;if(at(`candidate ${y} anchor=${String(x)} current=${String(e.comparisonBaseCommit)}`),!S?.comparisonBaseCommit&&S?.commit&&S.commit===e.commit){n.add(h.check);continue}if(!x||!e.commit||!e.comparisonBaseCommit){r.add(y);continue}if(x===e.comparisonBaseCommit){n.add(h.check);continue}let k=m.get(x)??[];k.push(h),m.set(x,k)}if(m.size===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let f=(e.runtime.worktreeIsClean??Jc)(e.projectRoot);if(at(`replay groups=${m.size} clean=${f} callback=${!!e.runtime.replayGate}`),!f||!e.runtime.replayGate){for(let h of m.values())for(let y of h)r.add(re(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o}}let g=[];for(let[h,y]of m){let S;try{S=e.runtime.replayGate(h),at(`replay base=${h} checks=${S.checksRun.join(",")} findings=${S.findings.length} suppressed=${S.suppressed.length}`)}catch(R){for(let D of y)r.add(re(D.check,D.findingId));g.push(`cross-HEAD outcome verification deferred for ${h.slice(0,12)}: ${R instanceof Error?R.message:String(R)}`);continue}let x=new Set(S.checksRun),k=Pg(S);for(let R of y){let D=re(R.check,R.findingId);if(!x.has(R.check)){r.add(D);continue}n.add(R.check);let _=k.find(O=>O.key===D);if(_){at(`replay retained exact ${D}`),t.push(_.observed),_.symbol&&o.set(_.observed.findingId,_.symbol);continue}let z=Gt(u.get(D)??[]),T=z?.symbol?k.find(O=>O.check===R.check&&O.symbol===z.symbol):void 0;if(T){at(`replay moved ${D} -> ${T.key}`),t.push(T.observed),T.symbol&&o.set(T.observed.findingId,T.symbol);continue}i.set(D,h),at(`replay verified ${D} against ${h}`)}}return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,...g.length>0?{warning:g.join("; ")}:{}}}function at(e){process.env.SCIP_QUERY_DEBUG&&console.error(`outcome-verification: ${e}`)}function $g(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 Pg(e){return[...e.findings.map(t=>({key:re(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:re(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 ol="SCIP_QUERY_SKIP_HOOK_INSTALL",oi="SCIP_QUERY_STOP_HOOK_MODE",Lg="scip-query hook-",Ag="scip-query diff-gate --hook",Yc="# scip-query:local-hooks:begin",Xc="# scip-query:local-hooks:end",Ut=[{relativePath:".codex/hooks.json",label:".codex/hooks.json"},{relativePath:".claude/settings.local.json",label:".claude/settings.local.json"}];function Tt(e,t={}){let n=sl(),r=t.env??process.env;if(Fg(r))return n.skipped.push({target:"project agent hooks",reason:`${ol}=1`}),n;let i=Wg(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),Og(e,n,t.dryRun),t.remove?(el(e,Ut[0],n,{dryRun:t.dryRun}),el(e,Ut[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(Zc(e,Ut[0],n,{provider:"codex",commandPrefix:i,force:t.force}),Zc(e,Ut[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&Dg({homeDir:t.homeDir,result:n}),n)}function Dg(e={}){let t=e.result??sl(),n=e.homeDir??Ig();return si({configPath:Jt(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),si({configPath:Jt(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function sl(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function Zc(e,t,n,r){if(ci(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook setup will not modify it"});return}let i=Jt(e,t.relativePath);_g({provider:r.provider,rootDir:Gn(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function el(e,t,n,r){if(ci(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}qg({configPath:Jt(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function Og(e,t,n=!1){let r=Ng(e);if(!r){t.warnings.push("Could not locate .git/info/exclude; local hook files may appear as untracked.");return}let i=Ut.filter(d=>!ci(e,d.relativePath));if(i.length===0)return;let o=[Yc,...i.map(d=>`/${d.relativePath}`),Xc].join(`
27
- `),s=ct(r)?il(r,"utf-8"):"",a=new RegExp(`${Le(Yc)}[\\s\\S]*?${Le(Xc)}\\n?`,"g"),c=s.replace(a,"").replace(/\n*$/,""),l=`${c}${c?`
19
+ `).trim();r.removed.push(t),!n.dryRun&&(a.length===0?Hc(i,{force:!0}):oi(i,`${a}
20
+ `))}function bg(e,t){let n=ct(e,".git","hooks");if(!Tt(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=ct(n,"pre-commit"),i=["#!/bin/sh",ii,"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
+ `);if(Tt(r)){let o=It(r,"utf-8");if(o.includes(ii)){if(o===i){t.unchanged.push(".git/hooks/pre-commit");return}}else{t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"});return}}oi(r,i),hg(r,493),t.written.push(".git/hooks/pre-commit")}function Sg(e,t,n){let r=ct(e,".git","hooks","pre-commit");if(!Tt(r)){n.unchanged.push(".git/hooks/pre-commit");return}if(!It(r,"utf-8").includes(ii)){n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"});return}n.removed.push(".git/hooks/pre-commit"),t.dryRun||Hc(r,{force:!0})}import{createHash as vg}from"crypto";import{existsSync as Bn,mkdirSync as xg,readFileSync as Vn,readdirSync as Rg,rmSync as Gc,writeFileSync as Uc}from"fs";import{join as Be}from"path";var Hn=Be(".scipquery","events"),kg=Be(".scipquery","ledger"),Jc="events.jsonl";function zc(e){return Be(e,kg)}function si(e){return Be(zc(e),Jc)}function Kc(e,t){let n=si(e),r=Bn(n),i=[...r?Qc(n):[],...t];if(i.length>0){let o=Be(e,Hn);xg(o,{recursive:!0});for(let s of i)wg(o,s)}r&&$g(e)}function wg(e,t){let n=`${JSON.stringify({ts:t.ts,check:t.check,findingId:t.findingId,event:t.event,commit:t.commit,...t.comparisonBaseCommit?{comparisonBaseCommit:t.comparisonBaseCommit}:{},...t.verifiedAgainstCommit?{verifiedAgainstCommit:t.verifiedAgainstCommit}:{},...t.symbol?{symbol:t.symbol}:{}},null,2)}
22
+ `,r=vg("sha256").update(n).digest("hex").slice(0,16).toUpperCase(),i=Be(e,`${t.ts}-${r}.json`);try{Uc(i,n,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o;if(Vn(i,"utf-8")!==n)throw new Error(`outcome event filename collision: ${i}`,{cause:o})}}function $g(e){Gc(si(e));let t=Be(zc(e),".gitattributes");if(!Bn(t))return;let n=Vn(t,"utf-8").split(`
23
+ `).filter(r=>r.trim()!==`${Jc} merge=union`).join(`
24
+ `).replace(/^\n+|\n+$/g,"");n===""?Gc(t):Uc(t,`${n}
25
+ `)}function Wn(e){let t=[],n=Be(e,Hn);if(Bn(n))for(let i of Rg(n).sort()){if(!i.endsWith(".json"))continue;let o=Yc(Vn(Be(n,i),"utf-8"));o&&t.push(o)}let r=si(e);return Bn(r)&&t.push(...Qc(r)),Cg(t)}function Qc(e){let t=[];for(let n of Vn(e,"utf-8").split(`
26
+ `)){let r=Yc(n);r&&t.push(r)}return t}function Yc(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}return Tg(t)?t:null}function Cg(e){let t=new Map;for(let n of e){let r=`${n.check}\0${n.findingId}\0${n.event}\0${n.commit??""}`,i=t.get(r);(!i||qn(n)>qn(i)||qn(n)===qn(i)&&n.ts<i.ts)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.ts-r.ts)}function qn(e){return+(e.comparisonBaseCommit!==void 0)+ +(e.verifiedAgainstCommit!==void 0)*2}var Pg=["caught","resolved","suppressed","reopened"];function Tg(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.ts=="number"&&typeof t.check=="string"&&typeof t.findingId=="string"&&Pg.includes(t.event)&&(t.commit===null||typeof t.commit=="string")&&(t.comparisonBaseCommit===void 0||typeof t.comparisonBaseCommit=="string")&&(t.verifiedAgainstCommit===void 0||t.event==="resolved"&&typeof t.verifiedAgainstCommit=="string")&&(t.symbol===void 0||typeof t.symbol=="string")}function Gn(e,t,n={}){let r=(n.now??Date.now)(),i=Eg(t),o=$a(e),s=e.config.projectRoot,a=n.headCommit?n.headCommit(s):nt(s)?.headCommit??null,c=n.resolveCommit?n.resolveCommit(s,t.base):jg(s,t.base),l=Ig({previous:o,observed:i,result:t,projectRoot:s,commit:a,comparisonBaseCommit:c,runtime:n}),d=Ca(e,l.ledgerObserved,l.checksRun,r,l.retainedKeys);try{let p=new Map;for(let f of t.findings)f.symbol&&p.set(f.id,f.symbol);for(let f of t.suppressed)f.finding.symbol&&p.set(f.finding.id,f.finding.symbol);for(let[f,g]of l.replaySymbols)p.set(f,g);let m=Ra(o,d,p,a,r,{...c?{comparisonBaseCommit:c}:{},verifiedAgainstByFinding:l.verifiedAgainstByFinding});return(n.appendEvents??Kc)(s,m),{ledger:d,observed:i,now:r,...l.warning?{warning:l.warning}:{}}}catch(p){return{ledger:d,observed:i,now:r,warning:[l.warning,`outcome event ledger not updated: ${p instanceof Error?p.message:String(p)}`].filter(Boolean).join("; ")}}}function Ig(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(h=>be(h.check,h.findingId))),a=new Set(e.result.checksRun),c=e.result.changedFiles.length===0&&!In(e.result)&&e.commit!==null&&e.comparisonBaseCommit!==null,l=e.previous.filter(h=>h.outcome!=="resolved"&&(a.has(h.check)||c)&&!s.has(be(h.check,h.findingId)));if(lt(`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??Wn)(e.projectRoot)}catch(h){for(let y of l)r.add(be(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${h instanceof Error?h.message:String(h)}`}}let p=new Map;for(let h of d){let y=be(h.check,h.findingId),S=p.get(y)??[];S.push(h),p.set(y,S)}let m=new Map;for(let h of l){let y=be(h.check,h.findingId),S=Gt(p.get(y)??[]),x=S?.comparisonBaseCommit??S?.commit;if(lt(`candidate ${y} anchor=${String(x)} current=${String(e.comparisonBaseCommit)}`),!S?.comparisonBaseCommit&&S?.commit&&S.commit===e.commit){n.add(h.check);continue}if(!x||!e.commit||!e.comparisonBaseCommit){r.add(y);continue}if(x===e.comparisonBaseCommit){n.add(h.check);continue}let w=m.get(x)??[];w.push(h),m.set(x,w)}if(m.size===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let f=e.runtime.worktreeIsClean?.(e.projectRoot)??nt(e.projectRoot)?.clean??!1;if(lt(`replay groups=${m.size} clean=${f} callback=${!!e.runtime.replayGate}`),!f||!e.runtime.replayGate){for(let h of m.values())for(let y of h)r.add(be(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o}}let g=[];for(let[h,y]of m){let S;try{S=e.runtime.replayGate(h),lt(`replay base=${h} checks=${S.checksRun.join(",")} findings=${S.findings.length} suppressed=${S.suppressed.length}`)}catch(R){for(let D of y)r.add(be(D.check,D.findingId));g.push(`cross-HEAD outcome verification deferred for ${h.slice(0,12)}: ${R instanceof Error?R.message:String(R)}`);continue}let x=new Set(S.checksRun),w=Lg(S);for(let R of y){let D=be(R.check,R.findingId);if(!x.has(R.check)){r.add(D);continue}n.add(R.check);let _=w.find(O=>O.key===D);if(_){lt(`replay retained exact ${D}`),t.push(_.observed),_.symbol&&o.set(_.observed.findingId,_.symbol);continue}let z=Gt(p.get(D)??[]),T=z?.symbol?w.find(O=>O.check===R.check&&O.symbol===z.symbol):void 0;if(T){lt(`replay moved ${D} -> ${T.key}`),t.push(T.observed),T.symbol&&o.set(T.observed.findingId,T.symbol);continue}i.set(D,h),lt(`replay verified ${D} against ${h}`)}}return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,...g.length>0?{warning:g.join("; ")}:{}}}function jg(e,t){let n=Vt(e,["rev-parse","--verify",`${t}^{commit}`]);return n&&/^[0-9a-f]{40}$/.test(n)?n:null}function lt(e){process.env.SCIP_QUERY_DEBUG&&console.error(`outcome-verification: ${e}`)}function Eg(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 Lg(e){return[...e.findings.map(t=>({key:be(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:be(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 sl="SCIP_QUERY_SKIP_HOOK_INSTALL",ai="SCIP_QUERY_STOP_HOOK_MODE",Mg="scip-query hook-",_g="scip-query diff-gate --hook",Xc="# scip-query:local-hooks:begin",Zc="# scip-query:local-hooks:end",Kt=[{relativePath:".codex/hooks.json",label:".codex/hooks.json"},{relativePath:".claude/settings.local.json",label:".claude/settings.local.json"}];function jt(e,t={}){let n=al(),r=t.env??process.env;if(Hg(r))return n.skipped.push({target:"project agent hooks",reason:`${sl}=1`}),n;let i=Qg(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),Bg(e,n,t.dryRun),t.remove?(tl(e,Kt[0],n,{dryRun:t.dryRun}),tl(e,Kt[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(el(e,Kt[0],n,{provider:"codex",commandPrefix:i,force:t.force}),el(e,Kt[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&qg({homeDir:t.homeDir,result:n}),n)}function qg(e={}){let t=e.result??al(),n=e.homeDir??Og();return ci({configPath:Qt(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),ci({configPath:Qt(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function al(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function el(e,t,n,r){if(di(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook setup will not modify it"});return}let i=Qt(e,t.relativePath);Gg({provider:r.provider,rootDir:Jn(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function tl(e,t,n,r){if(di(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}Ug({configPath:Qt(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function Bg(e,t,n=!1){let r=Vg(e);if(!r){t.warnings.push("Could not locate .git/info/exclude; local hook files may appear as untracked.");return}let i=Kt.filter(d=>!di(e,d.relativePath));if(i.length===0)return;let o=[Xc,...i.map(d=>`/${d.relativePath}`),Zc].join(`
27
+ `),s=dt(r)?ol(r,"utf-8"):"",a=new RegExp(`${Le(Xc)}[\\s\\S]*?${Le(Zc)}\\n?`,"g"),c=s.replace(a,"").replace(/\n*$/,""),l=`${c}${c?`
28
28
 
29
29
  `:""}${o}
30
- `;!n&&l!==s&&(ai(Gn(r),{recursive:!0}),Wn(r,l)),t.gitExcluded.push(...i.map(d=>d.label))}function Ng(e){try{let t=rl("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();return t?Eg(t)?t:jg(e,t):null}catch{return null}}function ci(e,t){try{return rl("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore"}),!0}catch{return!1}}function Fg(e=process.env){let t=e[ol];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function Mg(e=process.env){let t=e[oi]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function _g(e){if(!e.createRoot&&!ct(e.rootDir))return;let t=li(e.configPath,e.label,e.result);if(!t)return;if(t.scipQueryHooks==="declined"&&!e.force){e.result.skipped.push({target:e.label,reason:"scip-query hooks were previously removed; rerun with --force"});return}let n=Bg(t,e.provider,e.commandPrefix);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let r=ct(e.configPath);ai(Gn(e.configPath),{recursive:!0}),Wn(e.configPath,`${JSON.stringify(n,null,2)}
31
- `),e.result[r?"updated":"installed"].push(e.label)}function si(e){if(!ct(e.configPath))return;let t=li(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},r={...n},i=!1;for(let s of["SessionStart","UserPromptSubmit","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=al(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(i=!0,c.length>0?r[s]=c:delete r[s])}if(!i)return;let o={...t};Object.keys(r).length>0?o.hooks=r:delete o.hooks,e.dryRun||(Object.keys(o).length===0?Tg(e.configPath,{force:!0}):Wn(e.configPath,`${JSON.stringify(o,null,2)}
32
- `)),e.result.removed.push(e.label)}function qg(e){let t=e.result.removed.length;if(si(e),!e.writeDeclinedTombstone)return;let n=li(e.configPath,e.label,e.result);if(!n)return;let r={...n,scipQueryHooks:"declined"};e.dryRun||(ai(Gn(e.configPath),{recursive:!0}),Wn(e.configPath,`${JSON.stringify(r,null,2)}
33
- `)),e.result.removed.length===t&&e.result.removed.push(`${e.label} (declined)`)}function li(e,t,n){if(!ct(e))return{};try{let r=JSON.parse(il(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 Bg(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;for(let o of["SessionStart","UserPromptSubmit","Stop"]){let s=Array.isArray(r[o])?r[o]:[];i.hooks[o]=[...al(s),Hg(t,o,n)]}return i}function al(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!Vg(n)):[]})).filter(t=>t.hooks.length>0)}function Vg(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(Lg)||t===Ag)}function Hg(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"}]}:{hooks:[{type:"command",command:`${n} hook-stop`,timeout:30,statusMessage:"Running scip-query diff gate"}]}}function Wg(e){let t=Jt(e,"node_modules",".bin","scip-query");return ct(t)?t:"scip-query"}async function cl(){let e=await zg(Ht());e&&console.log(JSON.stringify(e))}function Gg(e){if(Nn(e))return;let t=dl(e),n=ul(t);if(!(!n||!ct(n.paths.dbPath)))return rh(n,r=>{let i={minTogether:6,skip:[]},o=St(r,i),s=Hn(r,o,{replayGate:a=>St(r,{...i,base:a})});return s.warning&&console.error(`note: ${s.warning}`),o})}function ll(){let e=Gg(Ht());!e||e.findings.length===0||console.log(JSON.stringify(Ug(e,Mg())))}function Ug(e,t="feedback"){let n=Wt(e),r=Jg(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${r}
30
+ `;!n&&l!==s&&(li(Jn(r),{recursive:!0}),Un(r,l)),t.gitExcluded.push(...i.map(d=>d.label))}function Vg(e){try{let t=il("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();return t?Fg(t)?t:Ng(e,t):null}catch{return null}}function di(e,t){try{return il("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore"}),!0}catch{return!1}}function Hg(e=process.env){let t=e[sl];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function Wg(e=process.env){let t=e[ai]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function Gg(e){if(!e.createRoot&&!dt(e.rootDir))return;let t=ui(e.configPath,e.label,e.result);if(!t)return;if(t.scipQueryHooks==="declined"&&!e.force){e.result.skipped.push({target:e.label,reason:"scip-query hooks were previously removed; rerun with --force"});return}let n=Jg(t,e.provider,e.commandPrefix);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let r=dt(e.configPath);li(Jn(e.configPath),{recursive:!0}),Un(e.configPath,`${JSON.stringify(n,null,2)}
31
+ `),e.result[r?"updated":"installed"].push(e.label)}function ci(e){if(!dt(e.configPath))return;let t=ui(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},r={...n},i=!1;for(let s of["SessionStart","UserPromptSubmit","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=cl(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(i=!0,c.length>0?r[s]=c:delete r[s])}if(!i)return;let o={...t};Object.keys(r).length>0?o.hooks=r:delete o.hooks,e.dryRun||(Object.keys(o).length===0?Dg(e.configPath,{force:!0}):Un(e.configPath,`${JSON.stringify(o,null,2)}
32
+ `)),e.result.removed.push(e.label)}function Ug(e){let t=e.result.removed.length;if(ci(e),!e.writeDeclinedTombstone)return;let n=ui(e.configPath,e.label,e.result);if(!n)return;let r={...n,scipQueryHooks:"declined"};e.dryRun||(li(Jn(e.configPath),{recursive:!0}),Un(e.configPath,`${JSON.stringify(r,null,2)}
33
+ `)),e.result.removed.length===t&&e.result.removed.push(`${e.label} (declined)`)}function ui(e,t,n){if(!dt(e))return{};try{let r=JSON.parse(ol(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 Jg(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;for(let o of["SessionStart","UserPromptSubmit","Stop"]){let s=Array.isArray(r[o])?r[o]:[];i.hooks[o]=[...cl(s),Kg(t,o,n)]}return i}function cl(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!zg(n)):[]})).filter(t=>t.hooks.length>0)}function zg(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(Mg)||t===_g)}function Kg(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"}]}:{hooks:[{type:"command",command:`${n} hook-stop`,timeout:30,statusMessage:"Running scip-query diff gate"}]}}function Qg(e){let t=Qt(e,"node_modules",".bin","scip-query");return dt(t)?t:"scip-query"}async function ll(){let e=await eh(Jt());e&&console.log(JSON.stringify(e))}function Yg(e){if(Mn(e))return;let t=ul(e),n=pl(t);if(!(!n||!dt(n.paths.dbPath)))return lh(n,r=>{let i={minTogether:6,skip:[]},o=xt(r,i),s=Gn(r,o,{replayGate:a=>xt(r,{...i,base:a})});return s.warning&&console.error(`note: ${s.warning}`),o})}function dl(){let e=Yg(Jt());!e||e.findings.length===0||console.log(JSON.stringify(Xg(e,Wg())))}function Xg(e,t="feedback"){let n=zt(e),r=Zg(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${r}
34
34
 
35
35
  This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${r}
36
36
 
37
- Stop hook allowed this turn to finish. Review these findings when relevant. Set ${oi}=feedback to ask the agent to continue without a hook error, or ${oi}=block to enforce the gate.`}}function Jg(e){return Wt(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function zg(e){let t=dl(e),n=nh(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let r=ul(t);if(!r)return;let i=await Qg(r,n),o=n==="SessionStart"?Xg(r.projectRoot,r.config,r.paths):Zg(String(t.prompt??""),r.config),s=[i,o].filter(a=>!!a?.trim()).join(`
38
- `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}var Kg={prepare:ic,ensureService:Qo,freshness:Oe,requestRefresh:Xo,startOneShot(e){Cg("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function Qg(e,t,n=Kg){let r=Pe(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:Ne,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}).`:(Yg(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 Yg(e,t,n,r){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||r.requestRefresh(kn(n).activityPath,`agent hook observed ${t} index while service was idle`)}function Xg(e,t,n){let r=Oe(e,t,n),i=he(e,t),s=Je(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.","For non-trivial edits, plan with scip-concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].filter(c=>c!==void 0).join(`
39
- `)}function Zg(e,t={},n=process.env){if(th(t,n)==="off")return"";let r=eh(e);return r?`scip-query routing reminder:
40
- ${r.message}`:""}var tl=[{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-debug","scip-triage-issue"],keywords:["debug","bug","regression","failing","fails","error","wrong"],message:"Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."},{id:"review",skillNames:["scip-maintainability","scip-api-impact","scip-verify"],keywords:["review","maintainability","architecture","boundary"],message:"Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."},{id:"implementation",skillNames:["scip-concrete-plan","scip-verify"],keywords:["implement","build","change","refactor","fix","add","update"],message:"Implementation request: plan first with scip-concrete-plan and `scip-query plan-context <target>`, then verify with 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-diagram"],keywords:["diagram","visualize","visualise","flow map","architecture map"],message:"Diagram request: use scip-diagram and back every node and edge with scip-query evidence."},{id:"health",skillNames:["scip-cleanup-audit","scip-cleanup-improve"],keywords:["health","score","dossier","cleanup","dead code","duplicate","debloat","as high as","maximize","maximise"],message:"Health or cleanup request: use scip-cleanup-audit before editing; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}];function eh(e){let t=tl.find(i=>i.skillNames.some(o=>nl(e,o)));if(t)return t;let n=0,r=[];for(let i of tl){let o=i.keywords.filter(s=>nl(e,s)).length;n+=o,o>0&&r.push(i)}return n<2||r.length===0?null:r[0]}function th(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function nl(e,t){let n=t.trim().split(/\s+/).map(r=>Le(r)).join("\\s+");return new RegExp(`(?<![A-Za-z0-9_-])${n}(?![A-Za-z0-9_-])`,"i").test(e)}function dl(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function nh(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function ul(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=Go(t);if(n)try{let r=fe(n),i=De(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}function rh(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,sharedEvidenceDbPath:tc(e.projectRoot,e.config),entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality,coverageContracts:e.config.coverageContracts,docs:e.config.docs},r=new Ae(n,vt(e.projectRoot));try{return t(r)}finally{r.close()}}import{existsSync as Jn,mkdirSync as lh,symlinkSync as dh,readlinkSync as pi,unlinkSync as mi,readdirSync as yl}from"fs";import{join as Te,dirname as Qt,resolve as ze,relative as uh,isAbsolute as ph}from"path";import{homedir as zn,platform as mh}from"os";import{fileURLToPath as bl}from"url";import{execFileSync as pl}from"child_process";import{createRequire as ih}from"module";import{existsSync as oh}from"fs";import{platform as zt,arch as ml}from"os";var fl="v0.8.1",di="https://github.com/sourcegraph/scip",gl="SCIP_QUERY_SCIP_BIN";function sh(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[gl];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 ah(e){let t=ih(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 Un(e=process.env){return sh({platform:zt(),arch:ml(),env:e,isOnPath:gt,fileExists:oh,resolveSidecar:ah})?.path??null}function Kt(){return Un()!==null}function ch(){let e=zt(),t=ml(),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:`${di}/releases/download/${fl}/${o}`,filename:o}}function ui(){let e=ch();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),zt()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
41
- `),console.log("Or download manually:")):zt()==="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 ${gl} to a local scip.exe path.
37
+ Stop hook allowed this turn to finish. Review these findings when relevant. Set ${ai}=feedback to ask the agent to continue without a hook error, or ${ai}=block to enforce the gate.`}}function Zg(e){return zt(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function eh(e){let t=ul(e),n=ch(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let r=pl(t);if(!r)return;let i=await nh(r,n),o=n==="SessionStart"?ih(r.projectRoot,r.config,r.paths):oh(String(t.prompt??""),r.config),s=[i,o].filter(a=>!!a?.trim()).join(`
38
+ `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}var th={prepare:nc,ensureService:bc,freshness:Fe,requestRefresh:vc,startOneShot(e){Ag("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function nh(e,t,n=th){let r=Ce(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:Ne,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}).`:(rh(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 rh(e,t,n,r){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||r.requestRefresh(Pn(n).activityPath,`agent hook observed ${t} index while service was idle`)}function ih(e,t,n){let r=Fe(e,t,n),i=ge(e,t),s=Ke(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.","For non-trivial edits, plan with scip-concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].filter(c=>c!==void 0).join(`
39
+ `)}function oh(e,t={},n=process.env){if(ah(t,n)==="off")return"";let r=sh(e);return r?`scip-query routing reminder:
40
+ ${r.message}`:""}var nl=[{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-debug","scip-triage-issue"],keywords:["debug","bug","regression","failing","fails","error","wrong"],message:"Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."},{id:"review",skillNames:["scip-maintainability","scip-api-impact","scip-verify"],keywords:["review","maintainability","architecture","boundary"],message:"Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."},{id:"implementation",skillNames:["scip-concrete-plan","scip-verify"],keywords:["implement","build","change","refactor","fix","add","update"],message:"Implementation request: plan first with scip-concrete-plan and `scip-query plan-context <target>`, then verify with 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-diagram"],keywords:["diagram","visualize","visualise","flow map","architecture map"],message:"Diagram request: use scip-diagram and back every node and edge with scip-query evidence."},{id:"health",skillNames:["scip-cleanup-audit","scip-cleanup-improve"],keywords:["health","score","dossier","cleanup","dead code","duplicate","debloat","as high as","maximize","maximise"],message:"Health or cleanup request: use scip-cleanup-audit before editing; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}];function sh(e){let t=nl.find(i=>i.skillNames.some(o=>rl(e,o)));if(t)return t;let n=0,r=[];for(let i of nl){let o=i.keywords.filter(s=>rl(e,s)).length;n+=o,o>0&&r.push(i)}return n<2||r.length===0?null:r[0]}function ah(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function rl(e,t){let n=t.trim().split(/\s+/).map(r=>Le(r)).join("\\s+");return new RegExp(`(?<![A-Za-z0-9_-])${n}(?![A-Za-z0-9_-])`,"i").test(e)}function ul(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function ch(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function pl(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=Xo(t);if(n)try{let r=me(n),i=De(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}function lh(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,sharedEvidenceDbPath:Za(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 Oe(n,Rt(e.projectRoot));try{return t(r)}finally{r.close()}}import{existsSync as Kn,mkdirSync as gh,symlinkSync as hh,readlinkSync as fi,unlinkSync as gi,readdirSync as bl}from"fs";import{join as Te,dirname as Zt,resolve as Qe,relative as yh,isAbsolute as bh}from"path";import{homedir as Qn,platform as Sh}from"os";import{fileURLToPath as Sl}from"url";import{execFileSync as ml}from"child_process";import{createRequire as dh}from"module";import{existsSync as uh}from"fs";import{platform as Yt,arch as fl}from"os";var gl="v0.8.1",pi="https://github.com/sourcegraph/scip",hl="SCIP_QUERY_SCIP_BIN";function ph(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[hl];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 mh(e){let t=dh(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 zn(e=process.env){return ph({platform:Yt(),arch:fl(),env:e,isOnPath:Ue,fileExists:uh,resolveSidecar:mh})?.path??null}function Xt(){return zn()!==null}function fh(){let e=Yt(),t=fl(),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:`${pi}/releases/download/${gl}/${o}`,filename:o}}function mi(){let e=fh();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Yt()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
41
+ `),console.log("Or download manually:")):Yt()==="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 ${hl} to a local scip.exe path.
42
42
  `),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
43
- `:` ${di}/releases/tag/${fl}
44
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function hl(e){if(zt()==="darwin"&&gt("brew")){e("Installing scip CLI via Homebrew...");try{if(pl("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),gt("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(gt("go")){e("Installing scip CLI via go install...");try{if(pl("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),gt("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: ${di}/releases`),!1}var fh=mh()==="win32",Kn=["_shared","scip-query","scip-setup","scip-calibrate","scip-cleanup-audit","scip-cleanup-improve","scip-integrity-audit","scip-twin-drift","scip-claim-audit","scip-probe-reachability","scip-hyper-optimization","scip-api-impact","scip-concrete-plan","scip-conductor","scip-debug","scip-explore","scip-root-cause","scip-triage-issue","scip-diagram","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook","scip-tla-model-system"];function Qn(e={}){let t=e.quiet?()=>{}:console.log,n=bl(import.meta.url),r=ze(Qt(n),"..","skills"),i=[Te(zn(),".claude","skills"),Te(zn(),".codex","skills"),Te(zn(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=Qt(s);if(!Jn(a))continue;lh(s,{recursive:!0});let c=xl(s);gh(s,r,c,o,t);for(let l of Kn){let d=Te(r,l),u=Te(s,l);if(!Jn(d)){o.skipped.push(`${c}/${l}`);continue}if(Jn(u)){try{let m=pi(u);if(ze(m)===ze(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}mi(u)}dh(d,u,fh?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function gh(e,t,n,r,i){let o=new Set(Kn);for(let s of yl(e)){if(o.has(s))continue;let a=Te(e,s),c;try{c=ze(Qt(a),pi(a))}catch{continue}vl(c,t)&&(mi(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function Sl(e={}){let t=bl(import.meta.url),n=ze(Qt(t),"..","skills"),r=e.homeDir??zn(),i=[Te(r,".claude","skills"),Te(r,".codex","skills"),Te(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!Jn(s))continue;let a=xl(s);for(let c of yl(s)){let l=Te(s,c),d;try{let u=pi(l);d=ze(Qt(l),u)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!vl(d,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{mi(l)}catch(u){o.skipped.push(`${a}/${c} (${u instanceof Error?u.message:String(u)})`)}}}return o}function vl(e,t){let n=uh(ze(t),ze(e));return n===""||!n.startsWith("..")&&!ph(n)}function xl(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as Bu}from"child_process";import{performance as Xe}from"perf_hooks";import{existsSync as ke,readFileSync as jx,renameSync as Lx,rmSync as Ax,unlinkSync as Dx,writeFileSync as Ox}from"fs";import{dirname as br,extname as Nx,join as ut,resolve as Fx}from"path";import{execFileSync as gS}from"child_process";import{createHash as hS}from"crypto";import{closeSync as yS,copyFileSync as cr,existsSync as Re,mkdirSync as ar,mkdtempSync as bS,openSync as SS,readdirSync as vS,readFileSync as lr,renameSync as Ud,rmSync as Ye,statSync as xS,writeFileSync as RS}from"fs";import{basename as sr,dirname as V,extname as kS,join as ne,resolve as _d}from"path";import{platform as wS}from"os";import hh from"better-sqlite3";import{execFileSync as yh}from"child_process";import{existsSync as bh,readdirSync as Sh,readFileSync as vh}from"fs";import{extname as Yn,join as Rl}from"path";function lt(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Xn({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Xn(e){let t=new Set((e.extensions??Io).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!bh(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=vt(e.projectRoot),r=xh(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new hh(e.dbPath);try{let o=kh(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
45
- VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let u=0;for(let m of d){if(o.has(m))continue;let f=vh(Rl(e.projectRoot,m),"utf-8"),g=s.run(wh(m),m,f);u+=Number(g.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 xh(e,t){let n=Rh(e,t);if(n)return n;let r=[],i=o=>{let s=o?Rl(e,o):e,a;try{a=Sh(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Eo.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(Yn(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function Rh(e,t){try{return yh("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
46
- `).filter(r=>r&&t.has(Yn(r).toLowerCase())).sort()}catch{return null}}function kh(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 wh(e){return Yn(e).toLowerCase()===".vue"?"vue":Yn(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as $h}from"crypto";import{appendFileSync as Ph,existsSync as Ch,mkdirSync as Th,readFileSync as Ih}from"fs";import{dirname as Cl,join as kl}from"path";var Eh="<global-symbols>";function jh(e){let t=[];for(let n of e.all(`
43
+ `:` ${pi}/releases/tag/${gl}
44
+ `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function yl(e){if(Yt()==="darwin"&&Ue("brew")){e("Installing scip CLI via Homebrew...");try{if(ml("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),Ue("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(Ue("go")){e("Installing scip CLI via go install...");try{if(ml("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),Ue("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: ${pi}/releases`),!1}var vh=Sh()==="win32",Yn=["_shared","scip-query","scip-setup","scip-calibrate","scip-cleanup-audit","scip-cleanup-improve","scip-integrity-audit","scip-twin-drift","scip-claim-audit","scip-probe-reachability","scip-hyper-optimization","scip-api-impact","scip-concrete-plan","scip-conductor","scip-debug","scip-explore","scip-root-cause","scip-triage-issue","scip-diagram","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook","scip-tla-model-system"];function Xn(e={}){let t=e.quiet?()=>{}:console.log,n=Sl(import.meta.url),r=Qe(Zt(n),"..","skills"),i=[Te(Qn(),".claude","skills"),Te(Qn(),".codex","skills"),Te(Qn(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=Zt(s);if(!Kn(a))continue;gh(s,{recursive:!0});let c=Rl(s);xh(s,r,c,o,t);for(let l of Yn){let d=Te(r,l),p=Te(s,l);if(!Kn(d)){o.skipped.push(`${c}/${l}`);continue}if(Kn(p)){try{let m=fi(p);if(Qe(m)===Qe(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(p)}hh(d,p,vh?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function xh(e,t,n,r,i){let o=new Set(Yn);for(let s of bl(e)){if(o.has(s))continue;let a=Te(e,s),c;try{c=Qe(Zt(a),fi(a))}catch{continue}xl(c,t)&&(gi(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function vl(e={}){let t=Sl(import.meta.url),n=Qe(Zt(t),"..","skills"),r=e.homeDir??Qn(),i=[Te(r,".claude","skills"),Te(r,".codex","skills"),Te(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!Kn(s))continue;let a=Rl(s);for(let c of bl(s)){let l=Te(s,c),d;try{let p=fi(l);d=Qe(Zt(l),p)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!xl(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(p){o.skipped.push(`${a}/${c} (${p instanceof Error?p.message:String(p)})`)}}}return o}function xl(e,t){let n=yh(Qe(t),Qe(e));return n===""||!n.startsWith("..")&&!bh(n)}function Rl(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as Hu}from"child_process";import{performance as et}from"perf_hooks";import{existsSync as ke,readFileSync as _x,renameSync as qx,rmSync as Bx,unlinkSync as Vx,writeFileSync as Hx}from"fs";import{dirname as Rr,extname as Wx,join as mt,resolve as Gx}from"path";import{execFileSync as wS}from"child_process";import{createHash as $S}from"crypto";import{closeSync as CS,copyFileSync as pr,existsSync as Re,mkdirSync as ur,mkdtempSync as PS,openSync as TS,readdirSync as IS,readFileSync as mr,renameSync as zd,rmSync as Ze,statSync as jS,writeFileSync as ES}from"fs";import{basename as dr,dirname as V,extname as LS,join as ne,resolve as Bd}from"path";import{platform as AS}from"os";import Rh from"better-sqlite3";import{execFileSync as kh}from"child_process";import{existsSync as wh,readdirSync as $h,readFileSync as Ch}from"fs";import{extname as Zn,join as kl}from"path";function ut(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>er({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function er(e){let t=new Set((e.extensions??Lo).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!wh(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Rt(e.projectRoot),r=Ph(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Rh(e.dbPath);try{let o=Ih(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
45
+ VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let p=0;for(let m of d){if(o.has(m))continue;let f=Ch(kl(e.projectRoot,m),"utf-8"),g=s.run(jh(m),m,f);p+=Number(g.changes)}return p})(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 Ph(e,t){let n=Th(e,t);if(n)return n;let r=[],i=o=>{let s=o?kl(e,o):e,a;try{a=$h(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Ao.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(Zn(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function Th(e,t){try{return kh("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
46
+ `).filter(r=>r&&t.has(Zn(r).toLowerCase())).sort()}catch{return null}}function Ih(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 jh(e){return Zn(e).toLowerCase()===".vue"?"vue":Zn(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Lh}from"crypto";import{appendFileSync as Ah,existsSync as Dh,mkdirSync as Oh,readFileSync as Fh}from"fs";import{dirname as Il,join as $l}from"path";function hi(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 tr(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=hi(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"),wl(r,i,s)):s.size>0?wl(r,i,s):{mode:"closure",changedFiles:r,affectedFiles:Eh(r,t,i),reasons:[]}}function wl(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function Eh(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()}var Nh="<global-symbols>";function Mh(e){let t=[];for(let n of e.all(`
47
47
  SELECT relative_path, language, position_encoding, text
48
48
  FROM documents
49
49
  `))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
@@ -70,7 +70,7 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
70
70
  FROM defn_enclosing_ranges r
71
71
  JOIN documents d ON d.id = r.document_id
72
72
  JOIN global_symbols g ON g.id = r.symbol_id
73
- `))t.push({relativePath:n.relative_path,kind:"definition",values:fi(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
73
+ `))t.push({relativePath:n.relative_path,kind:"definition",values:yi(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
74
74
  SELECT d.relative_path,
75
75
  c.chunk_index,
76
76
  m.role,
@@ -85,7 +85,7 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
85
85
  JOIN chunks c ON c.id = m.chunk_id
86
86
  JOIN documents d ON d.id = c.document_id
87
87
  JOIN global_symbols g ON g.id = m.symbol_id
88
- `))t.push({relativePath:n.relative_path,kind:"mention",values:fi(n,[n.chunk_index,n.role])});for(let n of e.all(`
88
+ `))t.push({relativePath:n.relative_path,kind:"mention",values:yi(n,[n.chunk_index,n.role])});for(let n of e.all(`
89
89
  SELECT g.symbol,
90
90
  g.display_name,
91
91
  g.kind,
@@ -99,9 +99,9 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
99
99
  ) AND NOT EXISTS (
100
100
  SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
101
101
  )
102
- `))t.push({relativePath:Eh,kind:"global-symbol",values:fi(n)});return Lh(t)}function Lh(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=$h("sha256");for(let s of i.sort())o.update(String(Buffer.byteLength(s))),o.update(":"),o.update(s),o.update(`
103
- `);n.set(r,o.digest("hex"))}return n}function Ah(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 gi(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 hi(e,t=Dh){let n=t.now();if(!t.databaseExists(e.previousDbPath))return Zn(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return Zn(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),s=Pn(e.previousSnapshot,e.currentSnapshot),a=new Set(o),c=s.changes.length>0&&!ss(s).fullProject&&s.changes.every(m=>a.has(m.path)),l=Cn(s,c?t.dependencyGraph(r):new Map,o),d=Ah(t.factDigests(r),t.factDigests(i)),u=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(u).toISOString(),durationMs:Math.max(0,u-n),manifest:s,plan:l,comparison:d,evaluation:gi(l,d,o.length)}}catch(o){return Zn(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{wl(r),wl(i)}}function Tl(e,t,n,r=Date.now()){return Zn(e,t,r,r,n)}function Il(e){let t=Cl(e);return{latestPath:kl(t,"affected-shadow-latest.json"),historyPath:kl(t,"affected-shadow.jsonl")}}function El(e,t=n=>Ih(n,"utf-8")){let n=Il(e),r;try{r=JSON.parse(t(n.latestPath))}catch(S){let x=_h(S),k=x?"telemetry-missing":Mh(S);return Ke(n,k,x?void 0:S instanceof Error?S.message:String(S))}if(q(r)&&typeof r.version=="number"&&r.version!==1)return Ke(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!Nh(r))return Ke(n,"telemetry-malformed");if(r.status==="unavailable")return Fh(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:Ke(n,"telemetry-malformed");if(r.status!=="evaluated")return Ke(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!q(r.manifest)||!q(i)||!q(o)||!q(s))return Ke(n,"telemetry-malformed");let a=i.mode,c=J(i.affectedFiles),l=J(i.reasons),d=J(o.changedFiles),u=J(s.predictedFiles),m=J(s.actualFiles),f=J(s.missingFiles),g=s.recall,h=s.affectedRatio;if(a!=="none"&&a!=="closure"&&a!=="full-project"||c===null||l===null||d===null||u===null||m===null||f===null||typeof s.passed!="boolean"||!$l(g)||!$l(h))return Ke(n,"telemetry-malformed");let y=m.length===0?1:(m.length-f.length)/m.length;return!Pl(c,u)||!Pl(d,m)||s.passed!==(f.length===0)||Math.abs(g-y)>Number.EPSILON||f.some(S=>!m.includes(S)||u.includes(S))?Ke(n,"telemetry-malformed"):{state:s.passed?"passing":"failing",...n,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,mode:a,recall:g,affectedRatio:h,predictedFiles:u,actualFiles:m,missingFiles:f,fallbackReasons:l}}function jl(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 Ll(e,t,n=Oh){let r=Il(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function fi(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 Dh={now:()=>Date.now(),databaseExists:e=>Ch(e),openDatabase:(e,t,n)=>new Ae({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>pn(e),dependencyGraph:e=>gn(e),factDigests:e=>jh(e)},Oh={appendHistory:(e,t)=>{Th(Cl(e),{recursive:!0}),Ph(e,`${JSON.stringify(t)}
104
- `)},writeLatest:(e,t)=>yt(e,t,{spacing:2,trailingNewline:!0})};function Zn(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function wl(e){try{e?.close()}catch{}}function Nh(e){return q(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 Fh(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function $l(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function Pl(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Ke(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function Mh(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function _h(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as qh}from"crypto";import{copyFileSync as Bh,existsSync as Al,rmSync as Dl}from"fs";import{resolve as Vh}from"path";import Fl from"better-sqlite3";var Hh={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}]},Wh={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 Ml(e){let t=Date.now(),n=Gh(e.affectedFiles);if(Uh(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Dl(e.candidateDbPath,{force:!0}),!Al(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Al(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");Ol(e.previousDbPath,"previous SQLite generation",!1),Ol(e.miniDbPath,"incremental SQLite mini database"),Bh(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new Fl(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),yi(r,"main","candidate SQLite generation"),yi(r,"incremental","incremental SQLite mini database"),Jh(r,n),zh(r,n.length);let i=bi(r,"main",!0),o=Qe(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Kh(r),Qh(r),Yh(r),e.onStage?.("after-delete"),Xh(r),e.onStage?.("after-symbol-reconciliation"),Zh(r),e.onStage?.("after-insert"),ey(r),ty(r,n.length,o),e.onStage?.("before-commit")}).immediate(),_l(r,"main","candidate SQLite generation");let c=[...ny(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:Date.now()-t}}catch(i){try{r?.close()}finally{Dl(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function Gh(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 Uh(e,t,n){let r=[e,t,n].map(i=>Vh(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Ol(e,t,n=!0){let r=new Fl(e,{readonly:!0,fileMustExist:!0});try{yi(r,"main",t),n&&_l(r,"main",t)}finally{r.close()}}function yi(e,t,n){for(let[r,i]of Object.entries(Hh)){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(Wh)){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}`)}Nl(e,t,"documents",["relative_path"],n),Nl(e,t,"global_symbols",["symbol"],n)}function Nl(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 _l(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 Jh(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 zh(e,t){let n=Qe(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=Qe(e,`SELECT COUNT(*) AS value
102
+ `))t.push({relativePath:Nh,kind:"global-symbol",values:yi(n)});return _h(t)}function _h(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=Lh("sha256");for(let s of i.sort())o.update(String(Buffer.byteLength(s))),o.update(":"),o.update(s),o.update(`
103
+ `);n.set(r,o.digest("hex"))}return n}function qh(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 bi(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 Si(e,t=Bh){let n=t.now();if(!t.databaseExists(e.previousDbPath))return nr(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return nr(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),s=wn(e.previousSnapshot,e.currentSnapshot),a=new Set(o),c=s.changes.length>0&&!hi(s).fullProject&&s.changes.every(m=>a.has(m.path)),l=tr(s,c?t.dependencyGraph(r):new Map,o),d=qh(t.factDigests(r),t.factDigests(i)),p=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(p).toISOString(),durationMs:Math.max(0,p-n),manifest:s,plan:l,comparison:d,evaluation:bi(l,d,o.length)}}catch(o){return nr(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{Cl(r),Cl(i)}}function jl(e,t,n,r=Date.now()){return nr(e,t,r,r,n)}function El(e){let t=Il(e);return{latestPath:$l(t,"affected-shadow-latest.json"),historyPath:$l(t,"affected-shadow.jsonl")}}function Ll(e,t=n=>Fh(n,"utf-8")){let n=El(e),r;try{r=JSON.parse(t(n.latestPath))}catch(S){let x=Uh(S),w=x?"telemetry-missing":Gh(S);return Ye(n,w,x?void 0:S instanceof Error?S.message:String(S))}if(q(r)&&typeof r.version=="number"&&r.version!==1)return Ye(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!Hh(r))return Ye(n,"telemetry-malformed");if(r.status==="unavailable")return Wh(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:Ye(n,"telemetry-malformed");if(r.status!=="evaluated")return Ye(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!q(r.manifest)||!q(i)||!q(o)||!q(s))return Ye(n,"telemetry-malformed");let a=i.mode,c=J(i.affectedFiles),l=J(i.reasons),d=J(o.changedFiles),p=J(s.predictedFiles),m=J(s.actualFiles),f=J(s.missingFiles),g=s.recall,h=s.affectedRatio;if(a!=="none"&&a!=="closure"&&a!=="full-project"||c===null||l===null||d===null||p===null||m===null||f===null||typeof s.passed!="boolean"||!Pl(g)||!Pl(h))return Ye(n,"telemetry-malformed");let y=m.length===0?1:(m.length-f.length)/m.length;return!Tl(c,p)||!Tl(d,m)||s.passed!==(f.length===0)||Math.abs(g-y)>Number.EPSILON||f.some(S=>!m.includes(S)||p.includes(S))?Ye(n,"telemetry-malformed"):{state:s.passed?"passing":"failing",...n,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,mode:a,recall:g,affectedRatio:h,predictedFiles:p,actualFiles:m,missingFiles:f,fallbackReasons:l}}function Al(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 Dl(e,t,n=Vh){let r=El(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function yi(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 Bh={now:()=>Date.now(),databaseExists:e=>Dh(e),openDatabase:(e,t,n)=>new Oe({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>gn(e),dependencyGraph:e=>bn(e),factDigests:e=>Mh(e)},Vh={appendHistory:(e,t)=>{Oh(Il(e),{recursive:!0}),Ah(e,`${JSON.stringify(t)}
104
+ `)},writeLatest:(e,t)=>St(e,t,{spacing:2,trailingNewline:!0})};function nr(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function Cl(e){try{e?.close()}catch{}}function Hh(e){return q(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 Wh(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function Pl(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function Tl(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Ye(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function Gh(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function Uh(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as Jh}from"crypto";import{copyFileSync as zh,existsSync as Ol,rmSync as Fl}from"fs";import{resolve as Kh}from"path";import _l from"better-sqlite3";var Qh={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}]},Yh={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 ql(e){let t=Date.now(),n=Xh(e.affectedFiles);if(Zh(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Fl(e.candidateDbPath,{force:!0}),!Ol(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Ol(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");Nl(e.previousDbPath,"previous SQLite generation",!1),Nl(e.miniDbPath,"incremental SQLite mini database"),zh(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new _l(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),vi(r,"main","candidate SQLite generation"),vi(r,"incremental","incremental SQLite mini database"),ey(r,n),ty(r,n.length);let i=xi(r,"main",!0),o=Xe(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{ny(r),ry(r),iy(r),e.onStage?.("after-delete"),oy(r),e.onStage?.("after-symbol-reconciliation"),sy(r),e.onStage?.("after-insert"),ay(r),cy(r,n.length,o),e.onStage?.("before-commit")}).immediate(),Bl(r,"main","candidate SQLite generation");let c=[...ly(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:Date.now()-t}}catch(i){try{r?.close()}finally{Fl(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function Xh(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 Zh(e,t,n){let r=[e,t,n].map(i=>Kh(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Nl(e,t,n=!0){let r=new _l(e,{readonly:!0,fileMustExist:!0});try{vi(r,"main",t),n&&Bl(r,"main",t)}finally{r.close()}}function vi(e,t,n){for(let[r,i]of Object.entries(Qh)){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(Yh)){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}`)}Ml(e,t,"documents",["relative_path"],n),Ml(e,t,"global_symbols",["symbol"],n)}function Ml(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 Bl(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 ey(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 ty(e,t){let n=Xe(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=Xe(e,`SELECT COUNT(*) AS value
105
105
  FROM main.documents d
106
106
  JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
107
107
  FROM temp.incremental_affected_paths p
@@ -111,7 +111,7 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
111
111
  FROM incremental.documents d
112
112
  LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
113
113
  WHERE p.relative_path IS NULL
114
- 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 Kh(e){e.exec(`
114
+ 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 ny(e){e.exec(`
115
115
  CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
116
116
  INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
117
117
  SELECT g.symbol
@@ -138,7 +138,7 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
138
138
  FROM incremental.mentions m
139
139
  JOIN incremental.global_symbols g ON g.id = m.symbol_id
140
140
  WHERE m.role = 1;
141
- `)}function Qh(e){let t=e.prepare(`WITH changed_symbols AS (
141
+ `)}function ry(e){let t=e.prepare(`WITH changed_symbols AS (
142
142
  SELECT symbol FROM temp.incremental_old_defined_symbols
143
143
  UNION
144
144
  SELECT symbol FROM temp.incremental_new_defined_symbols
@@ -161,7 +161,7 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
161
161
  SELECT u.symbol
162
162
  FROM unaffected_definitions u
163
163
  JOIN changed_symbols c ON c.symbol = u.symbol
164
- LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Yh(e){e.exec(`
164
+ LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function iy(e){e.exec(`
165
165
  DELETE FROM main.mentions
166
166
  WHERE chunk_id IN (
167
167
  SELECT c.id
@@ -183,7 +183,7 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
183
183
  );
184
184
  DELETE FROM main.documents
185
185
  WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
186
- `)}function Xh(e){e.exec(`
186
+ `)}function oy(e){e.exec(`
187
187
  UPDATE main.global_symbols
188
188
  SET display_name = NULL,
189
189
  kind = NULL,
@@ -225,7 +225,7 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
225
225
  WHERE source.symbol = main.global_symbols.symbol
226
226
  )
227
227
  WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
228
- `)}function Zh(e){let t=Qe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Qe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Qe(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)
228
+ `)}function sy(e){let t=Xe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Xe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Xe(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)
229
229
  SELECT id + ?, language, relative_path, position_encoding, text
230
230
  FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
231
231
  SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
@@ -240,15 +240,15 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
240
240
  r.start_line, r.start_char, r.end_line, r.end_char
241
241
  FROM incremental.defn_enclosing_ranges r
242
242
  JOIN incremental.global_symbols source ON source.id = r.symbol_id
243
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function ey(e){e.exec(`
243
+ JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function ay(e){e.exec(`
244
244
  DELETE FROM main.global_symbols
245
245
  WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
246
246
  AND NOT EXISTS (
247
247
  SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
248
248
  );
249
- `)}function ty(e,t,n){let r=Qe(e,"SELECT COUNT(*) AS value FROM main.documents"),i=Qe(e,`SELECT COUNT(*) AS value
249
+ `)}function cy(e,t,n){let r=Xe(e,"SELECT COUNT(*) AS value FROM main.documents"),i=Xe(e,`SELECT COUNT(*) AS value
250
250
  FROM main.documents d
251
- 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 ny(e){let t=bi(e,"main",!0),n=bi(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 bi(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
251
+ 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 ly(e){let t=xi(e,"main",!0),n=xi(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 xi(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
252
252
  FROM ${t}.documents d
253
253
  ${r}
254
254
  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
@@ -270,11 +270,11 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
270
270
  JOIN ${t}.documents d ON d.id = c.document_id
271
271
  JOIN ${t}.global_symbols g ON g.id = m.symbol_id
272
272
  ${r}
273
- 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 f=JSON.stringify([d,m]),g=c.get(m.relative_path)??[];g.push(f),c.set(m.relative_path,g)}let l=new Map;for(let[d,u]of[...c].sort(([m],[f])=>m.localeCompare(f))){let m=qh("sha256");for(let f of u.sort())m.update(f).update(`
274
- `);l.set(d,m.digest("hex"))}return l}function Qe(e,t){return e.prepare(t).get().value}import{readFileSync as ry,writeFileSync as iy}from"fs";function dt(e,t){let n=Date.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:r}}function Bl(e){let t=e.readFingerprint(),n=oy(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return sy(e.cachePath,e.readFingerprint(),r),r}function oy(e,t){try{let n=JSON.parse(ry(e,"utf-8"));return ql(n.fingerprint)===ql(t)?{result:n.result}:null}catch{return null}}function sy(e,t,n){iy(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
275
- `)}function ql(e){return JSON.stringify(e)}import{createHash as ay}from"crypto";import{existsSync as Si,readFileSync as cy,readdirSync as ly}from"fs";import{dirname as vi,join as er,relative as dy,resolve as xi,sep as Vl}from"path";function Hl(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=Jl(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Wl(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=Jl(a,e);c&&c!==i&&s.add(c)}}return uy(e,r)}function Gl(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 Ri(e){if(e===".")return"root";let t=ay("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Ul(e,t){let n=xi(e),r={};for(let i of t)r[i]=py(n,i);return r}function Jl(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 uy(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 py(e,t){let n=t==="."?e:er(e,t),r=my(n),i=fy(n),o=i?gy(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 my(e){let t=er(e,"package.json");if(!Si(t))return{name:void 0,dependencyNames:[],failed:!1};let n=ki(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 fy(e){let t=er(e,"tsconfig.json");if(Si(t))return t;let n;try{n=ly(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?er(e,n[0]):void 0}function gy(e,t){let n=ki(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=hy(n.value,e,t),i=zl(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function hy(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=vi(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=Kl(a,i,n);c&&o.add(c)}return[...o]}function zl(e,t,n,r){let i=yy(t);if(i)return{pathsTargets:by(i,vi(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Sy(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=ki(o);return s.ok?zl(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function yy(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 by(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=Kl(o,t,n);s&&r.add(s)}return[...r]}function Sy(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=xi(vi(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Vl).includes("node_modules")&&me(n,i)&&Si(i))return i}function Kl(e,t,n){let r=e.replace(/\/?\*+$/,""),i=xi(t,r===""?".":r);if(!me(n,i))return;let s=dy(n,i).split(Vl).join("/");return s===""?".":s}function vy(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]!==`
276
- `;)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 ki(e){try{let t=cy(e,"utf-8"),n=JSON.parse(vy(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as xy,readFileSync as Ry,readdirSync as ky,statSync as wy}from"fs";import te from"path";var $y=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Yt(e,t=[]){let n=te.resolve(e),r=t.flatMap(c=>Cy(n,c));if(r.length>0)return Ql(n,Yl(r));let i=Py(n),o=Yl(i),s=Iy(n,o)?[n,...o]:o,a=s.length>0?s:[n];return Ql(n,a)}function Ql(e,t){return[...new Set(t.map(n=>jy(e,n)))].sort((n,r)=>n.localeCompare(r))}function Py(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=ky(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=te.join(r,o.name);if(o.isDirectory()){!$y.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&Ty(s)&&t.push(te.dirname(s))}}return t}function Cy(e,t){let n=t.trim();if(!n)return[];let r=te.resolve(e,n);if(!me(e,r))return[];try{let i=wy(r);if(i.isDirectory())return[r];if(i.isFile()&&Xl(te.basename(r)))return[te.dirname(r)]}catch{return[]}return[]}function Ty(e){if(!Xl(te.basename(e)))return!1;let t=Zl(e);return t?te.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function Xl(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function Yl(e){let t=[...new Set(e.map(n=>te.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&Ly(n,r)))}function Iy(e,t){if(t.length===0||t.some(r=>te.resolve(r)===e))return!1;let n=te.join(e,"tsconfig.json");return xy(n)&&Ey(n)}function Ey(e){let n=Zl(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!te.extname(r))):!1}function Zl(e){try{let t=JSON.parse(Ry(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function jy(e,t){let n=te.relative(e,t);return n?n.split(te.sep).join("/"):"."}function Ly(e,t){let n=te.relative(e,t);return!!n&&!n.startsWith("..")&&!te.isAbsolute(n)}import{createHash as Zy}from"crypto";import{existsSync as $i,readFileSync as pd,statSync as eb,writeFileSync as Pi}from"fs";import{join as tb}from"path";import{readFileSync as ed}from"fs";import{createRequire as Ay}from"module";import{dirname as Dy,isAbsolute as DC,relative as OC,resolve as NC,sep as FC}from"path";var td=Ay(import.meta.url),Oy=1,nd="0.4.0";function wi(){let e=Ny();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Ny(){try{let e=td.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(ed(e,"utf8"));if(t.version!==nd)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${nd}`};let n=Dy(e),r=td.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(ed(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:Fy(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Fy(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Oy}`}import{createHash as My}from"crypto";import{readFileSync as _y}from"fs";import{dirname as qy,join as tr}from"path";var nr=2,By="typescript-index";function rd(e){let t=tr(e,By);return{rootDir:t,requestDir:tr(t,"requests"),responseDir:tr(t,"responses")}}function id(e){try{let t=JSON.parse(_y(tr(qy(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:My("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}import{randomUUID as Vy}from"crypto";import{existsSync as Hy,mkdirSync as od,readFileSync as Wy,rmSync as sd}from"fs";import{resolve as ad}from"path";var Gy=12e4,Uy=5,rr=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=Jo(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Yy(),this.runtime=n.runtime??Xy}request(t){let n=kn(this.cacheDir),r=rd(this.cacheDir),i=Mr(n.statePath);if(!cd(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),s=ad(r.requestDir,`${o}.json`),a=ad(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;od(r.requestDir,{recursive:!0}),od(r.responseDir,{recursive:!0}),yt(s,{protocolVersion:nr,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Hy(a))return Jy(Wy(a,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Mr(n.statePath);if(!cd(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Uy)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{sd(s,{force:!0}),sd(a,{force:!0})}}};function cd(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=zo,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===nr&&n.isProcessAlive(e.pid)&&(r||i)}function Jy(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==nr||o.id!==t||o.ok===!0&&o.baseGeneration!==n)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0)throw new Error(typeof o.error=="string"?o.error:"TypeScript index service request failed.");let s=zy(o.response,r),a=[...new Set(i)].sort(),c=s.fragments.map(l=>l.relativePath).sort();if(JSON.stringify(c)!==JSON.stringify(a))throw new Error("TypeScript index service omitted or added an affected document.");return s}function zy(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(Ky)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:Qy(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 Ky(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 Qy(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Yy(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Gy}var Xy={now:Date.now,randomId:Vy,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ht};function nb(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=Pn(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"||!_t(l.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Cn(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=rb([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=ld(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=ld(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=ud(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=ud(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:dd(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:dd(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 rb(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 md(e){let t=Date.now();try{if(!$i(e.previousDbPath)||!$i(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=wi();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new Ae({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),s,a;try{s=pn(o,{includeIgnored:!1}).filter(_t).sort(),a=gn(o)}finally{o.close()}let c=performance.now()-n,l=nb({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?Yt(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:a,producerIdentity:r.producerIdentity,rootTsconfigExists:$i(tb(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let d=id(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let m=new rr({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}),f=performance.now()-n,g=eb(e.previousShardPath).size>=Ja;n=performance.now();let h=g?null:pd(e.previousShardPath),y=g?{completeIndexBytes:null,affectedIndexBytes:Ha(m.fragments)}:Ua({packageVersion:r.packageVersion,baseIndexBytes:h,fragments:m.fragments}),S=performance.now()-n;n=performance.now(),g?za({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:m.fragments}):(Wa({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:h,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),Ga({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.nextFragmentGeneration,fragments:m.fragments,documentIdentities:l.nextDocumentIdentities}));let x=performance.now()-n;n=performance.now(),y.completeIndexBytes&&Pi(e.candidateShardPath,y.completeIndexBytes),Pi(e.candidateAffectedScipPath,y.affectedIndexBytes);let k=performance.now()-n,R={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-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:f,serviceMs:m.durationMs,assemblyMs:S,fragmentStoreMs:x,writeMs:k}};return e.onStatus(`Incremental TypeScript index emitted ${R.affectedFiles.length} affected document(s) in ${(R.durationMs/1e3).toFixed(3)}s (${R.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${S.toFixed(0)}ms, fragments ${x.toFixed(0)}ms, write ${k.toFixed(0)}ms).`),R}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 fd(e){let t=wi();if(!t.available)throw new Error(t.reason);let n=Ka({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:pd(e.baseShardPath),packageVersion:t.packageVersion});Pi(e.candidateShardPath,n)}function ld(e,t,n){let r=e.files.filter(i=>Vo(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 Ci(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function dd(e,t){return Ci(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function ud(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),s=as({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,Ci(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function Ci(e){return Zy("sha256").update(e).digest("hex")}import{execFile as ib}from"child_process";import{existsSync as ir,renameSync as Ii,rmSync as Ei,statSync as ob}from"fs";import{cpus as sb}from"os";import{join as gd}from"path";function ab(e,t,n){if(!e.defaultOutputPath)return;let r=gd(t,e.defaultOutputPath);n!==r&&ir(r)&&Ii(r,n)}function cb(e,t,n){if(!e.defaultOutputPath)return null;let r=gd(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Ei(i,{force:!0}),ir(r)?(Ii(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function lb(e){e&&(Ei(e.defaultOutputPath,{force:!0}),e.backupPath&&ir(e.backupPath)&&Ii(e.backupPath,e.defaultOutputPath))}function db(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,sb().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function hd(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=db(o.length,r),c=await pb(o,a,l=>Ti(l,t,n));if(a>1){let l=new Map;for(let d of c.filter(u=>u.skipped)){let u=o.find(m=>m.id===d.id);u&&(n(`Retrying ${u.label} indexer serially after parallel failure...`),l.set(u.id,await Ti(u,t,n)))}s.push(...c.map(d=>l.get(d.id)??d))}else s.push(...c);for(let l of i)s.push(await Ti(l,t,n));return s.sort((l,d)=>e.findIndex(u=>u.id===l.id)-e.findIndex(u=>u.id===d.id))}async function Ti(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Ei(e.scipPath,{force:!0});let r=cb(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{let a=Oo(e.binary,e.args);await ub(a.binary,a.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),ab(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
277
- `)[0]}`,d=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:d}}}finally{lb(r)}if(!ir(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}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:c}}}let s;try{s=ob(e.scipPath).size}catch{s=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,outputBytes:s}}function ub(e,t,n){return new Promise((r,i)=>{ib(e,[...t],n,o=>{o?i(o):r()})})}async function pb(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 Jb from"better-sqlite3";import{existsSync as zb}from"fs";import{dirname as Kb,join as Qb,resolve as Yb}from"path";import{readFileSync as fb,rmSync as gb,statSync as hb,mkdtempSync as yb}from"fs";import{tmpdir as bb}from"os";import{join as ji}from"path";import{Worker as Sb}from"worker_threads";function mb(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function It(){return{skippedReferences:0,skippedReferenceReasons:mb(),skippedReferenceSamples:[]}}function or(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)}}function yd(e){return e.length>=8&&Sd(e.length)>1}function bd(e){let t=Sd(e.vueFiles.length),n=xb(e.vueFiles),r=kb(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=yb(ji(bb(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=vb(),l=Date.now();try{for(let m=0;m<r.length;m++)new Sb(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:ji(o,`${m}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<r.length;){if(Date.now()-l>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let d=r.map((m,f)=>{let g=JSON.parse(fb(ji(o,`${f}.json`),"utf-8"));if(!g.ok)throw new Error(`Vue reference worker failed: ${g.error}`);return g.result}),u={occurrences:d.flatMap(m=>m.occurrences),...It()};for(let m of d)or(u,m);return u}finally{gb(o,{recursive:!0,force:!0})}}function Sd(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 vb(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function xb(e){let t=Rb(),n=[];for(let r of e){let i=vd(r),o=Math.max(1,Math.ceil(i/t));for(let s=0;s<o;s++)n.push({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 Rb(){return Number.POSITIVE_INFINITY}function kb(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:wb(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 wb(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,vd(e.fileName)-e.startOffset)}function vd(e){try{return hb(e).size}catch{return 1}}import{createRequire as $b}from"module";import{existsSync as Pb,readFileSync as Ai}from"fs";import{dirname as xd,extname as Cb,join as Rd,relative as Tb,resolve as Ib}from"path";import{pathToFileURL as Eb}from"url";function jb(e){e.transaction(()=>{e.prepare(`
273
+ ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,p]of Object.entries({documents:i,chunks:o,definitions:s,mentions:a}))for(let m of p){let f=JSON.stringify([d,m]),g=c.get(m.relative_path)??[];g.push(f),c.set(m.relative_path,g)}let l=new Map;for(let[d,p]of[...c].sort(([m],[f])=>m.localeCompare(f))){let m=Jh("sha256");for(let f of p.sort())m.update(f).update(`
274
+ `);l.set(d,m.digest("hex"))}return l}function Xe(e,t){return e.prepare(t).get().value}import{readFileSync as dy,writeFileSync as uy}from"fs";function pt(e,t){let n=Date.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:r}}function Hl(e){let t=e.readFingerprint(),n=py(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return my(e.cachePath,e.readFingerprint(),r),r}function py(e,t){try{let n=JSON.parse(dy(e,"utf-8"));return Vl(n.fingerprint)===Vl(t)?{result:n.result}:null}catch{return null}}function my(e,t,n){uy(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
275
+ `)}function Vl(e){return JSON.stringify(e)}import{createHash as fy}from"crypto";import{existsSync as Ri,readFileSync as gy,readdirSync as hy}from"fs";import{dirname as ki,join as rr,relative as yy,resolve as wi,sep as Wl}from"path";function Gl(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=Kl(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Ul(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=Kl(a,e);c&&c!==i&&s.add(c)}}return by(e,r)}function Jl(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 $i(e){if(e===".")return"root";let t=fy("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function zl(e,t){let n=wi(e),r={};for(let i of t)r[i]=Sy(n,i);return r}function Kl(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 by(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 Sy(e,t){let n=t==="."?e:rr(e,t),r=vy(n),i=xy(n),o=i?Ry(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 vy(e){let t=rr(e,"package.json");if(!Ri(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Ci(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 xy(e){let t=rr(e,"tsconfig.json");if(Ri(t))return t;let n;try{n=hy(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?rr(e,n[0]):void 0}function Ry(e,t){let n=Ci(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=ky(n.value,e,t),i=Ql(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function ky(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=ki(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=Yl(a,i,n);c&&o.add(c)}return[...o]}function Ql(e,t,n,r){let i=wy(t);if(i)return{pathsTargets:$y(i,ki(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Cy(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=Ci(o);return s.ok?Ql(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function wy(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 $y(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=Yl(o,t,n);s&&r.add(s)}return[...r]}function Cy(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=wi(ki(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Wl).includes("node_modules")&&pe(n,i)&&Ri(i))return i}function Yl(e,t,n){let r=e.replace(/\/?\*+$/,""),i=wi(t,r===""?".":r);if(!pe(n,i))return;let s=yy(n,i).split(Wl).join("/");return s===""?".":s}function Py(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]!==`
276
+ `;)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 Ci(e){try{let t=gy(e,"utf-8"),n=JSON.parse(Py(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as Ty,readFileSync as Iy,readdirSync as jy,statSync as Ey}from"fs";import te from"path";var Ly=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function en(e,t=[]){let n=te.resolve(e),r=t.flatMap(c=>Dy(n,c));if(r.length>0)return Xl(n,Zl(r));let i=Ay(n),o=Zl(i),s=Fy(n,o)?[n,...o]:o,a=s.length>0?s:[n];return Xl(n,a)}function Xl(e,t){return[...new Set(t.map(n=>My(e,n)))].sort((n,r)=>n.localeCompare(r))}function Ay(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=jy(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=te.join(r,o.name);if(o.isDirectory()){!Ly.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&Oy(s)&&t.push(te.dirname(s))}}return t}function Dy(e,t){let n=t.trim();if(!n)return[];let r=te.resolve(e,n);if(!pe(e,r))return[];try{let i=Ey(r);if(i.isDirectory())return[r];if(i.isFile()&&ed(te.basename(r)))return[te.dirname(r)]}catch{return[]}return[]}function Oy(e){if(!ed(te.basename(e)))return!1;let t=td(e);return t?te.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function ed(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function Zl(e){let t=[...new Set(e.map(n=>te.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&_y(n,r)))}function Fy(e,t){if(t.length===0||t.some(r=>te.resolve(r)===e))return!1;let n=te.join(e,"tsconfig.json");return Ty(n)&&Ny(n)}function Ny(e){let n=td(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!te.extname(r))):!1}function td(e){try{let t=JSON.parse(Iy(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function My(e,t){let n=te.relative(e,t);return n?n.split(te.sep).join("/"):"."}function _y(e,t){let n=te.relative(e,t);return!!n&&!n.startsWith("..")&&!te.isAbsolute(n)}import{createHash as sb}from"crypto";import{existsSync as Ti,readFileSync as fd,statSync as ab,writeFileSync as Ii}from"fs";import{join as cb}from"path";import{readFileSync as nd}from"fs";import{createRequire as qy}from"module";import{dirname as By,isAbsolute as KP,relative as QP,resolve as YP,sep as XP}from"path";var rd=qy(import.meta.url),Vy=1,id="0.4.0";function Pi(){let e=Hy();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Hy(){try{let e=rd.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(nd(e,"utf8"));if(t.version!==id)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${id}`};let n=By(e),r=rd.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(nd(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:Wy(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Wy(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Vy}`}import{createHash as Gy}from"crypto";import{readFileSync as Uy}from"fs";import{dirname as Jy,join as ir}from"path";var or=2,zy="typescript-index";function od(e){let t=ir(e,zy);return{rootDir:t,requestDir:ir(t,"requests"),responseDir:ir(t,"responses")}}function sd(e){try{let t=JSON.parse(Uy(ir(Jy(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Gy("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}import{randomUUID as Ky}from"crypto";import{existsSync as Qy,mkdirSync as ad,readFileSync as Yy,rmSync as cd}from"fs";import{resolve as ld}from"path";var Xy=12e4,Zy=5,sr=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=es(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??ib(),this.runtime=n.runtime??ob}request(t){let n=Pn(this.cacheDir),r=od(this.cacheDir),i=qr(n.statePath);if(!dd(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),s=ld(r.requestDir,`${o}.json`),a=ld(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;ad(r.requestDir,{recursive:!0}),ad(r.responseDir,{recursive:!0}),St(s,{protocolVersion:or,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Qy(a))return eb(Yy(a,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=qr(n.statePath);if(!dd(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Zy)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{cd(s,{force:!0}),cd(a,{force:!0})}}};function dd(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Qo,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===or&&n.isProcessAlive(e.pid)&&(r||i)}function eb(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==or||o.id!==t||o.ok===!0&&o.baseGeneration!==n)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0)throw new Error(typeof o.error=="string"?o.error:"TypeScript index service request failed.");let s=tb(o.response,r),a=[...new Set(i)].sort(),c=s.fragments.map(l=>l.relativePath).sort();if(JSON.stringify(c)!==JSON.stringify(a))throw new Error("TypeScript index service omitted or added an affected document.");return s}function tb(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(nb)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:rb(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 nb(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 rb(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function ib(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Xy}var ob={now:Date.now,randomId:Ky,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:bt};function lb(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=wn(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"||!Ht(l.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=tr(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=db([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=ud(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=ud(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=md(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=md(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:pd(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:pd(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 db(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 gd(e){let t=Date.now();try{if(!Ti(e.previousDbPath)||!Ti(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Pi();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new Oe({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),s,a;try{s=gn(o,{includeIgnored:!1}).filter(Ht).sort(),a=bn(o)}finally{o.close()}let c=performance.now()-n,l=lb({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?en(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:a,producerIdentity:r.producerIdentity,rootTsconfigExists:Ti(cb(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let d=sd(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let m=new sr({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}),f=performance.now()-n,g=ab(e.previousShardPath).size>=Ga;n=performance.now();let h=g?null:fd(e.previousShardPath),y=g?{completeIndexBytes:null,affectedIndexBytes:Ba(m.fragments)}:Wa({packageVersion:r.packageVersion,baseIndexBytes:h,fragments:m.fragments}),S=performance.now()-n;n=performance.now(),g?Ua({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:m.fragments}):(Va({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:h,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),Ha({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.nextFragmentGeneration,fragments:m.fragments,documentIdentities:l.nextDocumentIdentities}));let x=performance.now()-n;n=performance.now(),y.completeIndexBytes&&Ii(e.candidateShardPath,y.completeIndexBytes),Ii(e.candidateAffectedScipPath,y.affectedIndexBytes);let w=performance.now()-n,R={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-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:f,serviceMs:m.durationMs,assemblyMs:S,fragmentStoreMs:x,writeMs:w}};return e.onStatus(`Incremental TypeScript index emitted ${R.affectedFiles.length} affected document(s) in ${(R.durationMs/1e3).toFixed(3)}s (${R.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${S.toFixed(0)}ms, fragments ${x.toFixed(0)}ms, write ${w.toFixed(0)}ms).`),R}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 hd(e){let t=Pi();if(!t.available)throw new Error(t.reason);let n=Ja({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:fd(e.baseShardPath),packageVersion:t.packageVersion});Ii(e.candidateShardPath,n)}function ud(e,t,n){let r=e.files.filter(i=>Uo(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 ji(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function pd(e,t){return ji(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function md(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),s=ss({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,ji(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function ji(e){return sb("sha256").update(e).digest("hex")}import{execFile as ub}from"child_process";import{existsSync as ar,renameSync as Li,rmSync as Ai,statSync as pb}from"fs";import{cpus as mb}from"os";import{join as yd}from"path";function fb(e,t,n){if(!e.defaultOutputPath)return;let r=yd(t,e.defaultOutputPath);n!==r&&ar(r)&&Li(r,n)}function gb(e,t,n){if(!e.defaultOutputPath)return null;let r=yd(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Ai(i,{force:!0}),ar(r)?(Li(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function hb(e){e&&(Ai(e.defaultOutputPath,{force:!0}),e.backupPath&&ar(e.backupPath)&&Li(e.backupPath,e.defaultOutputPath))}function yb(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,mb().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function bd(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=yb(o.length,r),c=await Sb(o,a,l=>Ei(l,t,n));if(a>1){let l=new Map;for(let d of c.filter(p=>p.skipped)){let p=o.find(m=>m.id===d.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),l.set(p.id,await Ei(p,t,n)))}s.push(...c.map(d=>l.get(d.id)??d))}else s.push(...c);for(let l of i)s.push(await Ei(l,t,n));return s.sort((l,d)=>e.findIndex(p=>p.id===l.id)-e.findIndex(p=>p.id===d.id))}async function Ei(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Ai(e.scipPath,{force:!0});let r=gb(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{let a=Bo(e.binary,e.args);await bb(a.binary,a.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),fb(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
277
+ `)[0]}`,d=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:d}}}finally{hb(r)}if(!ar(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}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:c}}}let s;try{s=pb(e.scipPath).size}catch{s=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,outputBytes:s}}function bb(e,t,n){return new Promise((r,i)=>{ub(e,[...t],n,o=>{o?i(o):r()})})}async function Sb(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 vb}from"child_process";import{platform as xb}from"os";function cr(e,t){let n=e.installMethods,r=xn(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(Ue(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{vb(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:xb()==="win32"});let o=Rn(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 nS from"better-sqlite3";import{existsSync as rS}from"fs";import{dirname as iS,join as oS,resolve as sS}from"path";import{readFileSync as kb,rmSync as wb,statSync as $b,mkdtempSync as Cb}from"fs";import{tmpdir as Pb}from"os";import{join as Di}from"path";import{Worker as Tb}from"worker_threads";function Rb(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Et(){return{skippedReferences:0,skippedReferenceReasons:Rb(),skippedReferenceSamples:[]}}function lr(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)}}function Sd(e){return e.length>=8&&xd(e.length)>1}function vd(e){let t=xd(e.vueFiles.length),n=jb(e.vueFiles),r=Lb(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=Cb(Di(Pb(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=Ib(),l=Date.now();try{for(let m=0;m<r.length;m++)new Tb(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:Di(o,`${m}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<r.length;){if(Date.now()-l>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let d=r.map((m,f)=>{let g=JSON.parse(kb(Di(o,`${f}.json`),"utf-8"));if(!g.ok)throw new Error(`Vue reference worker failed: ${g.error}`);return g.result}),p={occurrences:d.flatMap(m=>m.occurrences),...Et()};for(let m of d)lr(p,m);return p}finally{wb(o,{recursive:!0,force:!0})}}function xd(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 Ib(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function jb(e){let t=Eb(),n=[];for(let r of e){let i=Rd(r),o=Math.max(1,Math.ceil(i/t));for(let s=0;s<o;s++)n.push({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 Eb(){return Number.POSITIVE_INFINITY}function Lb(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Ab(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 Ab(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Rd(e.fileName)-e.startOffset)}function Rd(e){try{return $b(e).size}catch{return 1}}import{createRequire as Db}from"module";import{existsSync as Ob,readFileSync as Fi}from"fs";import{dirname as kd,extname as Fb,join as wd,relative as Nb,resolve as Mb}from"path";import{pathToFileURL as _b}from"url";function qb(e){e.transaction(()=>{e.prepare(`
278
278
  DELETE FROM mentions
279
279
  WHERE chunk_id IN (
280
280
  SELECT c.id
@@ -289,12 +289,12 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
289
289
  FROM documents
290
290
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
291
291
  )
292
- `).run()})()}function kd(e,t){return e.prepare(`
292
+ `).run()})()}function $d(e,t){return e.prepare(`
293
293
  SELECT relative_path AS relativePath
294
294
  FROM documents
295
295
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
296
296
  ORDER BY relative_path
297
- `).all().map(r=>Ib(t,r.relativePath))}function wd(e,t){let{vueCore:n,ts:r,volarTs:i}=Lb(e),{parsed:o,vueOptions:s}=Ab(n,r,t),a=xd(t),c=n.createVueLanguagePlugin(r,o.options,s,f=>f),l=Db(n,r,c),d=Ob(a,o),{languageServiceHost:u}=i.createLanguageServiceHost(r,r.sys,l,f=>f,d),m=r.createLanguageService(u);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function Lb(e){let t=$b(Eb(Rd(e,"package.json")).href);return{vueCore:Li(t,"@vue/language-core",e),ts:Li(t,"typescript",e),volarTs:Li(t,"@volar/typescript",e)}}function Ab(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,xd(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Db(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Pb(o))return;let s=Ai(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??Bb(o))});return r.current=i,i}function Ob(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Li(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 $d(e,t,n){let r=Nb(e);return i=>{if(!i.name)return null;let o=Ve(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:Fb(c.starts,a.line,2,i.name)}}function Nb(e){let t=e.prepare(`
297
+ `).all().map(r=>Mb(t,r.relativePath))}function Cd(e,t){let{vueCore:n,ts:r,volarTs:i}=Bb(e),{parsed:o,vueOptions:s}=Vb(n,r,t),a=kd(t),c=n.createVueLanguagePlugin(r,o.options,s,f=>f),l=Hb(n,r,c),d=Wb(a,o),{languageServiceHost:p}=i.createLanguageServiceHost(r,r.sys,l,f=>f,d),m=r.createLanguageService(p);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function Bb(e){let t=Db(_b(wd(e,"package.json")).href);return{vueCore:Oi(t,"@vue/language-core",e),ts:Oi(t,"typescript",e),volarTs:Oi(t,"@volar/typescript",e)}}function Vb(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,kd(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Hb(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Ob(o))return;let s=Fi(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??Qb(o))});return r.current=i,i}function Wb(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Oi(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 Pd(e,t,n){let r=Gb(e);return i=>{if(!i.name)return null;let o=Ve(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(p=>p.line===a.line&&p.displayName===i.name);if(l)return l.symbolId;let d=c.containingByLine.get(a.line);return d&&d.displayName===i.name?d.symbolId:Ub(c.starts,a.line,2,i.name)}}function Gb(e){let t=e.prepare(`
298
298
  SELECT
299
299
  d.relative_path AS relativePath,
300
300
  der.start_line AS startLine,
@@ -305,22 +305,22 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
305
305
  JOIN documents d ON d.id = der.document_id
306
306
  JOIN global_symbols gs ON gs.id = der.symbol_id
307
307
  ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
308
- `).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 Fb(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 Pd(e,t,n){let r=Wb(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
308
+ `).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 Ub(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 Td(e,t,n){let r=Zb(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
309
309
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
310
310
  VALUES (?, ?, ?, ?)
311
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=Ve(t,l),u=Od(r.name,r.version,d);o.run(u,"default",7,`Vue component|${d}`);let m=Gb(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Cd(e,t,n,r,i){return e.transaction(()=>(jb(e),Mb(e,t,n,r),_b(e,i)))()}function Mb(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
311
+ `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=Ve(t,l),p=Nd(r.name,r.version,d);o.run(p,"default",7,`Vue component|${d}`);let m=eS(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Id(e,t,n,r,i){return e.transaction(()=>(qb(e),Jb(e,t,n,r),zb(e,i)))()}function Jb(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
312
312
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
313
313
  VALUES (?, ?, ?, ?, X'00')
314
314
  `),s=e.prepare(`
315
315
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
316
316
  VALUES (?, ?, 1)
317
- `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Ve(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 Td(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(Di(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Id(e){let t=new Set,n=[];for(let r of e){let i=Ed(r);t.has(i)||(t.add(i),n.push(r))}return n}function Ed(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function _b(e,t){let n=Hb(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
317
+ `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Ve(t,a),d=i.get(l);if(!d)continue;let p=o.run(d.id,-1,0,0);s.run(Number(p.lastInsertRowid),c)}}function jd(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(Ni(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Ed(e){let t=new Set,n=[];for(let r of e){let i=Ld(r);t.has(i)||(t.add(i),n.push(r))}return n}function Ld(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function zb(e,t){let n=Xb(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
318
318
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
319
319
  VALUES (?, ?, ?, ?, X'00')
320
320
  `),i=e.prepare(`
321
321
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
322
322
  VALUES (?, ?, 0)
323
- `),o=new Set,s=0,a=0;for(let c of t){let l=Ed(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*jd(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 Ld(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Di(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function qb(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 Ad(e,t){return Ve(e,t).startsWith("node_modules/")}function Ve(e,t){return Tb(e,t).replaceAll("\\","/")}function Bb(e){switch(Cb(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 Dd(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Ai(t,"utf-8"),r={text:n,lineStarts:Vb(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:qb}}function Vb(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Hb(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 Wb(e){try{let t=JSON.parse(Ai(Rd(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 Gb(e,t,n,r){let i=Ve(n,r),o=Od(t.name,t.version,i);return e.get(o)?.id??null}function Od(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Fd(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Xb({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Fi(e){return dt(lt(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),dt(Fd({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function Xb(e){let t=Yb(e.projectRoot,e.tsconfig);if(!zb(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Jb(e.dbPath);try{let r=kd(n,e.projectRoot),i=Qb(Kb(e.dbPath),"augment-vue-meta.json");return Bl({cachePath:i,readFingerprint:()=>tS(n,e.projectRoot,e.tsconfig),compute:()=>Zb({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()}}function Zb(e){let t=Pd(e.db,e.projectRoot,e.vueFiles),n=eS(e,t),r=Id(n.occurrences),i=Cd(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:dS(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:lS(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function eS(e,t){if(yd(e.vueFiles))return bd({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=nS({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return rS({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function tS(e,t,n){let r=e.prepare(`
323
+ `),o=new Set,s=0,a=0;for(let c of t){let l=Ld(c);if(o.has(l))continue;o.add(l);let d=n.get(c.sourceFile);if(!d)continue;let p=r.run(d,a++,c.sourceLine,c.sourceLine),m=i.run(Number(p.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*Ad(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 Dd(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Ni(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Kb(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 Od(e,t){return Ve(e,t).startsWith("node_modules/")}function Ve(e,t){return Nb(e,t).replaceAll("\\","/")}function Qb(e){switch(Fb(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 Fd(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Fi(t,"utf-8"),r={text:n,lineStarts:Yb(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Kb}}function Yb(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Xb(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 Zb(e){try{let t=JSON.parse(Fi(wd(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 eS(e,t,n,r){let i=Ve(n,r),o=Nd(t.name,t.version,i);return e.get(o)?.id??null}function Nd(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function _d(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>aS({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function qi(e){return pt(ut(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),pt(_d({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function aS(e){let t=sS(e.projectRoot,e.tsconfig);if(!rS(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new nS(e.dbPath);try{let r=$d(n,e.projectRoot),i=oS(iS(e.dbPath),"augment-vue-meta.json");return Hl({cachePath:i,readFingerprint:()=>dS(n,e.projectRoot,e.tsconfig),compute:()=>cS({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()}}function cS(e){let t=Td(e.db,e.projectRoot,e.vueFiles),n=lS(e,t),r=Ed(n.occurrences),i=Id(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:SS(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:bS(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function lS(e,t){if(Sd(e.vueFiles))return vd({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=uS({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return pS({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function dS(e,t,n){let r=e.prepare(`
324
324
  SELECT
325
325
  (SELECT COUNT(*) FROM documents) AS documents,
326
326
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -329,22 +329,22 @@ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
329
329
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
330
330
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
331
331
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
332
- `).get();return{version:3,tsconfig:n,files:vn(t),db:r}}function nS(e){let t=Dd();return{projectRoot:e.projectRoot,context:wd(e.projectRoot,e.configPath),symbolLookup:$d(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function rS(e){let t=[],n=It(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=iS(e,i);t.push(...o.occurrences),or(n,o)}return{occurrences:t,...n}}function iS(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Nd(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 Nd(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=Ve(e.projectRoot,t.fileName),a=[...jd(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:pS(a),processedStarts:new Set};return oS({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function oS(e){let t=[],n=It();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||sS(e.sourceInfo.text,r.start))continue;let i=Ld(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!Ad(e.projectRoot,d.fileName));if(!s){Oi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=Ve(e.projectRoot,s.fileName),c=aS(e.sourceFile,r.text,a);if(c){Oi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=Td(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){Oi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}Md(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),uS(t,e,r,i,a,l)}return{occurrences:t,...n}}function sS(e,t){let n=e.lastIndexOf(`
333
- `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function aS(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Nd(e,t,n){let r=It();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:Ve(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Oi(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 Ni(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 cS(e,t){let n=Ni(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=Ni(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function lS(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(...Ni(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function dS(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return cS(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function uS(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of mS(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&&(Md(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function Md(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 pS(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function mS(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=fS(r,l.textSpan.start,o,i.text);d!==null&&a.push(d)}return a}function fS(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Di(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Et(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=PS(e),s=Date.now();ar(V(o.outputScip),{recursive:!0}),ar(V(o.outputDb),{recursive:!0});let a=e.languages??tt(t);if(a.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: ${a.join(", ")}`);let c=Nt("reindex.fingerprint",()=>ov(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:a.length}),l,d;if(e.skipIfUnchanged!==!1&&!ec(t,o.outputDb)&&_d(o.outputScip)===_d(ne(V(o.outputDb),"index.scip"))){let g=Rn(t);if(l=g?En(g,c):void 0,l){let h=jn(l);if(h){if(!$S(o,c))try{Vr({snapshot:l,manifest:h,targetCacheDir:V(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${l.generationId.slice(0,12)}`)}catch(y){r(`Shared generation attach failed; continuing locally: ${_i(y)}`)}}else{let y=await rc(l);if(y.kind==="owner")d=y.release;else if(y.kind==="generation-ready"){let S=jn(l);if(S)try{Vr({snapshot:l,manifest:S,targetCacheDir:V(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${l.generationId.slice(0,12)} after waiting`)}catch(x){r(`Shared generation attach failed after waiting; continuing locally: ${_i(x)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let u=Va(ne(V(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!u)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${V(o.outputDb)}.`);let m;try{m=await Ft("reindex.lock",()=>XS(ne(V(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:a.length})}catch(g){throw u.release(),d?.(),g}let f=null;try{let g=null,h=Nt("reindex.reuse-check",()=>(g=CS({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r}),g),()=>({languages:a.length,reused:g!==null}));if(h)return qd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),h;await Ft("reindex.scip-cli-ready",()=>WS(i,r));let y=IS(o);f=y.runDir;let S,x=await Ft("reindex.fresh",async()=>(S=await ES({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:y,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),S),()=>({languages:a.length,reused:S?.reused,skipped:S?.skipped.length}));return qd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),x}catch(g){throw nu(o.metaPath,ur({trigger:e.trigger,result:"failed",start:s,error:g instanceof Error?g.message:String(g)})),g}finally{f&&Ye(f,{recursive:!0,force:!0}),m(),u.release(),d?.()}}function qd(e){if(e.snapshot){if(jn(e.snapshot)){Hr(e.snapshot,V(e.paths.outputDb),"local-fresh");return}try{let t=Rn(e.projectRoot),n=t?En(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}nc({snapshot:e.snapshot,sourceCacheDir:V(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=Rn(e.projectRoot);return(r?En(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Hr(e.snapshot,V(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: ${_i(t)}`)}}}function $S(e,t){if(!Re(e.outputScip)||!Re(e.outputDb)||!tu(e.metaPath,t))return!1;let n=nt(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function _i(e){return e instanceof Error?e.message:String(e)}function PS(e){let t=e.outputScip??ne(e.projectRoot,"index.scip"),n=e.outputDb??ne(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:ne(V(n),"meta.json")}}function CS(e){let t=nt(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!Re(e.paths.outputScip)||!Re(e.paths.outputDb)||!tu(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;dt(lt(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=ur({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return nu(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:TS(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function TS(e,t,n,r){let i=Zd(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:Xt(i[o]),outputBytes:Zt(Bi(e.outputDb,o)),durationMs:0}))}function IS(e){let t=bS(ne(V(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:ne(t,sr(e.outputScip)),tempOutputDb:ne(t,sr(e.outputDb)),tempMetaPath:ne(t,sr(e.metaPath))}}async function ES(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await Ft("reindex.language-indexers",async()=>(n=await LS(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(", ")}`),jS({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let f=Nt("reindex.publish",()=>BS(e,i,o,s,a,l),{mode:"metadata-only",languages:i.length,reused:s.length}),g=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(h=>h.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:f,shards:c}}let u=Nt("reindex.publish",()=>qS(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(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:u,shards:c}}function jS(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!Re(e.run.paths.outputScip)||!Re(e.run.paths.outputDb))return!1;let t=nt(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 LS(e,t){let n=FS({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[O,Z]of n)Z.reused&&(r.push({language:O,scipPath:Z.scipPath}),i.add(O));for(let O of i)e.onStatus(`Reusing cached ${O} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),s=nt(e.paths.outputDb,e.paths.metaPath),a=tn(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?md({projectRoot:e.projectRoot,cacheDir:V(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:en(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:en(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:qi(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,u=new Set(d?["typescript"]:[]),m=d?void 0:AS(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:h}=GS({languages:e.languages.filter(O=>!i.has(O)&&!u.has(O)),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}),y=m?f.filter(O=>O.language!=="typescript"||m.missedProjectIds.has(O.id)):f,S=await hd(y,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),x=[];if(m){OS(e.paths.outputDb,S);let O=h.typescript??e.tempPaths.tempOutputScip;x=NS({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:O,reusedProjects:m.reusedProjects})}let k=[...S,...x],{indexedOutputs:R}=JS(k,g),D=d?[{language:"typescript",scipPath:d.scipPath}]:[],_=[...r,...D,...R];zS(_,g,e.languages,e.opts.allowPartial,e.onStatus);let z=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:Zt(d.scipPath)??void 0}]:[],T=MS(n,[...S,...z],m?{outputDb:e.paths.outputDb,classification:m.classification}:void 0);return{indexedOutputs:_,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:_S(n,e.languages),shards:T,typescriptProjectShardContext:m?{projects:m.allProjects,fingerprints:m.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function AS(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=Yt(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Ul(e.projectRoot,r),o=Hl(n.fingerprint.files,r),s=Wl(r,i),a=Gl(r,o,s),c=tn(e.paths.metaPath),d=DS(c,a,g=>Re(dr(e.paths.outputDb,g))),u=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),m=new Set(u),f=new Set(r.filter(g=>!m.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:a,classification:d,reusedProjects:u,missedProjectIds:f}}function DS(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.typescriptProjectShards?.[i];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(He(s)!==He(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 OS(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=dr(e,r);ar(V(i),{recursive:!0}),cr(n.scipPath,i)}}function NS(e){return e.reusedProjects.map((t,n)=>{let r=dr(e.outputDb,t),i=en(e.tempOutputScip,"typescript-project-cached",n);return cr(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Zt(i)??void 0}})}function FS(e){let t=tn(e.paths.metaPath),n=Zd(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Bi(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!==3){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(!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(!Re(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}if(He(a)!==He(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 MS(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:Xt(o.fingerprint),outputBytes:Zt(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?Xt(a.fingerprint):o?Xt(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:Xt(o.fingerprint),outputBytes:Zt(dr(n.outputDb,i)),durationMs:0});return r}function Xt(e){return hS("sha256").update(He(e)).digest("hex").slice(0,16)}function Zt(e){try{return xS(e).size}catch{return null}}function _S(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function qS(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(Bd(e.paths.outputDb,n),l=Vd(n,e.tempPaths.tempOutputScip,e.onStatus));let d=KS({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..."),fd({cacheDir:V(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let x=n.map(k=>k.language==="typescript"?{language:k.language,scipPath:a.candidateScipPath}:k);return Bd(e.paths.outputDb,x),l=Vd(x,e.tempPaths.tempOutputScip,e.onStatus),l}});if(dt(lt(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&a){let x=null,k=null;try{x=new Ae({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),k=new Ae({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let R=cs(x,e.fingerprint,a.referenceFragmentsByFile,k);e.onStatus(`Cached exact TypeScript reference fragments for ${R} affected document(s).`)}catch(R){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${R instanceof Error?R.message:String(R)}.`)}finally{x?.close(),k?.close()}}let u=qi(e.paths.metaPath),m=d.mode==="incremental"&&a?YS(a,d.changedDocumentPaths):hi({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"}),f=ur({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(x=>x.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",h={...o};g&&delete h.typescript;let{metadata:y,pruneProjects:S}=zd({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:h,typescriptProjectShardContext:s,lastRefresh:f});return y.scipCompanion=g?"deferred":"current",Kd(e.paths.outputDb,S),Vi(e.tempPaths.tempMetaPath,y),qa({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}:{}}}),Qa(V(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),Jd(e.paths.outputDb,m,e.onStatus),f}function BS(e,t,n,r,i,o){let s=qi(e.paths.metaPath),a=null;try{cr(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(u){a=Tl("reused","oracle-error",`Could not snapshot the prior database: ${u instanceof Error?u.message:String(u)}`)}dt(lt(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),a??=hi({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=ur({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(u=>u.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=zd({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Kd(e.paths.outputDb,d),Vi(e.paths.metaPath,l),Ba(e.paths.outputDb,e.paths.metaPath),Jd(e.paths.outputDb,a,e.onStatus),c}function qi(e){return os(tn(e)?.fingerprint)}function Jd(e,t,n){try{Ll(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 zd(e){let t=VS({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:3,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 VS(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=tn(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Kd(e,t){let n=eu(e);if(t===null){Ye(n,{recursive:!0,force:!0});return}let r;try{r=vS(n)}catch{return}for(let i of HS(r,t))Ye(ne(n,i),{force:!0})}function HS(e,t){let n=new Set(t.map(r=>`${Ri(r)}.scip`));return e.filter(r=>!n.has(r))}function Bd(e,t){for(let n of t){let r=Bi(e,n.language);ar(V(r),{recursive:!0}),n.scipPath!==r&&cr(n.scipPath,r)}}async function WS(e,t){if(!Un()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
334
- Install from: https://github.com/sourcegraph/scip/releases`);if(wS()==="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..."),!hl(t))throw new Error(`The scip CLI is required but could not be installed.
335
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function GS(e){let t=[],n=[],r=e.languages.map((o,s)=>({language:o,scipPath:e.languages.length>1?en(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=US({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?Qd(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function US(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Mi({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??Yt(e.projectRoot,e.typescriptProjects);return t.length===0?[Mi({...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)=>Mi({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:en(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Mi(e){let t=et(e.language),n=No(t),r=_o(t,e.projectRoot);if(!r&&!Mo(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...`),!Sn(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??Fo(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:qo(t,e.env,i)}}}function JS(e,t){let n=new Map;for(let i of e)if(i.skipped)Qd(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)Xa(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&Ud(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Qd(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 zS(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
332
+ `).get();return{version:3,tsconfig:n,files:$n(t),db:r}}function uS(e){let t=Fd();return{projectRoot:e.projectRoot,context:Cd(e.projectRoot,e.configPath),symbolLookup:Pd(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function pS(e){let t=[],n=Et(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=mS(e,i);t.push(...o.occurrences),lr(n,o)}return{occurrences:t,...n}}function mS(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Md(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 Md(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=Ve(e.projectRoot,t.fileName),a=[...Ad(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:xS(a),processedStarts:new Set};return fS({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function fS(e){let t=[],n=Et();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||gS(e.sourceInfo.text,r.start))continue;let i=Dd(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!Od(e.projectRoot,d.fileName));if(!s){Mi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=Ve(e.projectRoot,s.fileName),c=hS(e.sourceFile,r.text,a);if(c){Mi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=jd(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){Mi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}qd(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),vS(t,e,r,i,a,l)}return{occurrences:t,...n}}function gS(e,t){let n=e.lastIndexOf(`
333
+ `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function hS(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Md(e,t,n){let r=Et();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:Ve(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Mi(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 _i(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 yS(e,t){let n=_i(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=_i(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function bS(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(..._i(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function SS(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return yS(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function vS(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of RS(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&&(qd(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function qd(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 xS(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function RS(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=kS(r,l.textSpan.start,o,i.text);d!==null&&a.push(d)}return a}function kS(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Ni(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Lt(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=OS(e),s=Date.now();ur(V(o.outputScip),{recursive:!0}),ur(V(o.outputDb),{recursive:!0});let a=e.languages??rt(t);if(a.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: ${a.join(", ")}`);let c=Mt("reindex.fingerprint",()=>Ko(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:a.length}),l,d;if(e.skipIfUnchanged!==!1&&!Xa(t,o.outputDb)&&Bd(o.outputScip)===Bd(ne(V(o.outputDb),"index.scip"))){let g=nt(t);if(l=g?En(g,c):void 0,l){let h=Ln(l);if(h){if(!DS(o,c))try{Hr({snapshot:l,manifest:h,targetCacheDir:V(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${l.generationId.slice(0,12)}`)}catch(y){r(`Shared generation attach failed; continuing locally: ${Vi(y)}`)}}else{let y=await tc(l);if(y.kind==="owner")d=y.release;else if(y.kind==="generation-ready"){let S=Ln(l);if(S)try{Hr({snapshot:l,manifest:S,targetCacheDir:V(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${l.generationId.slice(0,12)} after waiting`)}catch(x){r(`Shared generation attach failed after waiting; continuing locally: ${Vi(x)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=qa(ne(V(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${V(o.outputDb)}.`);let m;try{m=await _t("reindex.lock",()=>av(ne(V(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:a.length})}catch(g){throw p.release(),d?.(),g}let f=null;try{let g=null,h=Mt("reindex.reuse-check",()=>(g=FS({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r}),g),()=>({languages:a.length,reused:g!==null}));if(h)return Vd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),h;await _t("reindex.scip-cli-ready",()=>ZS(i,r));let y=MS(o);f=y.runDir;let S,x=await _t("reindex.fresh",async()=>(S=await _S({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:y,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),S),()=>({languages:a.length,reused:S?.reused,skipped:S?.skipped.length}));return Vd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),x}catch(g){throw iu(o.metaPath,gr({trigger:e.trigger,result:"failed",start:s,error:g instanceof Error?g.message:String(g)})),g}finally{f&&Ze(f,{recursive:!0,force:!0}),m(),p.release(),d?.()}}function Vd(e){if(e.snapshot){if(Ln(e.snapshot)){Wr(e.snapshot,V(e.paths.outputDb),"local-fresh");return}try{let t=nt(e.projectRoot),n=t?En(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}ec({snapshot:e.snapshot,sourceCacheDir:V(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=nt(e.projectRoot);return(r?En(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Wr(e.snapshot,V(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: ${Vi(t)}`)}}}function DS(e,t){if(!Re(e.outputScip)||!Re(e.outputDb)||!ru(e.metaPath,t))return!1;let n=it(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Vi(e){return e instanceof Error?e.message:String(e)}function OS(e){let t=e.outputScip??ne(e.projectRoot,"index.scip"),n=e.outputDb??ne(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:ne(V(n),"meta.json")}}function FS(e){let t=it(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!Re(e.paths.outputScip)||!Re(e.paths.outputDb)||!ru(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;pt(ut(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=gr({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return iu(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:NS(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function NS(e,t,n,r){let i=tu(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:tn(i[o]),outputBytes:nn(Wi(e.outputDb,o)),durationMs:0}))}function MS(e){let t=PS(ne(V(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:ne(t,dr(e.outputScip)),tempOutputDb:ne(t,dr(e.outputDb)),tempMetaPath:ne(t,dr(e.metaPath))}}async function _S(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await _t("reindex.language-indexers",async()=>(n=await BS(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(", ")}`),qS({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let f=Mt("reindex.publish",()=>QS(e,i,o,s,a,l),{mode:"metadata-only",languages:i.length,reused:s.length}),g=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(h=>h.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:f,shards:c}}let p=Mt("reindex.publish",()=>KS(e,t,i,o,s,a,l,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:s.length,skipped:o.length}),m=p.durationMs;return e.onStatus(`Done in ${(m/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:p,shards:c}}function qS(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!Re(e.run.paths.outputScip)||!Re(e.run.paths.outputDb))return!1;let t=it(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 BS(e,t){let n=US({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[O,Z]of n)Z.reused&&(r.push({language:O,scipPath:Z.scipPath}),i.add(O));for(let O of i)e.onStatus(`Reusing cached ${O} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),s=it(e.paths.outputDb,e.paths.metaPath),a=on(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?gd({projectRoot:e.projectRoot,cacheDir:V(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:rn(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:rn(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:Hi(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),m=d?void 0:VS(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:h}=ev({languages:e.languages.filter(O=>!i.has(O)&&!p.has(O)),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}),y=m?f.filter(O=>O.language!=="typescript"||m.missedProjectIds.has(O.id)):f,S=await bd(y,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),x=[];if(m){WS(e.paths.outputDb,S);let O=h.typescript??e.tempPaths.tempOutputScip;x=GS({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:O,reusedProjects:m.reusedProjects})}let w=[...S,...x],{indexedOutputs:R}=nv(w,g),D=d?[{language:"typescript",scipPath:d.scipPath}]:[],_=[...r,...D,...R];rv(_,g,e.languages,e.opts.allowPartial,e.onStatus);let z=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:nn(d.scipPath)??void 0}]:[],T=JS(n,[...S,...z],m?{outputDb:e.paths.outputDb,classification:m.classification}:void 0);return{indexedOutputs:_,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:zS(n,e.languages),shards:T,typescriptProjectShardContext:m?{projects:m.allProjects,fingerprints:m.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function VS(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=en(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=zl(e.projectRoot,r),o=Gl(n.fingerprint.files,r),s=Ul(r,i),a=Jl(r,o,s),c=on(e.paths.metaPath),d=HS(c,a,g=>Re(fr(e.paths.outputDb,g))),p=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),m=new Set(p),f=new Set(r.filter(g=>!m.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:a,classification:d,reusedProjects:p,missedProjectIds:f}}function HS(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.typescriptProjectShards?.[i];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(He(s)!==He(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 WS(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=fr(e,r);ur(V(i),{recursive:!0}),pr(n.scipPath,i)}}function GS(e){return e.reusedProjects.map((t,n)=>{let r=fr(e.outputDb,t),i=rn(e.tempOutputScip,"typescript-project-cached",n);return pr(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:nn(i)??void 0}})}function US(e){let t=on(e.paths.metaPath),n=tu(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Wi(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!==3){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(!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(!Re(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}if(He(a)!==He(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 JS(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:tn(o.fingerprint),outputBytes:nn(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?tn(a.fingerprint):o?tn(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:tn(o.fingerprint),outputBytes:nn(fr(n.outputDb,i)),durationMs:0});return r}function tn(e){return $S("sha256").update(He(e)).digest("hex").slice(0,16)}function nn(e){try{return jS(e).size}catch{return null}}function zS(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function KS(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(Hd(e.paths.outputDb,n),l=Wd(n,e.tempPaths.tempOutputScip,e.onStatus));let d=iv({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..."),hd({cacheDir:V(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let x=n.map(w=>w.language==="typescript"?{language:w.language,scipPath:a.candidateScipPath}:w);return Hd(e.paths.outputDb,x),l=Wd(x,e.tempPaths.tempOutputScip,e.onStatus),l}});if(pt(ut(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&a){let x=null,w=null;try{x=new Oe({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),w=new Oe({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let R=as(x,e.fingerprint,a.referenceFragmentsByFile,w);e.onStatus(`Cached exact TypeScript reference fragments for ${R} affected document(s).`)}catch(R){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${R instanceof Error?R.message:String(R)}.`)}finally{x?.close(),w?.close()}}let p=Hi(e.paths.metaPath),m=d.mode==="incremental"&&a?sv(a,d.changedDocumentPaths):Si({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:p,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),f=gr({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(x=>x.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",h={...o};g&&delete h.typescript;let{metadata:y,pruneProjects:S}=Qd({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:h,typescriptProjectShardContext:s,lastRefresh:f});return y.scipCompanion=g?"deferred":"current",Yd(e.paths.outputDb,S),Gi(e.tempPaths.tempMetaPath,y),Ma({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}:{}}}),za(V(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),Kd(e.paths.outputDb,m,e.onStatus),f}function QS(e,t,n,r,i,o){let s=Hi(e.paths.metaPath),a=null;try{pr(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){a=jl("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}pt(ut(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),a??=Si({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=gr({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=Qd({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Yd(e.paths.outputDb,d),Gi(e.paths.metaPath,l),_a(e.paths.outputDb,e.paths.metaPath),Kd(e.paths.outputDb,a,e.onStatus),c}function Hi(e){return Jo(on(e)?.fingerprint)}function Kd(e,t,n){try{Dl(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 Qd(e){let t=YS({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:3,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 YS(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=on(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Yd(e,t){let n=nu(e);if(t===null){Ze(n,{recursive:!0,force:!0});return}let r;try{r=IS(n)}catch{return}for(let i of XS(r,t))Ze(ne(n,i),{force:!0})}function XS(e,t){let n=new Set(t.map(r=>`${$i(r)}.scip`));return e.filter(r=>!n.has(r))}function Hd(e,t){for(let n of t){let r=Wi(e,n.language);ur(V(r),{recursive:!0}),n.scipPath!==r&&pr(n.scipPath,r)}}async function ZS(e,t){if(!zn()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
334
+ Install from: https://github.com/sourcegraph/scip/releases`);if(AS()==="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..."),!yl(t))throw new Error(`The scip CLI is required but could not be installed.
335
+ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function ev(e){let t=[],n=[],r=e.languages.map((o,s)=>({language:o,scipPath:e.languages.length>1?rn(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=tv({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?Xd(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function tv(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Bi({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??en(e.projectRoot,e.typescriptProjects);return t.length===0?[Bi({...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)=>Bi({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:rn(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Bi(e){let t=st(e.language),n=xn(t),r=Ho(t,e.projectRoot);if(!r&&!Vo(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??Rn(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:Wo(t,e.env,i)}}}function nv(e,t){let n=new Map;for(let i of e)if(i.skipped)Xd(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)Qa(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&zd(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Xd(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 rv(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
336
336
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
337
337
  `+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.
338
338
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
339
- `))}function Vd(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Za(e.map(o=>o.scipPath),t);return Xd(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Ud(e[0].scipPath,t);return!1}function KS(e){let t;if(QS(e)){let i=ne(e.run.tempPaths.runDir,"typescript-affected.db");try{Yd(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Hd(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=Ml({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),Ye(i,{force:!0}),Ye(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 Hd(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function QS(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!Re(e.run.paths.outputDb)||!Re(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 YS(e,t){let n=Date.now(),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:Date.now()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:gi(e.plan,o,e.projectFileCount)}}function Hd(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!Re(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||Yd(e,r);let o=Un();if(!o)throw new Error("scip CLI is not available");gS(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}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 Yd(e,t){let n=Ya(e);Xd(n,t)}function Xd(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function en(e,t,n){let r=kS(e)||".scip",i=sr(e,r);return ne(V(e),`${i}.${n+1}.${t}${r}`)}async function XS(e,t){for(let n=0;n<2;n++){let r=ZS(e,t);if(r)return r;let i=ev(e);if(i&&tv(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await rv(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${V(e)}; refusing to steal an active lock.`);Ye(e,{force:!0});continue}if(i&&!ht(i.pid)){Ye(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${V(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${V(e)}.`)}function ZS(e,t){let n;try{n=SS(e,"wx")}catch(i){if((typeof i=="object"&&i&&"code"in i?i.code:void 0)==="EEXIST")return null;throw i}let r={version:1,pid:process.pid,projectRoot:t.projectRoot,startedAt:new Date().toISOString(),trigger:t.trigger};return RS(n,JSON.stringify(r)+`
340
- `),()=>{try{yS(n)}finally{Ye(e,{force:!0})}}}function ev(e){try{let t=JSON.parse(lr(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:{version:1,pid:t.pid,projectRoot:typeof t.projectRoot=="string"?t.projectRoot:V(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function tv(e,t){return e?.kind==="manual-cli"&&nv(t?.trigger)}function nv(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function rv(e){return Wd(e,"SIGTERM"),await Gd(e,2e3)?!0:(Wd(e,"SIGKILL"),Gd(e,1e3))}function Wd(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Gd(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!ht(e))return!0;await iv(50)}return!ht(e)}function iv(e){return new Promise(t=>setTimeout(t,e))}function ov(e,t,n){return Wo(e,t,n)}function Zd(e,t,n){return Object.fromEntries(t.map(r=>{let i=et(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Ho(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=r==="clojure"?sv(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&av(n),...o,clojureConfigPath:s,files:vn(e,{language:r,markerFiles:i})}]}))}function sv(e){return e?.trim()||void 0}function av(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Bi(e,t){return ne(V(e),"language-indexes",`${t}.scip`)}function eu(e){return ne(V(e),"language-indexes","typescript-projects")}function dr(e,t){return ne(eu(e),`${Ri(t)}.scip`)}function tn(e){try{return JSON.parse(lr(e,"utf-8"))}catch{return null}}function tu(e,t){try{let n=JSON.parse(lr(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&He(n.fingerprint)===He(t)&&He([...n.indexedLanguages??[]].sort())===He(t.languages)}catch{return!1}}function Vi(e,t){yt(e,t,{spacing:2,trailingNewline:!0})}function nu(e,t){try{let n=JSON.parse(lr(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Vi(e,{...n,lastRefresh:t})}catch{}}function ur(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-e.start,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function He(e){return JSON.stringify(e)}var Hi=864e5;function ru(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=cv(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,f=0,g=0,h=0,y=0,S=[];for(let k of d){f+=k.events.filter(_=>_.event==="reopened").length;let R=k.events[k.events.length-1],D=`${k.check}\0${k.findingId}`;if(R.event==="resolved"&&s.has(D))g+=1;else if(R.event==="resolved"){let _=Gt(k.events.slice(0,-1)),z=_?.comparisonBaseCommit??_?.commit,T=R.comparisonBaseCommit??R.commit;z&&(T===z||R.verifiedAgainstCommit===z)?(u+=1,S.push((R.ts-k.caughtAt)/Hi)):h+=1}else R.event==="suppressed"?m+=1:y+=1}let x=u+m;c.push({check:l,caught:d.length,fixed:u,suppressed:m,reopened:f,moved:g,unverified:h,open:y,precision:x>0?u/x:null,medianDaysToFix:S.length>0?lv(S):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,d)=>l.check.localeCompare(d.check))}}function cv(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 iu(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*Hi:Hi;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function lv(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{fork as dv}from"child_process";import{statSync as uv}from"fs";import{isAbsolute as pv,join as mv,relative as fv}from"path";import{watch as gv}from"chokidar";import hv from"ignore";var pr=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Pe(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.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=vt(t.projectRoot),this.extraIgnore=hv(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=gv(this.projectRoot,{ignoreInitial:!0,ignored:(n,r)=>this.isIgnoredWatchPath(n,r?.isDirectory()??!1)});t.on("all",(n,r)=>{this.stopped||this.handleFileChange(r)}),t.on("error",n=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`))}),this.fsWatchers.push(t)}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(t,n={}){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=ou(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}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")||this.scheduleReindex({kind:"watch-source",detail:n})}relativeWatchPath(t){let n=pv(t)?t:mv(this.projectRoot,t);return fv(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=ou(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=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-t;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=Date.now();this.setStatus({state:"indexing",startedAt:r}),this.runReindex(n).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=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(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(t){return new Promise((n,r)=>{let i=Date.now(),o=fe(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=De(this.projectRoot,s),c=s.indexer?.typescript,l=s.indexer?.clojure,d=dv(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:a.indexPath,SCIP_REINDEX_OUTPUT_DB:a.dbPath,SCIP_REINDEX_LANGUAGES:(s.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(s.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});d.on("exit",u=>{u===0?n(Date.now()-i):r(new Error(`Reindex worker exited with code ${u}`))}),d.on("error",r)})}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=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=Nr(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n=Uo(this.projectRoot,t),r={head:Nr(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let i=uv(n);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function ou(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}import{existsSync as Mv}from"fs";import{existsSync as au,mkdirSync as cu,readFileSync as lu,writeFileSync as du}from"fs";import{homedir as yv}from"os";import{dirname as uu,isAbsolute as bv,join as Wi,relative as su,resolve as Sv}from"path";function pu(e,t={}){let n=t.dossierDir?Sv(e.projectRoot,t.dossierDir):Wi(e.projectRoot,"docs","scip-query"),r={markdownPath:Wi(n,"health-dossier.md"),jsonPath:Wi(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=Tv({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return $v(r.markdownPath,vv(i),r),Pv(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function vv(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${Ui(e.health)}`,"","## Items That Need Attention","",...xv(e),"","## Blocked Or Unavailable Checks","",...Rv(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","",...kv(e),"","## JSON","",`Machine-readable report: \`${wv(e)}\``,""].join(`
341
- `)}`}function xv(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 Rv(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 kv(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 Ui(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function wv(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function $v(e,t,n){if(cu(uu(e),{recursive:!0}),(au(e)?lu(e,"utf-8"):null)===t){n.unchanged.push(e);return}du(e,t),n.written.push(e)}function Pv(e,t,n){cu(uu(e),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
342
- `,i=au(e)?lu(e,"utf-8"):null;if(i&&Cv(i,r)){n.unchanged.push(e);return}du(e,r),n.written.push(e)}function Cv(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 Tv(e,t){return Gi(e,t)}function Gi(e,t){return typeof e=="string"?Iv(e,t):Array.isArray(e)?e.map(n=>Gi(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Gi(r,t)])):e}function Iv(e,t){if(e===t)return".";if(!bv(e))return e;let n=su(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=su(yv(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as Ev}from"child_process";import{readFileSync as fu}from"fs";import{dirname as mu,join as jv,resolve as Lv}from"path";import{fileURLToPath as Av}from"url";var mr={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 Dv(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of mr[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function Ji(e){return[...new Set(e.filter(t=>mr[t]!==void 0))].sort()}function gu(e,t={}){let n=t.runtime??Fv,r=t.packageRoot??Ov(),i=Ji(e),o=i.filter(u=>n.probe(mr[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=Nv(r),c=Dv(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let d=i.filter(u=>n.probe(mr[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 Ov(){let e=mu(Av(import.meta.url));for(;;){let t=jv(e,"package.json");try{if(JSON.parse(fu(t,"utf8")).name==="scip-query")return e}catch{}let n=mu(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function Nv(e){return JSON.parse(fu(Lv(e,"package.json"),"utf8")).optionalDependencies??{}}var Fv={probe:e=>fn(e)==="ast",resetProbe:Co,install:(e,t)=>{let n=Ev(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"});return n.status===0?{ok:!0}:{ok:!1,error:(n.stderr||n.stdout||n.error?.message||"npm install failed").trim()}}};function bu(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 Su(e={}){let t=[],n=Fe(),{projectRoot:r,paths:i,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?Ma(r,n.config,e.languages):null,c=a?.config??n.config,l=xt(c,{projectRoot:r}),d=l.filter(j=>j.level==="error"),u=null,m=null;if(d.length===0&&c.watch?.enabled!==s)try{u=_a(r,c,s)}catch(j){m=jt(j)}let f=u?.config??c,g=Kt();F(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]}:{}}),F(t,{id:"scip-cli",label:"scip CLI",status:g?"ok":"warn",message:g?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let h=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:Qn({quiet:!0});F(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(j=>`Pruned ${j}`),...h.skipped.map(j=>`Skipped ${j}`)]});let y=u?xt(f,{projectRoot:r}):l,S=y.filter(j=>j.level==="error");F(t,{id:"config",label:"Project config",status:S.length>0?"failed":y.length>0?"warn":"ok",message:y.length===0?"Config OK.":`${y.length} diagnostic(s), ${S.length} error(s).`,details:y.map(j=>`${j.level.toUpperCase()} ${j.path}: ${j.message}`)});let x=he(r,f);F(t,{id:"readiness",label:"Indexer readiness",status:x.languages.length===0?"failed":x.indexers.some(j=>!j.runnable)?"warn":"ok",message:x.languages.length===0?"No supported project languages detected.":`Detected languages: ${x.languages.join(", ")}`,details:x.indexers.map(j=>`${j.runnable?"OK":j.installed?"WARN":"MISSING"} ${j.language}: ${j.binaryLabel}${j.note?` - ${j.note}`:""}`)});let k=e.installAstParsers===!1?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:gu(x.languages);F(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers===!1?"skipped":k.unavailable.length>0?"warn":"ok",message:e.installAstParsers===!1?"Skipped by setup choice.":k.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${k.availableAfter.length}/${k.supportedLanguages.length} selected language parser(s) available${k.installed.length>0?`; installed ${k.installed.join(", ")}`:""}.`,details:[...k.unavailable.length>0?[`Unavailable: ${k.unavailable.join(", ")}`]:[],...k.error?[k.error]:[]]});let R=e.installIndexers??!0,D=R?Kv(r,x,t):[];R||F(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped by guided setup choice."});let _=he(r,f),z=await _v({projectRoot:r,paths:i,config:f,readiness:_,configHasErrors:S.length>0,steps:t,onStatus:e.onStatus}),T=z.reindexResult,O=z.freshness,Z=Pe(f),N=qv({projectRoot:r,cacheDir:i.cacheDir,watchConfig:Z,readiness:_,configHasErrors:S.length>0,reindexResult:T,postReindexFreshness:O,steps:t}),H=he(r,f),dn=Je(H),wo=Oe(r,f,i);F(t,{id:"capabilities",label:"Capability matrix",status:tx(dn),message:nx(dn)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let $o=e.runHealth===!1?Xv(t):await Yv(i.dbPath,t),we=H.languages.includes("rust")?xn(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;F(t,{id:"rust-semantic-session",label:"Rust semantic session",status:we===null?"skipped":we.valid?"ok":"failed",message:we===null?"Skipped because Rust was not detected.":`${we.transport}/${we.state} selected from ${we.source}; ${we.fallback} fallback; opt out with ${we.optOut}.`});let ee=null;try{e.noHooks?F(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(ee=Tt(r),F(t,{id:"project-hooks",label:"Project agent hooks",status:ee.skipped.length>0?"warn":"ok",message:`${ee.installed.length} installed, ${ee.updated.length} updated, ${ee.unchanged.length} already configured, ${ee.removed.length} hook config(s) cleaned up, ${ee.skipped.length} skipped.`,details:[...ee.gitExcluded.map(j=>`Checkout-local Git exclude: ${j}`),...ee.removed.map(j=>`Removed ${j}`),...ee.skipped.map(j=>`Skipped ${j.target}: ${j.reason}`),...ee.warnings]}))}catch(j){F(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:jt(j)})}let be=null;try{e.noAgentGuidance?F(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(be=Fn(r,{gitHook:e.gitHook}),F(t,{id:"agent-guidance",label:"Project agent guidance",status:be.skipped.length>0?"warn":"ok",message:`${be.written.length} written, ${be.unchanged.length} already wired, ${be.skipped.length} skipped.`,details:be.skipped.map(j=>`Skipped ${j.target}: ${j.reason}`)}))}catch(j){F(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:jt(j)})}let un=Bv({reindexResult:T,readiness:H,capabilities:dn,freshness:wo,health:$o,hooksResult:ee,agentResult:be,watchConfig:Z,watchService:N,rustSemanticSession:we,steps:t});F(t,{id:"smoke-tests",label:"Setup smoke tests",status:Vv(un),message:Hv(un),details:un.map(j=>`${j.command}: ${j.status} - ${j.evidence}`)});let gf={repository:[...a?.changed?[a.configPath]:[],...u?.changed?[u.configPath]:[],...be?.written.filter(j=>!j.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...ee?.installed??[],...ee?.updated??[],...ee?.gitExcluded??[],...be?.written.filter(j=>j.startsWith(".git/hooks/"))??[]])],user:[...h.installed,...k.installed,...D.filter(j=>j.attempted).map(j=>`${j.binaryLabel} installer`)]},je={projectRoot:r,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:g,languages:H.languages,steps:t,skills:h,astParsers:k,initialReadiness:x,indexerRemediation:D,readiness:H,capabilities:dn,freshness:wo,reindex:T,automaticRefreshConfig:u,watchService:N,rustSemanticSession:we,health:$o,smokeTests:un,healthDossier:null,hooks:ee,setupAgent:be,changeScopes:gf,filesWritten:be?.written??[],verdict:Ki(t,H)};if(e.runHealth===!1)return F(t,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),je.verdict=Ki(t,H),je;let $e=pu(je,{dossierDir:e.dossierDir});return je.healthDossier=$e,je.changeScopes.repository.push(...$e.written),je.filesWritten=[...je.filesWritten,...$e.written],F(t,{id:"health-dossier",label:"Health dossier",status:$e.status==="failed"?"failed":"ok",message:$e.status==="failed"?$e.error:`${$e.written.length} written, ${$e.unchanged.length} unchanged.`,details:[$e.markdownPath,$e.jsonPath]}),je.verdict=Ki(t,H),je}async function _v(e){if(e.readiness.languages.length===0||e.configHasErrors)return F(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 Et({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=Oe(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.");F(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){F(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:jt(i),details:t})}return{reindexResult:n,freshness:r}}function qv(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 F(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=wn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:Ne,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 F(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 F(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:jt(n)}),null}}function vu(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${Ui(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:"),zi("Repository records (commit)",e.changeScopes.repository),zi("Checkout preferences (do not commit)",e.changeScopes.checkout),zi("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 zi(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function Bv(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:Wv(e.steps),evidence:Gv(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?Uv(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:hu(e.readiness,e.freshness),evidence:yu(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:hu(e.readiness,e.freshness),evidence:yu(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:Jv(e.capabilities),evidence:zv(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 Vv(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Hv(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 Wv(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Gv(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function Uv(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 hu(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function yu(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 Jv(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function zv(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 Kv(e,t,n){let r=[];if(t.languages.length===0)return F(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=et(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=Sn(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=Qv(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 F(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 F(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 Qv(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function Yv(e,t){if(!Mv(e)){let n="Skipped because no SQLite index database exists yet.";return F(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Qi(n)}try{let n=await An({full:!0,json:!0});return F(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),Zv(n)}catch(n){let r=jt(n);return F(t,{id:"health",label:"Health audit",status:"failed",message:r}),Qi(r)}}function Xv(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return F(e,{id:"health",label:"Health audit",status:"skipped",message:t}),Qi(t)}function Zv(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(ex),warnings:e.warnings??[]}}function ex(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-cleanup-audit to confirm this signal; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}}function Qi(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Ki(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 tx(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 nx(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 F(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function jt(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as rx}from"readline";function ix(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function ox(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 xu(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=ix(e);rx(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
339
+ `))}function Wd(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Ya(e.map(o=>o.scipPath),t);return eu(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&zd(e[0].scipPath,t);return!1}function iv(e){let t;if(ov(e)){let i=ne(e.run.tempPaths.runDir,"typescript-affected.db");try{Zd(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Gd(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=ql({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),Ze(i,{force:!0}),Ze(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 Gd(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function ov(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!Re(e.run.paths.outputDb)||!Re(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 sv(e,t){let n=Date.now(),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:Date.now()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:bi(e.plan,o,e.projectFileCount)}}function Gd(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!Re(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||Zd(e,r);let o=zn();if(!o)throw new Error("scip CLI is not available");wS(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}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 Zd(e,t){let n=Ka(e);eu(n,t)}function eu(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function rn(e,t,n){let r=LS(e)||".scip",i=dr(e,r);return ne(V(e),`${i}.${n+1}.${t}${r}`)}async function av(e,t){for(let n=0;n<2;n++){let r=cv(e,t);if(r)return r;let i=lv(e);if(i&&dv(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await pv(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${V(e)}; refusing to steal an active lock.`);Ze(e,{force:!0});continue}if(i&&!bt(i.pid)){Ze(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${V(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${V(e)}.`)}function cv(e,t){let n;try{n=TS(e,"wx")}catch(i){if((typeof i=="object"&&i&&"code"in i?i.code:void 0)==="EEXIST")return null;throw i}let r={version:1,pid:process.pid,projectRoot:t.projectRoot,startedAt:new Date().toISOString(),trigger:t.trigger};return ES(n,JSON.stringify(r)+`
340
+ `),()=>{try{CS(n)}finally{Ze(e,{force:!0})}}}function lv(e){try{let t=JSON.parse(mr(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:{version:1,pid:t.pid,projectRoot:typeof t.projectRoot=="string"?t.projectRoot:V(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function dv(e,t){return e?.kind==="manual-cli"&&uv(t?.trigger)}function uv(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function pv(e){return Ud(e,"SIGTERM"),await Jd(e,2e3)?!0:(Ud(e,"SIGKILL"),Jd(e,1e3))}function Ud(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Jd(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!bt(e))return!0;await mv(50)}return!bt(e)}function mv(e){return new Promise(t=>setTimeout(t,e))}function tu(e,t,n){return Object.fromEntries(t.map(r=>{let i=st(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:zo(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=r==="clojure"?fv(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&gv(n),...o,clojureConfigPath:s,files:$n(e,{language:r,markerFiles:i})}]}))}function fv(e){return e?.trim()||void 0}function gv(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Wi(e,t){return ne(V(e),"language-indexes",`${t}.scip`)}function nu(e){return ne(V(e),"language-indexes","typescript-projects")}function fr(e,t){return ne(nu(e),`${$i(t)}.scip`)}function on(e){try{return JSON.parse(mr(e,"utf-8"))}catch{return null}}function ru(e,t){try{let n=JSON.parse(mr(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&He(n.fingerprint)===He(t)&&He([...n.indexedLanguages??[]].sort())===He(t.languages)}catch{return!1}}function Gi(e,t){St(e,t,{spacing:2,trailingNewline:!0})}function iu(e,t){try{let n=JSON.parse(mr(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Gi(e,{...n,lastRefresh:t})}catch{}}function gr(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-e.start,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function He(e){return JSON.stringify(e)}var Ui=864e5;function ou(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}`,p=i.get(d);p||(p={check:l.check,findingId:l.findingId,caughtAt:l.ts,events:[]},i.set(d,p)),p.events.push(l)}let o=[...i.values()].filter(l=>t.sinceMs===void 0||l.caughtAt>=t.sinceMs),s=hv(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 p=0,m=0,f=0,g=0,h=0,y=0,S=[];for(let w of d){f+=w.events.filter(_=>_.event==="reopened").length;let R=w.events[w.events.length-1],D=`${w.check}\0${w.findingId}`;if(R.event==="resolved"&&s.has(D))g+=1;else if(R.event==="resolved"){let _=Gt(w.events.slice(0,-1)),z=_?.comparisonBaseCommit??_?.commit,T=R.comparisonBaseCommit??R.commit;z&&(T===z||R.verifiedAgainstCommit===z)?(p+=1,S.push((R.ts-w.caughtAt)/Ui)):h+=1}else R.event==="suppressed"?m+=1:y+=1}let x=p+m;c.push({check:l,caught:d.length,fixed:p,suppressed:m,reopened:f,moved:g,unverified:h,open:y,precision:x>0?p/x:null,medianDaysToFix:S.length>0?yv(S):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,d)=>l.check.localeCompare(d.check))}}function hv(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 su(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*Ui:Ui;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function yv(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{fork as bv}from"child_process";import{statSync as Sv}from"fs";import{isAbsolute as vv,join as xv,relative as Rv}from"path";import{watch as kv}from"chokidar";import wv from"ignore";var hr=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Ce(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.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Rt(t.projectRoot),this.extraIgnore=wv(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=kv(this.projectRoot,{ignoreInitial:!0,ignored:(n,r)=>this.isIgnoredWatchPath(n,r?.isDirectory()??!1)});t.on("all",(n,r)=>{this.stopped||this.handleFileChange(r)}),t.on("error",n=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`))}),this.fsWatchers.push(t)}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(t,n={}){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=au(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}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")||this.scheduleReindex({kind:"watch-source",detail:n})}relativeWatchPath(t){let n=vv(t)?t:xv(this.projectRoot,t);return Rv(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=au(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=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-t;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=Date.now();this.setStatus({state:"indexing",startedAt:r}),this.runReindex(n).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=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(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(t){return new Promise((n,r)=>{let i=Date.now(),o=me(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=De(this.projectRoot,s),c=s.indexer?.typescript,l=s.indexer?.clojure,d=bv(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:a.indexPath,SCIP_REINDEX_OUTPUT_DB:a.dbPath,SCIP_REINDEX_LANGUAGES:(s.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(s.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});d.on("exit",p=>{p===0?n(Date.now()-i):r(new Error(`Reindex worker exited with code ${p}`))}),d.on("error",r)})}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=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=Vt(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n=Zo(this.projectRoot,t),r={head:Vt(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let i=Sv(n);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function au(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}import{existsSync as Uv}from"fs";import{existsSync as lu,mkdirSync as du,readFileSync as uu,writeFileSync as pu}from"fs";import{homedir as $v}from"os";import{dirname as mu,isAbsolute as Cv,join as Ji,relative as cu,resolve as Pv}from"path";function fu(e,t={}){let n=t.dossierDir?Pv(e.projectRoot,t.dossierDir):Ji(e.projectRoot,"docs","scip-query"),r={markdownPath:Ji(n,"health-dossier.md"),jsonPath:Ji(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=Fv({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return Av(r.markdownPath,Tv(i),r),Dv(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function Tv(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${Ki(e.health)}`,"","## Items That Need Attention","",...Iv(e),"","## Blocked Or Unavailable Checks","",...jv(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","",...Ev(e),"","## JSON","",`Machine-readable report: \`${Lv(e)}\``,""].join(`
341
+ `)}`}function Iv(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 jv(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 Ev(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 Ki(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function Lv(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Av(e,t,n){if(du(mu(e),{recursive:!0}),(lu(e)?uu(e,"utf-8"):null)===t){n.unchanged.push(e);return}pu(e,t),n.written.push(e)}function Dv(e,t,n){du(mu(e),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
342
+ `,i=lu(e)?uu(e,"utf-8"):null;if(i&&Ov(i,r)){n.unchanged.push(e);return}pu(e,r),n.written.push(e)}function Ov(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 Fv(e,t){return zi(e,t)}function zi(e,t){return typeof e=="string"?Nv(e,t):Array.isArray(e)?e.map(n=>zi(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,zi(r,t)])):e}function Nv(e,t){if(e===t)return".";if(!Cv(e))return e;let n=cu(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=cu($v(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as Mv}from"child_process";import{readFileSync as hu}from"fs";import{dirname as gu,join as _v,resolve as qv}from"path";import{fileURLToPath as Bv}from"url";var yr={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 Vv(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of yr[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function Qi(e){return[...new Set(e.filter(t=>yr[t]!==void 0))].sort()}function yu(e,t={}){let n=t.runtime??Gv,r=t.packageRoot??Hv(),i=Qi(e),o=i.filter(p=>n.probe(yr[p].ast)),s=i.filter(p=>!o.includes(p));if(s.length===0)return{supportedLanguages:i,availableBefore:o,installed:[],availableAfter:o,unavailable:[],attempted:!1};let a=Wv(r),c=Vv(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let d=i.filter(p=>n.probe(yr[p].ast));return{supportedLanguages:i,availableBefore:o,installed:l.ok?c:[],availableAfter:d,unavailable:i.filter(p=>!d.includes(p)),attempted:!0,...l.error?{error:l.error}:{}}}function Hv(){let e=gu(Bv(import.meta.url));for(;;){let t=_v(e,"package.json");try{if(JSON.parse(hu(t,"utf8")).name==="scip-query")return e}catch{}let n=gu(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function Wv(e){return JSON.parse(hu(qv(e,"package.json"),"utf8")).optionalDependencies??{}}var Gv={probe:e=>yn(e)==="ast",resetProbe:jo,install:(e,t)=>{let n=Mv(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"});return n.status===0?{ok:!0}:{ok:!1,error:(n.stderr||n.stdout||n.error?.message||"npm install failed").trim()}}};function vu(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 xu(e={}){let t=[],n=Me(),{projectRoot:r,paths:i,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?Fa(r,n.config,e.languages):null,c=a?.config??n.config,l=kt(c,{projectRoot:r}),d=l.filter(E=>E.level==="error"),p=null,m=null;if(d.length===0&&c.watch?.enabled!==s)try{p=Na(r,c,s)}catch(E){m=At(E)}let f=p?.config??c,g=Xt();N(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?p?.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."),...p?{details:[p.configPath]}:{}}),N(t,{id:"scip-cli",label:"scip CLI",status:g?"ok":"warn",message:g?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let h=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:Xn({quiet:!0});N(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(E=>`Pruned ${E}`),...h.skipped.map(E=>`Skipped ${E}`)]});let y=p?kt(f,{projectRoot:r}):l,S=y.filter(E=>E.level==="error");N(t,{id:"config",label:"Project config",status:S.length>0?"failed":y.length>0?"warn":"ok",message:y.length===0?"Config OK.":`${y.length} diagnostic(s), ${S.length} error(s).`,details:y.map(E=>`${E.level.toUpperCase()} ${E.path}: ${E.message}`)});let x=ge(r,f);N(t,{id:"readiness",label:"Indexer readiness",status:x.languages.length===0?"failed":x.indexers.some(E=>!E.runnable)?"warn":"ok",message:x.languages.length===0?"No supported project languages detected.":`Detected languages: ${x.languages.join(", ")}`,details:x.indexers.map(E=>`${E.runnable?"OK":E.installed?"WARN":"MISSING"} ${E.language}: ${E.binaryLabel}${E.note?` - ${E.note}`:""}`)});let w=e.installAstParsers===!1?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:yu(x.languages);N(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers===!1?"skipped":w.unavailable.length>0?"warn":"ok",message:e.installAstParsers===!1?"Skipped by setup choice.":w.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${w.availableAfter.length}/${w.supportedLanguages.length} selected language parser(s) available${w.installed.length>0?`; installed ${w.installed.join(", ")}`:""}.`,details:[...w.unavailable.length>0?[`Unavailable: ${w.unavailable.join(", ")}`]:[],...w.error?[w.error]:[]]});let R=e.installIndexers??!0,D=R?rx(r,x,t):[];R||N(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped by guided setup choice."});let _=ge(r,f),z=await Jv({projectRoot:r,paths:i,config:f,readiness:_,configHasErrors:S.length>0,steps:t,onStatus:e.onStatus}),T=z.reindexResult,O=z.freshness,Z=Ce(f),F=zv({projectRoot:r,cacheDir:i.cacheDir,watchConfig:Z,readiness:_,configHasErrors:S.length>0,reindexResult:T,postReindexFreshness:O,steps:t}),H=ge(r,f),mn=Ke(H),Po=Fe(r,f,i);N(t,{id:"capabilities",label:"Capability matrix",status:lx(mn),message:dx(mn)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let To=e.runHealth===!1?sx(t):await ox(i.dbPath,t),we=H.languages.includes("rust")?Cn(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;N(t,{id:"rust-semantic-session",label:"Rust semantic session",status:we===null?"skipped":we.valid?"ok":"failed",message:we===null?"Skipped because Rust was not detected.":`${we.transport}/${we.state} selected from ${we.source}; ${we.fallback} fallback; opt out with ${we.optOut}.`});let ee=null;try{e.noHooks?N(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(ee=jt(r),N(t,{id:"project-hooks",label:"Project agent hooks",status:ee.skipped.length>0?"warn":"ok",message:`${ee.installed.length} installed, ${ee.updated.length} updated, ${ee.unchanged.length} already configured, ${ee.removed.length} hook config(s) cleaned up, ${ee.skipped.length} skipped.`,details:[...ee.gitExcluded.map(E=>`Checkout-local Git exclude: ${E}`),...ee.removed.map(E=>`Removed ${E}`),...ee.skipped.map(E=>`Skipped ${E.target}: ${E.reason}`),...ee.warnings]}))}catch(E){N(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:At(E)})}let ye=null;try{e.noAgentGuidance?N(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(ye=_n(r,{gitHook:e.gitHook}),N(t,{id:"agent-guidance",label:"Project agent guidance",status:ye.skipped.length>0?"warn":"ok",message:`${ye.written.length} written, ${ye.unchanged.length} already wired, ${ye.skipped.length} skipped.`,details:ye.skipped.map(E=>`Skipped ${E.target}: ${E.reason}`)}))}catch(E){N(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:At(E)})}let fn=Kv({reindexResult:T,readiness:H,capabilities:mn,freshness:Po,health:To,hooksResult:ee,agentResult:ye,watchConfig:Z,watchService:F,rustSemanticSession:we,steps:t});N(t,{id:"smoke-tests",label:"Setup smoke tests",status:Qv(fn),message:Yv(fn),details:fn.map(E=>`${E.command}: ${E.status} - ${E.evidence}`)});let yf={repository:[...a?.changed?[a.configPath]:[],...p?.changed?[p.configPath]:[],...ye?.written.filter(E=>!E.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...ee?.installed??[],...ee?.updated??[],...ee?.gitExcluded??[],...ye?.written.filter(E=>E.startsWith(".git/hooks/"))??[]])],user:[...h.installed,...w.installed,...D.filter(E=>E.attempted).map(E=>`${E.binaryLabel} installer`)]},Ee={projectRoot:r,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:g,languages:H.languages,steps:t,skills:h,astParsers:w,initialReadiness:x,indexerRemediation:D,readiness:H,capabilities:mn,freshness:Po,reindex:T,automaticRefreshConfig:p,watchService:F,rustSemanticSession:we,health:To,smokeTests:fn,healthDossier:null,hooks:ee,setupAgent:ye,changeScopes:yf,filesWritten:ye?.written??[],verdict:Xi(t,H)};if(e.runHealth===!1)return N(t,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),Ee.verdict=Xi(t,H),Ee;let $e=fu(Ee,{dossierDir:e.dossierDir});return Ee.healthDossier=$e,Ee.changeScopes.repository.push(...$e.written),Ee.filesWritten=[...Ee.filesWritten,...$e.written],N(t,{id:"health-dossier",label:"Health dossier",status:$e.status==="failed"?"failed":"ok",message:$e.status==="failed"?$e.error:`${$e.written.length} written, ${$e.unchanged.length} unchanged.`,details:[$e.markdownPath,$e.jsonPath]}),Ee.verdict=Xi(t,H),Ee}async function Jv(e){if(e.readiness.languages.length===0||e.configHasErrors)return N(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 Lt({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=Fe(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.");N(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){N(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:At(i),details:t})}return{reindexResult:n,freshness:r}}function zv(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 N(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=Fn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:Ne,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 N(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 N(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:At(n)}),null}}function Ru(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${Ki(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:"),Yi("Repository records (commit)",e.changeScopes.repository),Yi("Checkout preferences (do not commit)",e.changeScopes.checkout),Yi("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 Yi(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function Kv(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:Xv(e.steps),evidence:Zv(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?ex(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:bu(e.readiness,e.freshness),evidence:Su(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:bu(e.readiness,e.freshness),evidence:Su(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:tx(e.capabilities),evidence:nx(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 Qv(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Yv(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 Xv(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Zv(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function ex(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 bu(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function Su(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 tx(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function nx(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 rx(e,t,n){let r=[];if(t.languages.length===0)return N(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=st(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 p=ix(kn(a,e));r.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:d,before:s,after:p,messages:c,recovery:p.runnable?void 0:p.note??p.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(r.length===0)return N(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(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 ix(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function ox(e,t){if(!Uv(e)){let n="Skipped because no SQLite index database exists yet.";return N(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Zi(n)}try{let n=await Dn({full:!0,json:!0});return N(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),ax(n)}catch(n){let r=At(n);return N(t,{id:"health",label:"Health audit",status:"failed",message:r}),Zi(r)}}function sx(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return N(e,{id:"health",label:"Health audit",status:"skipped",message:t}),Zi(t)}function ax(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(cx),warnings:e.warnings??[]}}function cx(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-cleanup-audit to confirm this signal; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}}function Zi(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Xi(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 lx(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 dx(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 N(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function At(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as ux}from"readline";function px(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function mx(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 ku(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=px(e);ux(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
343
343
  `),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
344
344
 
345
345
  `),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
346
- `)}),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(`
347
- `),s(r.selected);return}let m=u.name==="up"?"up":u.name==="down"?"down":u.name==="space"?"toggle":null;m&&(r=ox(r,m,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!i),t.pause()}}import{existsSync as Ru,mkdirSync as sx,writeFileSync as ax}from"fs";import{dirname as cx,join as ku}from"path";function wu(e,t={}){let n=ku(e,".github","workflows","scip-query.yml"),r=lx({hasNpmProject:Ru(ku(e,"package.json"))});return Ru(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(sx(cx(n),{recursive:!0}),ax(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function lx(e){let t=`scip-query@${Ne}`;return`name: scip-query
346
+ `)}),n.write("\x1B[K")};o(!0);try{return await new Promise((s,a)=>{let c=(d,p)=>{if(p.ctrl&&p.name==="c"){l(),a(new Error("Setup cancelled."));return}if(p.name==="return"||p.name==="enter"){l(),n.write(`
347
+ `),s(r.selected);return}let m=p.name==="up"?"up":p.name==="down"?"down":p.name==="space"?"toggle":null;m&&(r=mx(r,m,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!i),t.pause()}}import{existsSync as wu,mkdirSync as fx,writeFileSync as gx}from"fs";import{dirname as hx,join as $u}from"path";function Cu(e,t={}){let n=$u(e,".github","workflows","scip-query.yml"),r=yx({hasNpmProject:wu($u(e,"package.json"))});return wu(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(fx(hx(n),{recursive:!0}),gx(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function yx(e){let t=`scip-query@${Ne}`;return`name: scip-query
348
348
 
349
349
  # Generated by scip-query setup-ci.
350
350
  # Install the language indexers your repository needs before the reindex step
@@ -372,69 +372,69 @@ ${e.hasNpmProject?` - run: npm ci
372
372
  `)+`
373
373
  `} - run: npx ${t} reindex
374
374
  - run: npx ${t} diff-gate --base "origin/\${{ github.base_ref }}"
375
- `}import{existsSync as dx}from"fs";import{join as fr}from"path";function $u(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=Sl({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=ux(e.projectRoot,{dryRun:e.dryRun})),s}function ux(e,t={}){return{hooks:Tt(e,{remove:!0,dryRun:t.dryRun}),agentSetup:qc(e,{dryRun:t.dryRun}),left:px(e)}}function px(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])=>dx(t)).map(([t])=>t)}import{existsSync as mx,readFileSync as fx}from"fs";import{createRequire as gx}from"module";import hr from"path";import{performance as gr}from"perf_hooks";var hx=gx(import.meta.url),nn;function Eu(e){let t=yx();if(!t)return $n("typescript is not installed");let n=ns(e);if(n.length===0)return $n("no tsconfig found");try{return new Yi(e.config.projectRoot,t,n.map(r=>bx(t,r)))}catch(r){return $n(r instanceof Error?r.message:String(r),n[0],n)}}function ju(e,t,n){let r=gr.now(),i=Pu(t,e),o=gr.now()-r,s=gr.now(),a=Pu(n,e),c=gr.now()-s,l=[],d=0,u=0,m=0,f=0,g=0;for(let h of e){let y=i.get(h.symbolId)??[],S=a.get(h.symbolId)??[];u+=y.length,m+=S.length;let x=Cu(y),k=Cu(S),R=Tu(y,k),D=Tu(S,x);if(R.length===0&&D.length===0){d+=1;continue}f+=R.length,g+=D.length,l.push({symbol:h.symbol,missing:R,extra:D})}return{slot:"semantic-references",definitions:e.length,matches:d,mismatchCount:l.length,missingReferenceCount:f,extraReferenceCount:g,baselineReferenceCount:u,candidateReferenceCount:m,baselineMs:Number(o.toFixed(3)),candidateMs:Number(c.toFixed(3)),mismatches:l}}var Yi=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=hr.join(this.projectRoot,t.relativePath),r=this.bundleForFile(n);if(!r)return[];let i=r.service.getProgram()?.getSourceFile(n);if(!i)return[];let o=vx(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=xx(this.ts,r.service,this.projectRoot,l);d&&(d.file===t.relativePath&&d.line>=t.startLine&&d.line<=t.endLine||a.push(d))}return es(a)}bundleForFile(t){let n=Au(t);return this.bundles.find(r=>r.files.has(n))??null}};function yx(){if(nn!==void 0)return nn;try{nn=hx("typescript")}catch{nn=null}return nn}function bx(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(Iu(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,hr.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>Iu(e,s)).join(`
376
- `));let i=new Set(r.fileNames.map(Au)),o=e.createLanguageService(Sx(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function Sx(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?hr.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(mx(n))return e.ScriptSnapshot.fromString(fx(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 vx(e,t,n){let r=t.text.split(`
377
- `),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 xx(e,t,n,r){let i=ts(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 Pu(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function Cu(e){return new Set(e.map(Lu))}function Tu(e,t){return e.filter(n=>!t.has(Lu(n)))}function Lu(e){return`${e.file}:${e.line}:${e.column}`}function Au(e){return hr.resolve(e).replace(/\\/g,"/")}function Iu(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
378
- `)}import{readFileSync as Rx}from"fs";function Du(e){let t=[];for(let[n,r]of Rx(e,"utf8").split(`
379
- `).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 Ou(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[y,S]of e.entries()){let x=ye(S.name)??ye(S.phase),k=Ix(S.durationMs),R=ye(S.runId);x&&k!==null&&(l+=1,s.add(x),R&&o.add(R),kx(i,S,x,k),wx(r,S,x,k,R),ye(S.subsystemWorkIdentity)&&c.add(x));let D=ye(S.workIdentity);if(!D)continue;d+=1,x&&a.add(x);let _=Tx(S.workOutcome);if(!x||k===null||!_){u+=1;continue}let z=R??`unknown-run-${y}`,T=JSON.stringify([x,D]),O=n.get(T)??{spanName:x,workIdentity:D,observations:[]};O.observations.push({runId:z,command:ye(S.command)??"unknown",durationMs:k,outcome:_}),n.set(T,O)}let m=[...n.values()].map(Cx).filter(y=>y!==null).sort((y,S)=>S.estimatedAvoidableMs-y.estimatedAvoidableMs||S.repeatComputations-y.repeatComputations||y.spanName.localeCompare(S.spanName)||y.workIdentity.localeCompare(S.workIdentity)),f=[...r.values()].map($x).filter(y=>y!==null).sort((y,S)=>S.laterRunMs-y.laterRunMs||S.laterRunEvents-y.laterRunEvents||y.spanName.localeCompare(S.spanName)),g=[...i.values()].map(Px).sort((y,S)=>S.totalDurationMs-y.totalDurationMs||y.subsystem.localeCompare(S.subsystem)),h=t.top??20;return{profileEvents:e.length,spanEvents:l,distinctSpanNames:s.size,instrumentedEvents:d,unclassifiedInstrumentedEvents:u,exactIdentifiedSpanNames:a.size,workloadIdentifiedEvents:g.reduce((y,S)=>y+S.workloadIdentifiedEvents,0),workloadIdentifiedSpanNames:c.size,runCount:o.size,repeatedGroups:m.length,largestOpportunityMs:m[0]?.estimatedAvoidableMs??0,rows:m.slice(0,h),repeatedWorkloads:f.length,largestRepeatedWorkloadMs:f[0]?.laterRunMs??0,workloadRows:f.slice(0,h),subsystemCoverage:g}}function Nu(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(`
375
+ `}import{existsSync as bx}from"fs";import{join as br}from"path";function Pu(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=vl({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=Sx(e.projectRoot,{dryRun:e.dryRun})),s}function Sx(e,t={}){return{hooks:jt(e,{remove:!0,dryRun:t.dryRun}),agentSetup:Wc(e,{dryRun:t.dryRun}),left:vx(e)}}function vx(e){return[[".scipquery.json",br(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",br(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",br(e,".scipquery","ledger")],["docs/scip-query/",br(e,"docs","scip-query")]].filter(([,t])=>bx(t)).map(([t])=>t)}import{existsSync as xx,readFileSync as Rx}from"fs";import{createRequire as kx}from"module";import vr from"path";import{performance as Sr}from"perf_hooks";var wx=kx(import.meta.url),sn;function Lu(e){let t=$x();if(!t)return Tn("typescript is not installed");let n=rs(e);if(n.length===0)return Tn("no tsconfig found");try{return new eo(e.config.projectRoot,t,n.map(r=>Cx(t,r)))}catch(r){return Tn(r instanceof Error?r.message:String(r),n[0],n)}}function Au(e,t,n){let r=Sr.now(),i=Tu(t,e),o=Sr.now()-r,s=Sr.now(),a=Tu(n,e),c=Sr.now()-s,l=[],d=0,p=0,m=0,f=0,g=0;for(let h of e){let y=i.get(h.symbolId)??[],S=a.get(h.symbolId)??[];p+=y.length,m+=S.length;let x=Iu(y),w=Iu(S),R=ju(y,w),D=ju(S,x);if(R.length===0&&D.length===0){d+=1;continue}f+=R.length,g+=D.length,l.push({symbol:h.symbol,missing:R,extra:D})}return{slot:"semantic-references",definitions:e.length,matches:d,mismatchCount:l.length,missingReferenceCount:f,extraReferenceCount:g,baselineReferenceCount:p,candidateReferenceCount:m,baselineMs:Number(o.toFixed(3)),candidateMs:Number(c.toFixed(3)),mismatches:l}}var eo=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=vr.join(this.projectRoot,t.relativePath),r=this.bundleForFile(n);if(!r)return[];let i=r.service.getProgram()?.getSourceFile(n);if(!i)return[];let o=Tx(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=Ix(this.ts,r.service,this.projectRoot,l);d&&(d.file===t.relativePath&&d.line>=t.startLine&&d.line<=t.endLine||a.push(d))}return ts(a)}bundleForFile(t){let n=Ou(t);return this.bundles.find(r=>r.files.has(n))??null}};function $x(){if(sn!==void 0)return sn;try{sn=wx("typescript")}catch{sn=null}return sn}function Cx(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(Eu(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,vr.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>Eu(e,s)).join(`
376
+ `));let i=new Set(r.fileNames.map(Ou)),o=e.createLanguageService(Px(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function Px(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?vr.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(xx(n))return e.ScriptSnapshot.fromString(Rx(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 Tx(e,t,n){let r=t.text.split(`
377
+ `),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 Ix(e,t,n,r){let i=ns(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 Tu(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function Iu(e){return new Set(e.map(Du))}function ju(e,t){return e.filter(n=>!t.has(Du(n)))}function Du(e){return`${e.file}:${e.line}:${e.column}`}function Ou(e){return vr.resolve(e).replace(/\\/g,"/")}function Eu(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
378
+ `)}import{readFileSync as jx}from"fs";function Fu(e){let t=[];for(let[n,r]of jx(e,"utf8").split(`
379
+ `).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 Nu(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,p=0;for(let[y,S]of e.entries()){let x=he(S.name)??he(S.phase),w=Nx(S.durationMs),R=he(S.runId);x&&w!==null&&(l+=1,s.add(x),R&&o.add(R),Ex(i,S,x,w),Lx(r,S,x,w,R),he(S.subsystemWorkIdentity)&&c.add(x));let D=he(S.workIdentity);if(!D)continue;d+=1,x&&a.add(x);let _=Fx(S.workOutcome);if(!x||w===null||!_){p+=1;continue}let z=R??`unknown-run-${y}`,T=JSON.stringify([x,D]),O=n.get(T)??{spanName:x,workIdentity:D,observations:[]};O.observations.push({runId:z,command:he(S.command)??"unknown",durationMs:w,outcome:_}),n.set(T,O)}let m=[...n.values()].map(Ox).filter(y=>y!==null).sort((y,S)=>S.estimatedAvoidableMs-y.estimatedAvoidableMs||S.repeatComputations-y.repeatComputations||y.spanName.localeCompare(S.spanName)||y.workIdentity.localeCompare(S.workIdentity)),f=[...r.values()].map(Ax).filter(y=>y!==null).sort((y,S)=>S.laterRunMs-y.laterRunMs||S.laterRunEvents-y.laterRunEvents||y.spanName.localeCompare(S.spanName)),g=[...i.values()].map(Dx).sort((y,S)=>S.totalDurationMs-y.totalDurationMs||y.subsystem.localeCompare(S.subsystem)),h=t.top??20;return{profileEvents:e.length,spanEvents:l,distinctSpanNames:s.size,instrumentedEvents:d,unclassifiedInstrumentedEvents:p,exactIdentifiedSpanNames:a.size,workloadIdentifiedEvents:g.reduce((y,S)=>y+S.workloadIdentifiedEvents,0),workloadIdentifiedSpanNames:c.size,runCount:o.size,repeatedGroups:m.length,largestOpportunityMs:m[0]?.estimatedAvoidableMs??0,rows:m.slice(0,h),repeatedWorkloads:f.length,largestRepeatedWorkloadMs:f[0]?.laterRunMs??0,workloadRows:f.slice(0,h),subsystemCoverage:g}}function Mu(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(`
380
380
  `)}
381
- `}function kx(e,t,n,r){let i=ye(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),ye(t.subsystemWorkIdentity)&&(o.workloadIdentifiedEvents+=1,o.workloadIdentifiedSpanNames.add(n)),ye(t.workIdentity)&&(o.exactIdentifiedEvents+=1,o.exactIdentifiedSpanNames.add(n)),e.set(i,o)}function wx(e,t,n,r,i){let o=ye(t.subsystemWorkIdentity);if(!o||!i||t.workloadIdentityKind!=="published-project")return;let s=ye(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:ye(t.command)??"unknown",durationMs:r}),e.set(a,c)}function $x(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:Lt(e.observations.map(o=>o.durationMs)),firstRunMs:Lt(r.map(o=>o.durationMs)),laterRunMs:Lt(i.map(o=>o.durationMs))}}function Px(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 Cx(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=Lt(r.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=Lt(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:Lt(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:i,crossRunRecomputeMs:o,estimatedAvoidableMs:i+o,cacheHits:yr(e.observations,"cache-hit"),cacheMisses:yr(e.observations,"cache-miss"),reused:yr(e.observations,"reused"),skipped:yr(e.observations,"skipped")}}function Tx(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function yr(e,t){return e.filter(n=>n.outcome===t).length}function Ix(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function ye(e){return typeof e=="string"&&e.length>0?e:null}function Lt(e){return e.reduce((t,n)=>t+n,0)}var Fu={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 Mu(e,t){let n=Ex(t);return{...e,warnings:[...e.warnings??[],Fu.note,...n],capabilities:t,scoreInterpretation:Fu}}function Ex(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.`]})}var Mx=new Set(Na),_x=18e4,Vu=100*1024*1024,qx=new Set(To),Bx=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],Vx=[["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 Hx(e){return e.filter(t=>Mx.has(t))}async function Hu(e){let t=G(e),n=Y(),r=fe(n),i=De(n,r),o=b(t,"json");try{let s=Hx(wt(t,"language")),a=await Et({projectRoot:n,languages:s.length>0?s:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:b(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,clojureConfigPath:r.indexer?.clojure?.configPath,skipIfUnchanged:!b(t,"force"),allowPartial:b(t,"allowPartial"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",indexerConcurrency:U(t,"indexerConcurrency")??r.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...o?{onStatus:()=>{}}:{}});if(o){I("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 Wu(){let e=Y(),t=Rt(e);try{let n=Xn({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)}}function Gu(e){let t=G(e),n=Y(),r=Rt(n);try{let i=Fi({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 Uu(e){let t=G(e);le(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=ea(n,{base:w(t,"base")}),o=ta(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function Ju(e){let t=G(e);try{let n=await cc({base:w(t,"base")});if(b(t,"json")){I("diff-impact",[],t,n);return}lc(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function zu(e,t){let n=G(t),r=String(e).split(",").filter(i=>i.length>0);le(i=>{let o=[];for(let c of r)Ia.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:w(n,"scope"),full:b(n,"full")},a=o.length===1?Ea(i,o[0],s):ja(i,o,s);console.log(JSON.stringify(a))})}async function Ku(e){let t=G(e);if(b(t,"writeBaseline")||b(t,"baseline")){rR(t);return}try{let n=await An({scope:w(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:r,config:i,dbPath:o}=Fe(),s=Je(he(r,i),{hasIndexedGraph:ke(o)}),a=Mu(n,s);if(b(t,"json")){I("health",[],t,a);return}ac(a,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Qu(e){let t=G(e),n=Y(),r=U(t,"timeoutMs")??_x,i=b(t,"progress"),o=b(t,"profile"),s=w(t,"profileOut"),a={projectRoot:n,...Zx(n),index:Xi(ke(Rt(n))),commands:[]};b(t,"coldIndex")&&(At(i,"cold index started"),a.coldIndex=await Wx(n),At(i,`cold index finished ${a.coldIndex.durationMs}ms`),Mt({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),At(i,"warm index started"),a.warmIndex=await zx(n),At(i,`warm index finished ${a.warmIndex.durationMs}ms`),Mt({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=Xi(ke(Rt(n))));for(let c of Kx(t))a.commands.push(Yx(n,c,r,{progress:i,profile:o,profileOut:s}));if(b(t,"json")){I("bench",[],t,a);return}eR(a)}function Yu(e,t){let n=G(t),r=Fx(String(e)),i=Ou(Du(r),{top:U(n,"top")??20});if(b(n,"json")){I("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(Nu(i,r))}function Xu(e){let t=G(e);le(n=>{let r=n.config.projectRoot,i=w(t,"scope")??null,o=b(t,"full"),s=U(t,"limit")??200,a=Math.max(0,U(t,"maxMismatches")??10),c=Ao(n).filter(k=>_t(k.relativePath)).filter(k=>!n.isIgnored(k.relativePath)).sort(nR),l=i?c.filter(k=>k.relativePath.includes(i)):c,d=o?l:l.slice(0,s),u=Xe.now(),m=is(n),f=Number((Xe.now()-u).toFixed(3)),g=Xe.now(),h=Eu(n),y=Number((Xe.now()-g).toFixed(3)),S=ju(d,m,h),x={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:f,availability:m.availability()},candidate:{provider:"tsserver",createMs:y,availability:h.availability()},comparison:{...S,mismatches:S.mismatches.slice(0,a)}};if(b(t,"json")){I("typescript-semantic-compare",[],t,x);return}tR(x)})}async function Wx(e){let t=fe(e),n=De(e,t),r=br(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;Gx(r);let o=Ux(r,i);try{let s=await Zu(()=>Et({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 _u(r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...ep(e)}}catch(s){throw _u(r,i,o,"restore-backup"),s}}var Zi={existsSync:ke,readFileSync:jx,writeFileSync:Ox,renameSync:Lx,rmSync:Ax,unlinkSync:Dx};function eo(e){return ut(br(e),"bench-restore.json")}function Gx(e,t=Zi){let n=eo(e);if(!t.existsSync(n))return!1;let r=Jx(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 Ux(e,t,n=Zi){return n.existsSync(e)?(n.writeFileSync(eo(e),JSON.stringify({originalPath:e,backupPath:t})),n.renameSync(e,t),!0):!1}function _u(e,t,n,r,i=Zi){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=eo(e);i.existsSync(o)&&i.unlinkSync(o)}function Jx(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 zx(e){let t=fe(e),n=De(e,t),r=await Zu(()=>Et({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,...ep(e)}}async function Zu(e){let t=Xe.now(),n=await e();return{durationMs:Math.round(Xe.now()-t),value:n}}function ep(e){return ke(Rt(e))?le(t=>{let n=bt(t);return{files:n.documents,symbols:n.symbols}}):{}}function Kx(e){let t=wt(e,"command");return t.length>0?t.map(Qx).filter(n=>n.length>0):[...Bx.map(n=>[...n]),...b(e,"includeHeavy")?Vx.map(n=>[...n]):[]]}function Qx(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function Yx(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;At(r.progress,`${i} started`),Mt({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=Xe.now(),s={...r.profile?Xx(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=Bu(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:Vu,timeout:n}),c=Math.round(Xe.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 At(r.progress,`${i} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),Mt({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 At(e,t){e&&process.stderr.write(`[bench] ${t}
382
- `)}function Xx(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function Zx(e){let t=Bu("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:Vu});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
383
- `).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(r=>qx.has(Nx(r).toLowerCase())).length}}function eR(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, ${Ue(e.index.indexSizeBytes)}`),e.coldIndex&&qu("Cold index",e.coldIndex),e.warmIndex&&qu("Warm index",e.warmIndex),console.log(`
384
- 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 qu(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function tR(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(`
385
- Mismatch samples:`);for(let t of e.comparison.mismatches)console.log(` ${t.symbol}`),console.log(` missing=${t.missing.length} extra=${t.extra.length}`)}}function nR(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function rR(e){let t=w(e,"scope");le(n=>{if(b(e,"writeBaseline")){let i=la(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=da(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 tp(){let e=Qn(),t=e.installed.length+e.alreadyLinked.length;console.log(`
386
- ${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 np(e){let t=G(e),n=Y(),r=Tt(n,{shared:b(t,"shared"),remove:b(t,"remove"),force:b(t,"force")});if(b(t,"json")){I("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(`
381
+ `}function Ex(e,t,n,r){let i=he(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),he(t.subsystemWorkIdentity)&&(o.workloadIdentifiedEvents+=1,o.workloadIdentifiedSpanNames.add(n)),he(t.workIdentity)&&(o.exactIdentifiedEvents+=1,o.exactIdentifiedSpanNames.add(n)),e.set(i,o)}function Lx(e,t,n,r,i){let o=he(t.subsystemWorkIdentity);if(!o||!i||t.workloadIdentityKind!=="published-project")return;let s=he(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:he(t.command)??"unknown",durationMs:r}),e.set(a,c)}function Ax(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:Dt(e.observations.map(o=>o.durationMs)),firstRunMs:Dt(r.map(o=>o.durationMs)),laterRunMs:Dt(i.map(o=>o.durationMs))}}function Dx(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 Ox(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=Dt(r.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=Dt(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:Dt(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:i,crossRunRecomputeMs:o,estimatedAvoidableMs:i+o,cacheHits:xr(e.observations,"cache-hit"),cacheMisses:xr(e.observations,"cache-miss"),reused:xr(e.observations,"reused"),skipped:xr(e.observations,"skipped")}}function Fx(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function xr(e,t){return e.filter(n=>n.outcome===t).length}function Nx(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function he(e){return typeof e=="string"&&e.length>0?e:null}function Dt(e){return e.reduce((t,n)=>t+n,0)}var _u={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 qu(e,t){let n=Mx(t);return{...e,warnings:[...e.warnings??[],_u.note,...n],capabilities:t,scoreInterpretation:_u}}function Mx(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.`]})}var Ux=new Set(Da),Jx=18e4,Wu=100*1024*1024,zx=new Set(Eo),Kx=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],Qx=[["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 Yx(e){return e.filter(t=>Ux.has(t))}async function Gu(e){let t=G(e),n=Y(),r=me(n),i=De(n,r),o=b(t,"json");try{let s=Yx(Ct(t,"language")),a=await Lt({projectRoot:n,languages:s.length>0?s:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:b(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,clojureConfigPath:r.indexer?.clojure?.configPath,skipIfUnchanged:!b(t,"force"),allowPartial:b(t,"allowPartial"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",indexerConcurrency:U(t,"indexerConcurrency")??r.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...o?{onStatus:()=>{}}:{}});if(o){I("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 Uu(){let e=Y(),t=wt(e);try{let n=er({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)}}function Ju(e){let t=G(e),n=Y(),r=wt(n);try{let i=qi({projectRoot:n,dbPath:r,tsconfig:k(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 zu(e){let t=G(e);ce(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=Ys(n,{base:k(t,"base")}),o=Xs(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function Ku(e){let t=G(e);try{let n=await sc({base:k(t,"base")});if(b(t,"json")){I("diff-impact",[],t,n);return}ac(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Qu(e,t){let n=G(t),r=String(e).split(",").filter(i=>i.length>0);ce(i=>{let o=[];for(let c of r)Pa.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:k(n,"scope"),full:b(n,"full")},a=o.length===1?Ta(i,o[0],s):Ia(i,o,s);console.log(JSON.stringify(a))})}async function Yu(e){let t=G(e);if(b(t,"writeBaseline")||b(t,"baseline")){uR(t);return}try{let n=await Dn({scope:k(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:r,config:i,dbPath:o}=Me(),s=Ke(ge(r,i),{hasIndexedGraph:ke(o)}),a=qu(n,s);if(b(t,"json")){I("health",[],t,a);return}oc(a,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Xu(e){let t=G(e),n=Y(),r=U(t,"timeoutMs")??Jx,i=b(t,"progress"),o=b(t,"profile"),s=k(t,"profileOut"),a={projectRoot:n,...aR(n),index:to(ke(wt(n))),commands:[]};b(t,"coldIndex")&&(Ot(i,"cold index started"),a.coldIndex=await Xx(n),Ot(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),Ot(i,"warm index started"),a.warmIndex=await nR(n),Ot(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=to(ke(wt(n))));for(let c of rR(t))a.commands.push(oR(n,c,r,{progress:i,profile:o,profileOut:s}));if(b(t,"json")){I("bench",[],t,a);return}cR(a)}function Zu(e,t){let n=G(t),r=Gx(String(e)),i=Nu(Fu(r),{top:U(n,"top")??20});if(b(n,"json")){I("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(Mu(i,r))}function ep(e){let t=G(e);ce(n=>{let r=n.config.projectRoot,i=k(t,"scope")??null,o=b(t,"full"),s=U(t,"limit")??200,a=Math.max(0,U(t,"maxMismatches")??10),c=Fo(n).filter(w=>Ht(w.relativePath)).filter(w=>!n.isIgnored(w.relativePath)).sort(dR),l=i?c.filter(w=>w.relativePath.includes(i)):c,d=o?l:l.slice(0,s),p=et.now(),m=os(n),f=Number((et.now()-p).toFixed(3)),g=et.now(),h=Lu(n),y=Number((et.now()-g).toFixed(3)),S=Au(d,m,h),x={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:f,availability:m.availability()},candidate:{provider:"tsserver",createMs:y,availability:h.availability()},comparison:{...S,mismatches:S.mismatches.slice(0,a)}};if(b(t,"json")){I("typescript-semantic-compare",[],t,x);return}lR(x)})}async function Xx(e){let t=me(e),n=De(e,t),r=Rr(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;Zx(r);let o=eR(r,i);try{let s=await tp(()=>Lt({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 Bu(r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...np(e)}}catch(s){throw Bu(r,i,o,"restore-backup"),s}}var no={existsSync:ke,readFileSync:_x,writeFileSync:Hx,renameSync:qx,rmSync:Bx,unlinkSync:Vx};function ro(e){return mt(Rr(e),"bench-restore.json")}function Zx(e,t=no){let n=ro(e);if(!t.existsSync(n))return!1;let r=tR(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 eR(e,t,n=no){return n.existsSync(e)?(n.writeFileSync(ro(e),JSON.stringify({originalPath:e,backupPath:t})),n.renameSync(e,t),!0):!1}function Bu(e,t,n,r,i=no){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=ro(e);i.existsSync(o)&&i.unlinkSync(o)}function tR(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 nR(e){let t=me(e),n=De(e,t),r=await tp(()=>Lt({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,...np(e)}}async function tp(e){let t=et.now(),n=await e();return{durationMs:Math.round(et.now()-t),value:n}}function np(e){return ke(wt(e))?ce(t=>{let n=vt(t);return{files:n.documents,symbols:n.symbols}}):{}}function rR(e){let t=Ct(e,"command");return t.length>0?t.map(iR).filter(n=>n.length>0):[...Kx.map(n=>[...n]),...b(e,"includeHeavy")?Qx.map(n=>[...n]):[]]}function iR(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function oR(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;Ot(r.progress,`${i} started`),qt({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=et.now(),s={...r.profile?sR(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=Hu(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:Wu,timeout:n}),c=Math.round(et.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 Ot(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 Ot(e,t){e&&process.stderr.write(`[bench] ${t}
382
+ `)}function sR(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function aR(e){let t=Hu("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:Wu});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
383
+ `).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(r=>zx.has(Wx(r).toLowerCase())).length}}function cR(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, ${Je(e.index.indexSizeBytes)}`),e.coldIndex&&Vu("Cold index",e.coldIndex),e.warmIndex&&Vu("Warm index",e.warmIndex),console.log(`
384
+ 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 Vu(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function lR(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(`
385
+ Mismatch samples:`);for(let t of e.comparison.mismatches)console.log(` ${t.symbol}`),console.log(` missing=${t.missing.length} extra=${t.extra.length}`)}}function dR(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function uR(e){let t=k(e,"scope");ce(n=>{if(b(e,"writeBaseline")){let i=sa(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=aa(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 rp(){let e=Xn(),t=e.installed.length+e.alreadyLinked.length;console.log(`
386
+ ${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 ip(e){let t=G(e),n=Y(),r=jt(n,{shared:b(t,"shared"),remove:b(t,"remove"),force:b(t,"force")});if(b(t,"json")){I("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(`
387
387
  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(`
388
- No project-local hook config was written.`)}function rp(){let e=!1;Kt()?console.log("scip CLI: installed"):(ui(),e=!0);let t=Y(),n=fe(t),r=he(t,n);if(r.languages.length===0){console.log(`
388
+ No project-local hook config was written.`)}function op(){let e=!1;Xt()?console.log("scip CLI: installed"):(mi(),e=!0);let t=Y(),n=me(t),r=ge(t,n);if(r.languages.length===0){console.log(`
389
389
  No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
390
390
  Detected languages: ${r.languages.join(", ")}`),console.log(`
391
- 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=xp(r);i.length>0&&console.log(`
392
- Semantic provider readiness:`);for(let o of i){let s=o.available?" OK":o.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${o.language}: ${mR(o)}${Rp(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function ip(e){sp(e,"capabilities")}function op(e){b(G(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),sp(e,"capability-matrix")}function sp(e,t){let n=G(e),{projectRoot:r,config:i,paths:o,dbPath:s}=Fe(),a=he(r,i),c=Oe(r,i,o),l=Je(a,{hasIndexedGraph:ke(s)&&c.state!=="missing"});if(b(n,"json")){I(t,[],n,l);return}to(l)}function ap(){let e=Y(),t=tt(e),n=Fa(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function cp(e){let t=G(e),n=Y(),r=fe(n),i=xt(r,{projectRoot:n});if(b(t,"json"))I("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 lp(e,t){let n=G(t),r=w(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=ma(Y(),{id:String(e),check:w(n,"check"),file:w(n,"file"),reason:r,expiresAt:w(n,"expiresAt")});if(b(n,"json")){I("suppress",[String(e)],n,i);return}console.log(`Suppression written to ${i.path}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exitCode=1}}function dp(e){let t=G(e),n=Date.now(),r=w(t,"since"),i;if(r){let y=iu(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=Y(),s=Vn(o),a=ru(s,{sinceMs:i,check:w(t,"check")});if(b(t,"json")){I("effectiveness",[],t,a);return}if(a.checks.length===0){console.log(s.length===0?`No outcome events recorded yet (${ut(Bn,"*.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 c=["check","caught","fixed","suppressed","open","moved","unverified","precision","median-days-to-fix"],l=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)]),d=c.map((y,S)=>Math.max(y.length,...l.map(x=>x[S].length))),u=y=>y.map((S,x)=>S.padEnd(d[x])).join(" ");console.log(u(c));for(let y of l)console.log(u(y));let m=a.checks.reduce((y,S)=>y+S.fixed,0),f=a.checks.reduce((y,S)=>y+S.suppressed,0),g=a.checks.reduce((y,S)=>y+S.unverified,0),h=m+f;h>0?console.log(`
391
+ 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=kp(r);i.length>0&&console.log(`
392
+ Semantic provider readiness:`);for(let o of i){let s=o.available?" OK":o.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${o.language}: ${xR(o)}${wp(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function sp(e){cp(e,"capabilities")}function ap(e){b(G(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),cp(e,"capability-matrix")}function cp(e,t){let n=G(e),{projectRoot:r,config:i,paths:o,dbPath:s}=Me(),a=ge(r,i),c=Fe(r,i,o),l=Ke(a,{hasIndexedGraph:ke(s)&&c.state!=="missing"});if(b(n,"json")){I(t,[],n,l);return}io(l)}function lp(){let e=Y(),t=rt(e),n=Oa(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function dp(e){let t=G(e),n=Y(),r=me(n),i=kt(r,{projectRoot:n});if(b(t,"json"))I("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 up(e,t){let n=G(t),r=k(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=da(Y(),{id:String(e),check:k(n,"check"),file:k(n,"file"),reason:r,expiresAt:k(n,"expiresAt")});if(b(n,"json")){I("suppress",[String(e)],n,i);return}console.log(`Suppression written to ${i.path}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exitCode=1}}function pp(e){let t=G(e),n=Date.now(),r=k(t,"since"),i;if(r){let y=su(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=Y(),s=Wn(o),a=ou(s,{sinceMs:i,check:k(t,"check")});if(b(t,"json")){I("effectiveness",[],t,a);return}if(a.checks.length===0){console.log(s.length===0?`No outcome events recorded yet (${mt(Hn,"*.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 c=["check","caught","fixed","suppressed","open","moved","unverified","precision","median-days-to-fix"],l=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)]),d=c.map((y,S)=>Math.max(y.length,...l.map(x=>x[S].length))),p=y=>y.map((S,x)=>S.padEnd(d[x])).join(" ");console.log(p(c));for(let y of l)console.log(p(y));let m=a.checks.reduce((y,S)=>y+S.fixed,0),f=a.checks.reduce((y,S)=>y+S.suppressed,0),g=a.checks.reduce((y,S)=>y+S.unverified,0),h=m+f;h>0?console.log(`
393
393
  ${m} finding(s) verified fixed against a stable comparison base, ${f} suppressed, ${g} disappeared without comparable evidence \u2014 overall precision ${Math.round(m/h*100)}%.`):g>0&&console.log(`
394
- ${g} finding(s) disappeared without comparable comparison-base evidence; precision is not available.`)}function up(e){let t=G(e),{report:n,hasIndexerProblems:r,hasErrors:i}=pp("doctor");b(t,"json")?I("doctor",[],t,n):lR(n,r),process.exitCode=i?1:0}function pp(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Fe(),o=xt(n,{projectRoot:t}),s=he(t,n),a=Oe(t,n,r),c=ke(i),l=Je(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=vc(t,n,r),u=s.indexers.some(g=>!g.runnable),m=o.some(g=>g.level==="error")||u||a.state==="missing"||a.state==="stale",f=o.some(g=>g.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:f}}function mp(e){let t=G(e),n=Y(),r=Fn(n,{gitHook:b(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(`
395
- 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 fp(e){let t=G(e);try{let n={gitHook:b(t,"gitHook"),noHooks:b(t,"noHooks")||t.hooks===!1,dossierDir:w(t,"dossierDir"),runHealth:b(t,"yes")?!1:t.health!==!1,installSkills:t.skills!==!1,installAstParsers:t.parsers!==!1,...b(t,"yes")?{automaticRefresh:!0}:{}},r=b(t,"json"),i=!r&&!b(t,"yes")&&process.stdin.isTTY&&process.stdout.isTTY;(b(t,"guided")||i)&&(n=await iR(n,{json:b(t,"json")})),r||(n.onStatus=s=>console.log(` ${s}`));let o=await Su(n);b(t,"json")?I("setup",[],t,o):vu(o),process.exitCode=o.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function iR(e,t){let{projectRoot:n,config:r}=Fe(),i=he(n,r),o=bu({files:oR(n),watchEnabled:Pe(r).enabled,readiness:i}),s=i.languages.map(g=>({id:`language:${g}`,scope:"project",label:`Index ${g}`,reason:"Detected in this project.",selected:!0})),a=o.actions.map(g=>({id:g.id,scope:g.scope==="repository"?"project":g.scope,label:g.label,reason:g.reason,selected:g.recommended})),c=Ji(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 xu([...s,...a]):new Set([...sR(o.actions),...s.map(g=>g.id)]);l&&aR(o.actions,d);let u=d.has("create-agent-guidance")||d.has("update-agent-guidance"),m=o.actions.some(g=>g.id==="enable-automatic-refresh"),f=o.actions.some(g=>g.id==="install-indexers");return{...e,...m?{automaticRefresh:d.has("enable-automatic-refresh")}:{},noHooks:e.noHooks||o.actions.some(g=>g.id==="install-project-hooks")&&!d.has("install-project-hooks"),noAgentGuidance:!u,...f?{installIndexers:d.has("install-indexers")}:{},languages:i.languages.filter(g=>d.has(`language:${g}`)),installSkills:d.has("install-agent-skills"),installAstParsers:d.has("install-ast-parsers"),runHealth:d.has("run-health-analysis")}}function oR(e){return{agentsMd:ke(ut(e,"AGENTS.md")),claudeMd:ke(ut(e,"CLAUDE.md")),codexHooks:ke(ut(e,".codex","hooks.json")),claudeSettings:ke(ut(e,".claude","settings.local.json"))}}function sR(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function aR(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 gp(e){let t=G(e),n=Y(),r=wu(n,{force:b(t,"force"),dryRun:b(t,"dryRun")});if(b(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 hp(e){let t=G(e);if(b(t,"global")&&b(t,"project")){console.error("error: choose either --global or --project, not both."),process.exitCode=1;return}let n=$u({projectRoot:Y(),global:b(t,"global"),project:b(t,"project"),dryRun:b(t,"dryRun")});if(b(t,"json")){I("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 yp(e){let t=G(e),n=Y(),r=fe(n),i=U(t,"debounce"),o=U(t,"cooldown"),s=U(t,"gitPoll"),a=U(t,"idleTimeout"),c=b(t,"daemon"),l=b(t,"status"),d=b(t,"stop"),u=b(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 f=[["--debounce",i,!1],["--cooldown",o,!0],["--git-poll",s,!1],["--idle-timeout",a,!0]].find(([,R,D])=>R!==void 0&&(!Number.isInteger(R)||(D?Number(R)<0:Number(R)<=0)));if(f){console.error(`error: ${f[0]} requires ${f[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}let g={...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=Pe(r);r.watch=h;let y=De(n,r),S={projectRoot:n,cacheDir:y.cacheDir,cliVersion:Ne,watchOverrides:g};if(l){let R=bp(Fr(S),h.enabled);u?I("watch",[],t,R):Sp(R);return}if(d){try{let R=Yo(S);u?I("watch",[],t,R):console.log(R.disposition==="stopped"?`Stopped watch service${R.pid?` (pid ${R.pid})`:""}.`:"Watch service is already stopped.")}catch(R){console.error(`error: ${R instanceof Error?R.message:String(R)}`),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 R=wn(S);u?I("watch",[],t,R):console.log(`${R.disposition==="started"?"Started":"Reused"} watch service for ${n} (pid ${R.state.pid}).`)}catch(R){console.error(`error: ${R instanceof Error?R.message:String(R)}`),process.exitCode=1}return}let x=Zo(ut(br(y.dbPath),Ko),n);if(!x.acquired){console.error(x.message),process.exitCode=1;return}let k=new pr({projectRoot:n,config:r,languages:r.languages,onStatus:R=>{process.stdout.write(`\r\x1B[K${Wr(R)}`)},onReindexComplete:R=>{console.log(`
394
+ ${g} finding(s) disappeared without comparable comparison-base evidence; precision is not available.`)}function mp(e){let t=G(e),{report:n,hasIndexerProblems:r,hasErrors:i}=fp("doctor");b(t,"json")?I("doctor",[],t,n):yR(n,r),process.exitCode=i?1:0}function fp(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Me(),o=kt(n,{projectRoot:t}),s=ge(t,n),a=Fe(t,n,r),c=ke(i),l=Ke(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=Rc(t,n,r),p=s.indexers.some(g=>!g.runnable),m=o.some(g=>g.level==="error")||p||a.state==="missing"||a.state==="stale",f=o.some(g=>g.level==="error")||p||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:p,hasErrors:f}}function gp(e){let t=G(e),n=Y(),r=_n(n,{gitHook:b(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(`
395
+ 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 hp(e){let t=G(e);try{let n={gitHook:b(t,"gitHook"),noHooks:b(t,"noHooks")||t.hooks===!1,dossierDir:k(t,"dossierDir"),runHealth:b(t,"yes")?!1:t.health!==!1,installSkills:t.skills!==!1,installAstParsers:t.parsers!==!1,...b(t,"yes")?{automaticRefresh:!0}:{}},r=b(t,"json"),i=!r&&!b(t,"yes")&&process.stdin.isTTY&&process.stdout.isTTY;(b(t,"guided")||i)&&(n=await pR(n,{json:b(t,"json")})),r||(n.onStatus=s=>console.log(` ${s}`));let o=await xu(n);b(t,"json")?I("setup",[],t,o):Ru(o),process.exitCode=o.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function pR(e,t){let{projectRoot:n,config:r}=Me(),i=ge(n,r),o=vu({files:mR(n),watchEnabled:Ce(r).enabled,readiness:i}),s=i.languages.map(g=>({id:`language:${g}`,scope:"project",label:`Index ${g}`,reason:"Detected in this project.",selected:!0})),a=o.actions.map(g=>({id:g.id,scope:g.scope==="repository"?"project":g.scope,label:g.label,reason:g.reason,selected:g.recommended})),c=Qi(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 ku([...s,...a]):new Set([...fR(o.actions),...s.map(g=>g.id)]);l&&gR(o.actions,d);let p=d.has("create-agent-guidance")||d.has("update-agent-guidance"),m=o.actions.some(g=>g.id==="enable-automatic-refresh"),f=o.actions.some(g=>g.id==="install-indexers");return{...e,...m?{automaticRefresh:d.has("enable-automatic-refresh")}:{},noHooks:e.noHooks||o.actions.some(g=>g.id==="install-project-hooks")&&!d.has("install-project-hooks"),noAgentGuidance:!p,...f?{installIndexers:d.has("install-indexers")}:{},languages:i.languages.filter(g=>d.has(`language:${g}`)),installSkills:d.has("install-agent-skills"),installAstParsers:d.has("install-ast-parsers"),runHealth:d.has("run-health-analysis")}}function mR(e){return{agentsMd:ke(mt(e,"AGENTS.md")),claudeMd:ke(mt(e,"CLAUDE.md")),codexHooks:ke(mt(e,".codex","hooks.json")),claudeSettings:ke(mt(e,".claude","settings.local.json"))}}function fR(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function gR(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 yp(e){let t=G(e),n=Y(),r=Cu(n,{force:b(t,"force"),dryRun:b(t,"dryRun")});if(b(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 bp(e){let t=G(e);if(b(t,"global")&&b(t,"project")){console.error("error: choose either --global or --project, not both."),process.exitCode=1;return}let n=Pu({projectRoot:Y(),global:b(t,"global"),project:b(t,"project"),dryRun:b(t,"dryRun")});if(b(t,"json")){I("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 Sp(e){let t=G(e),n=Y(),r=me(n),i=U(t,"debounce"),o=U(t,"cooldown"),s=U(t,"gitPoll"),a=U(t,"idleTimeout"),c=b(t,"daemon"),l=b(t,"status"),d=b(t,"stop"),p=b(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(p&&m===0){console.error("error: --json requires --daemon, --status, or --stop."),process.exitCode=1;return}let f=[["--debounce",i,!1],["--cooldown",o,!0],["--git-poll",s,!1],["--idle-timeout",a,!0]].find(([,R,D])=>R!==void 0&&(!Number.isInteger(R)||(D?Number(R)<0:Number(R)<=0)));if(f){console.error(`error: ${f[0]} requires ${f[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}let g={...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=Ce(r);r.watch=h;let y=De(n,r),S={projectRoot:n,cacheDir:y.cacheDir,cliVersion:Ne,watchOverrides:g};if(l){let R=vp(zr(S),h.enabled);p?I("watch",[],t,R):xp(R);return}if(d){try{let R=Sc(S);p?I("watch",[],t,R):console.log(R.disposition==="stopped"?`Stopped watch service${R.pid?` (pid ${R.pid})`:""}.`:"Watch service is already stopped.")}catch(R){console.error(`error: ${R instanceof Error?R.message:String(R)}`),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 R=Fn(S);p?I("watch",[],t,R):console.log(`${R.disposition==="started"?"Started":"Reused"} watch service for ${n} (pid ${R.state.pid}).`)}catch(R){console.error(`error: ${R instanceof Error?R.message:String(R)}`),process.exitCode=1}return}let x=xc(mt(Rr(y.dbPath),Yo),n);if(!x.acquired){console.error(x.message),process.exitCode=1;return}let w=new hr({projectRoot:n,config:r,languages:r.languages,onStatus:R=>{process.stdout.write(`\r\x1B[K${Gr(R)}`)},onReindexComplete:R=>{console.log(`
396
396
  Reindex complete in ${(R/1e3).toFixed(1)}s`)},onError:R=>{console.error(`
397
397
  Watch error: ${R.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.
398
- `),k.start(),process.on("SIGINT",()=>{k.stop(),x.release(),console.log(`
399
- Stopped.`),process.exit(0)}),process.once("exit",x.release)}function bp(e,t=!0){let{classification:n}=e;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}:{enabled:t,state:"stopped",mode:"none"};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,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,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};default:return cR(n)}}function Sp(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`);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: ${Wr(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}`),"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 cR(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function vp(e){let t=G(e),{report:n}=pp("status"),r=Pe(fe(n.projectRoot)).enabled,i=bp(Fr({projectRoot:n.projectRoot,cacheDir:br(n.configuredDbPath),cliVersion:Ne}),r),o=El(n.dbPath),s=nt(n.dbPath,n.freshness.metaPath),a=xn(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(b(t,"json")){I("status",[],t,{...n,affectedSetShadow:o,sqliteGeneration:s,rustSemanticSession:a,watchService:i,stats:Xi(n.exists)});return}dR(n,{affectedSetShadow:o,capabilities:b(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:i})}function lR(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})`:""}`),to(e.capabilities)}function dR(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 xp(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}${Rp(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: ${fR(e.freshness.lastRefresh)}`),Sp(t.watchService),uR(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"),pR(t.sqliteGeneration),console.log(`Shadow: ${jl(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),gR(e.exists),t.capabilities&&(console.log(""),to(e.capabilities))}function uR(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), ${Ue(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${Ue(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), ${Ue(e.cleanup.deletedBytes??0)} removed`)}function pR(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})`),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 xp(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function mR(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function Rp(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function fR(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 Xi(e){if(e)return le(t=>{let n=bt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function gR(e){e&&le(t=>{let n=bt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Ue(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function to(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(`
400
- 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 rn(e){return{...e,options:C(e.options)}}function Ie({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,...a}){let c=rn(a);return{...c,renderShape:"list",handler:uc({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s})}}function Sr({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c,...l}){let d=rn(l);return{...d,renderShape:"table",handler:pc({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c})}}function kp({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a,...c}){let l=rn(c);return{...l,renderShape:"grouped-by-file",handler:mc({commandName:l.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a})}}function wp({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=rn(a);return{...c,renderShape:"sectioned-report",handler:fc({commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}function vr({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=rn(a);return{...c,budget:c.budget??"semantic",renderShape:"sectioned-report",handler:gc(c.id,{commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}import{existsSync as JR,mkdirSync as zR,writeFileSync as KR}from"fs";import{dirname as QR,relative as YR}from"path";import{existsSync as Ge,readdirSync as xR,readFileSync as pt}from"fs";import{basename as RR,dirname as jp,isAbsolute as Lp,join as kR,relative as wR,resolve as on,sep as $R}from"path";import{spawnSync as yR}from"child_process";import{dirname as bR}from"path";function Pp(e){let n=(e.spawnSync??yR)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:bR(e.specPath),maxBuffer:1024*1024*32});if(n.status!==0)return null;let r=n.stdout??"";return r.includes("<?xml")?r:null}function Cp(e){let t=vR(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=Tp(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 SR=8;function vR(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=no(s,"uniquename"),c=no(s,"kind"),l=no(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:$p(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:$p(l),block:s})}return t}function Tp(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 f=n.get(m)??"";f==="'"?d="write-next":f==="UNCHANGED"?d="unchanged-run":d==="unchanged-run"&&f==="$Tuple"||d!=="write-next"&&(d="read");continue}if(u==="OpDeclNodeRef"){let f=t.get(m);if(!f)continue;d==="write-next"?(c.add(f),d="read"):d==="unchanged-run"||a.add(f);continue}if(u==="UserDefinedOpKindRef"){d==="unchanged-run"&&(d="read");let f=r.get(m);if(f&&s<SR&&!o.has(f.uid)&&f.filename===i){let g=Tp(f.block,t,n,r,i,new Set([...o,f.uid]),s+1);for(let h of g.reads)a.add(h);for(let h of g.writes)c.add(h)}continue}d==="unchanged-run"&&(d="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function no(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function $p(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var Ap=["update","insert","delete"],Dp=["select","query","findFirst","findMany"],ro=new Set([...Ap,...Dp]);function io(e){let t=e.methods&&e.methods.length>0?e.methods:[...ro],n=new Set(Ap),r=new Set(Dp);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var PR=/^(.*)@L(\d+)-L(\d+)$/;function oo(e){let t=e.match(PR);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 CR=new Set(["auto","sany","tlc","apalache","none"]),Rr=/^[A-Za-z_][A-Za-z0-9_]*$/;function Op(e){return CR.has(e)}function kr(e,t){let n=[],r=pe(e,t);if(!r)return{errors:[`map path escapes project root: ${t}`]};if(!Ge(r))return{errors:[`map file not found: ${t}`]};let i;try{i=JSON.parse(pt(r,"utf8"))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let o=TR(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:jp(r)},errors:n}:{errors:n}}function pe(e,t){if(!t)return null;let n=Lp(t)?on(t):on(e,t);return me(e,n)?n:null}function Np(e,t,n){if(!n)return null;if(Lp(n)){let s=on(n);return me(e,s)?s:null}let r=on(e,n);if(me(e,r)&&Ge(r))return r;let i=on(t,n);if(me(e,i)&&Ge(i))return i;let o=me(e,r)?r:i;return me(e,o)?o:null}function Fp(e,t){let n=pe(e,t);if(!n||!Ge(n))return null;let r=pt(n,"utf8");return{path:n,modelParse:"regex-fallback",text:r,variables:VR(r),operators:HR(r),actions:[]}}function Mp(e,t,n){let r=pe(e,t);if(!r||!Ge(r))return null;let i=pt(r,"utf8"),o=Cp(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function so(e,t){let n=pe(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!Ge(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let r=JSON.parse(pt(n,"utf8")),i=Array.isArray(r)?r:q(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(!q(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}o.push({action:c.action,before:q(c.before)?c.before:void 0,after:q(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 ao(e,t){let n=new Set,r=[];for(let i of t){let o=pe(e,i)??i;n.has(o)||(n.add(o),r.push(i))}return r}function TR(e,t){if(!q(e))return t.push("map file must contain a JSON object"),null;let n=DR(e.variables,t);AR(n,t);let r=qR(e.actions,n,t),i=IR(e.init,t);jR(i,r,t);let o={module:Ep(e.module,"module",t),config:Ep(e.config,"config",t),scope:J(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:J(e.invariants)??[],traces:J(e.traces)??[],unmappedWriteScope:LR(e.unmappedWriteScope,t)};return GR(e.scope,t),t.length===0?o:null}function IR(e,t){if(e===void 0)return;if(!q(e)){t.push("init must be an object when present");return}let n=J(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let r=ER(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function ER(e,t){if(e===void 0)return;if(!q(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 jR(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 LR(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 AR(e,t){xr(e,t,"alias",n=>n.aliases),xr(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),xr(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),xr(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=io(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function xr(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 DR(e,t){if(!q(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(!Rr.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!q(i)){t.push(`variables.${r} must be an object`);continue}let o=qp(i.code);if(!o||o.length===0){t.push(`variables.${r}.code must name at least one TypeScript referent`);continue}let s=J(i.aliases)??[],a=NR(i.resource,r,t),c=FR(i.statements,r,t),l=MR(i.ormCalls,r,t),d=_R(i.waive,r,t),u=OR(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 OR(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 NR(e,t,n){if(e===void 0)return;if(!q(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 FR(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(!q(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 MR(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(!q(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=J(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=>!ro.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...ro].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function _R(e,t,n){if(e===void 0)return;if(!q(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 qR(e,t,n){if(!q(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(!Rr.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!q(s)){n.push(`actions.${o} must be an object`);continue}let a=qp(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 f=oo(m);"error"in f&&n.push(`actions.${o}.code: ${f.error}`)}let c=J(s.reads)??[],l=J(s.writes)??[],d=J(s.calls)??[];for(let m of[...c,...l])r.has(m)||n.push(`actions.${o} references unknown variable: ${m}`);let u=BR(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 BR(e,t,n,r,i,o,s){if(q(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=J(e.reads)??[],l=J(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${o}.waive must list reads or writes`),Ip(o,"reads",c,i,s),Ip(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 Ip(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function VR(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();Rr.test(o)&&t.add(o)}}return[...t].sort()}function HR(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 WR=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function _p(e){if(!e||!Ge(e))return[];let t=pt(e,"utf8").replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,r=!1;for(let i of t.split(/[\s,]+/))if(i){if(WR.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&Rr.test(i)&&n.add(i)}return[...n].sort()}function Ep(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function qp(e){return typeof e=="string"?[e]:J(e)}function GR(e,t){e!==void 0&&(J(e)||t.push("scope must be an array of strings when present"))}function wr(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var UR=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function Bp(e,t){if(!Ge(t))return{status:"none"};let r=pt(t,"utf8").match(UR)?.[1],i=wR(e,t).split($R).join("/"),o=RR(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(d=>!!d)),a=jp(t);if(!Ge(a))return{status:"none"};let c=[];for(let d of xR(a)){if(!d.endsWith(".scip-tla.json"))continue;let u=kR(a,d),m;try{m=JSON.parse(pt(u,"utf8"))}catch{continue}q(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 $r(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(` ${oe(u.startLine,u.endLine)} (${u.loc} LOC) ${u.shortName}${m}`)}}}var co=20,Vp=K("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:B(t,0)||void 0,minLoc:P(n,"minLoc",1),includeTests:b(n,"includeTests"),skipBarrels:b(n,"skipBarrels"),includeMembers:b(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=Ss(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=!b(n,"onlyInternal"),d=!b(n,"onlyDead"),u=!b(n,"onlyDead")&&!b(n,"onlyInternal"),m=l?s:[],f=d?a:[],g=u?c:[],h=m.reduce((N,H)=>N+H.loc,0),y=f.reduce((N,H)=>N+H.loc,0),S=g.reduce((N,H)=>N+H.loc,0),x=b(n,"full"),k=x?m:m.slice(0,co),R=x?f:f.slice(0,co),D=x?g:g.slice(0,co),_=k.reduce((N,H)=>N+H.loc,0),z=R.reduce((N,H)=>N+H.loc,0),T=D.reduce((N,H)=>N+H.loc,0),O={total:m.length+f.length+g.length,deadCode:m.length,fileInternal:f.length,implicitUsage:g.length,loc:h+y+S};if(b(n,"json")){I("dead",t,n,{...o,shown:{deadCode:m,fileInternal:f,implicitUsage:g},shownCounts:O,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&&f.length===0&&g.length===0){E.empty("No matching dead-code symbols found.");return}m.length>0&&($r(k,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
401
- Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,_,{count:m.length,loc:h}),!x&&m.length>k.length&&console.log(`
402
- Showing top ${k.length} by LOC. Re-run with --full for the remaining ${m.length-k.length}.`)),f.length>0&&(m.length>0&&console.log(""),$r(R,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
398
+ `),w.start(),process.on("SIGINT",()=>{w.stop(),x.release(),console.log(`
399
+ Stopped.`),process.exit(0)}),process.once("exit",x.release)}function vp(e,t=!0){let{classification:n}=e;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}:{enabled:t,state:"stopped",mode:"none"};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,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,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};default:return hR(n)}}function xp(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`);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: ${Gr(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}`),"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 hR(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function Rp(e){let t=G(e),{report:n}=fp("status"),r=Ce(me(n.projectRoot)).enabled,i=vp(zr({projectRoot:n.projectRoot,cacheDir:Rr(n.configuredDbPath),cliVersion:Ne}),r),o=Ll(n.dbPath),s=it(n.dbPath,n.freshness.metaPath),a=Cn(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(b(t,"json")){I("status",[],t,{...n,affectedSetShadow:o,sqliteGeneration:s,rustSemanticSession:a,watchService:i,stats:to(n.exists)});return}bR(n,{affectedSetShadow:o,capabilities:b(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:i})}function yR(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})`:""}`),io(e.capabilities)}function bR(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 kp(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}${wp(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: ${RR(e.freshness.lastRefresh)}`),xp(t.watchService),SR(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"),vR(t.sqliteGeneration),console.log(`Shadow: ${Al(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),kR(e.exists),t.capabilities&&(console.log(""),io(e.capabilities))}function SR(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), ${Je(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${Je(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), ${Je(e.cleanup.deletedBytes??0)} removed`)}function vR(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})`),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 kp(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function xR(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function wp(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function RR(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 to(e){if(e)return ce(t=>{let n=vt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function kR(e){e&&ce(t=>{let n=vt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Je(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function io(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(`
400
+ 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 an(e){return{...e,options:P(e.options)}}function Ie({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,...a}){let c=an(a);return{...c,renderShape:"list",handler:lc({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s})}}function kr({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c,...l}){let d=an(l);return{...d,renderShape:"table",handler:dc({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c})}}function $p({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a,...c}){let l=an(c);return{...l,renderShape:"grouped-by-file",handler:uc({commandName:l.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a})}}function Cp({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=an(a);return{...c,renderShape:"sectioned-report",handler:pc({commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}function wr({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=an(a);return{...c,budget:c.budget??"semantic",renderShape:"sectioned-report",handler:mc(c.id,{commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}import{existsSync as tk,mkdirSync as nk,writeFileSync as rk}from"fs";import{dirname as ik,relative as ok}from"path";import{existsSync as Ge,readdirSync as IR,readFileSync as ft}from"fs";import{basename as jR,dirname as Ap,isAbsolute as Dp,join as ER,relative as LR,resolve as cn,sep as AR}from"path";import{spawnSync as $R}from"child_process";import{dirname as CR}from"path";function Tp(e){let n=(e.spawnSync??$R)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:CR(e.specPath),maxBuffer:1024*1024*32});if(n.status!==0)return null;let r=n.stdout??"";return r.includes("<?xml")?r:null}function Ip(e){let t=TR(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=jp(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 PR=8;function TR(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=oo(s,"uniquename"),c=oo(s,"kind"),l=oo(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:Pp(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:Pp(l),block:s})}return t}function jp(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[,p,m]of l){if(p==="BuiltInKindRef"){let f=n.get(m)??"";f==="'"?d="write-next":f==="UNCHANGED"?d="unchanged-run":d==="unchanged-run"&&f==="$Tuple"||d!=="write-next"&&(d="read");continue}if(p==="OpDeclNodeRef"){let f=t.get(m);if(!f)continue;d==="write-next"?(c.add(f),d="read"):d==="unchanged-run"||a.add(f);continue}if(p==="UserDefinedOpKindRef"){d==="unchanged-run"&&(d="read");let f=r.get(m);if(f&&s<PR&&!o.has(f.uid)&&f.filename===i){let g=jp(f.block,t,n,r,i,new Set([...o,f.uid]),s+1);for(let h of g.reads)a.add(h);for(let h of g.writes)c.add(h)}continue}d==="unchanged-run"&&(d="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function oo(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function Pp(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var Op=["update","insert","delete"],Fp=["select","query","findFirst","findMany"],so=new Set([...Op,...Fp]);function ao(e){let t=e.methods&&e.methods.length>0?e.methods:[...so],n=new Set(Op),r=new Set(Fp);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var DR=/^(.*)@L(\d+)-L(\d+)$/;function co(e){let t=e.match(DR);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 OR=new Set(["auto","sany","tlc","apalache","none"]),Cr=/^[A-Za-z_][A-Za-z0-9_]*$/;function Np(e){return OR.has(e)}function Pr(e,t){let n=[],r=ue(e,t);if(!r)return{errors:[`map path escapes project root: ${t}`]};if(!Ge(r))return{errors:[`map file not found: ${t}`]};let i;try{i=JSON.parse(ft(r,"utf8"))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let o=FR(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:Ap(r)},errors:n}:{errors:n}}function ue(e,t){if(!t)return null;let n=Dp(t)?cn(t):cn(e,t);return pe(e,n)?n:null}function Mp(e,t,n){if(!n)return null;if(Dp(n)){let s=cn(n);return pe(e,s)?s:null}let r=cn(e,n);if(pe(e,r)&&Ge(r))return r;let i=cn(t,n);if(pe(e,i)&&Ge(i))return i;let o=pe(e,r)?r:i;return pe(e,o)?o:null}function _p(e,t){let n=ue(e,t);if(!n||!Ge(n))return null;let r=ft(n,"utf8");return{path:n,modelParse:"regex-fallback",text:r,variables:QR(r),operators:YR(r),actions:[]}}function qp(e,t,n){let r=ue(e,t);if(!r||!Ge(r))return null;let i=ft(r,"utf8"),o=Ip(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function lo(e,t){let n=ue(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!Ge(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let r=JSON.parse(ft(n,"utf8")),i=Array.isArray(r)?r:q(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(!q(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}o.push({action:c.action,before:q(c.before)?c.before:void 0,after:q(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 uo(e,t){let n=new Set,r=[];for(let i of t){let o=ue(e,i)??i;n.has(o)||(n.add(o),r.push(i))}return r}function FR(e,t){if(!q(e))return t.push("map file must contain a JSON object"),null;let n=VR(e.variables,t);BR(n,t);let r=zR(e.actions,n,t),i=NR(e.init,t);_R(i,r,t);let o={module:Lp(e.module,"module",t),config:Lp(e.config,"config",t),scope:J(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:J(e.invariants)??[],traces:J(e.traces)??[],unmappedWriteScope:qR(e.unmappedWriteScope,t)};return ZR(e.scope,t),t.length===0?o:null}function NR(e,t){if(e===void 0)return;if(!q(e)){t.push("init must be an object when present");return}let n=J(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let r=MR(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function MR(e,t){if(e===void 0)return;if(!q(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 _R(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 qR(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 BR(e,t){$r(e,t,"alias",n=>n.aliases),$r(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),$r(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),$r(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=ao(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function $r(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 VR(e,t){if(!q(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(!Cr.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!q(i)){t.push(`variables.${r} must be an object`);continue}let o=Vp(i.code);if(!o||o.length===0){t.push(`variables.${r}.code must name at least one TypeScript referent`);continue}let s=J(i.aliases)??[],a=WR(i.resource,r,t),c=GR(i.statements,r,t),l=UR(i.ormCalls,r,t),d=JR(i.waive,r,t),p=HR(i.selfAlias,r,t),m=p?[...new Set([r,...s])]:[...new Set(s)];p===!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}:{},...p===!1?{selfAlias:!1}:{}}}return n}function HR(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 WR(e,t,n){if(e===void 0)return;if(!q(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 GR(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(!q(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 UR(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(!q(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=J(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=>!so.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...so].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function JR(e,t,n){if(e===void 0)return;if(!q(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 zR(e,t,n){if(!q(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(!Cr.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!q(s)){n.push(`actions.${o} must be an object`);continue}let a=Vp(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 f=co(m);"error"in f&&n.push(`actions.${o}.code: ${f.error}`)}let c=J(s.reads)??[],l=J(s.writes)??[],d=J(s.calls)??[];for(let m of[...c,...l])r.has(m)||n.push(`actions.${o} references unknown variable: ${m}`);let p=KR(s.waive,s.allowUnknown===!0,c,l,r,o,n);i[o]={code:a,reads:c,writes:l,calls:d,...p?{waive:p}:{}}}return i}function KR(e,t,n,r,i,o,s){if(q(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=J(e.reads)??[],l=J(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${o}.waive must list reads or writes`),Ep(o,"reads",c,i,s),Ep(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 Ep(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function QR(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();Cr.test(o)&&t.add(o)}}return[...t].sort()}function YR(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 XR=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function Bp(e){if(!e||!Ge(e))return[];let t=ft(e,"utf8").replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,r=!1;for(let i of t.split(/[\s,]+/))if(i){if(XR.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&Cr.test(i)&&n.add(i)}return[...n].sort()}function Lp(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function Vp(e){return typeof e=="string"?[e]:J(e)}function ZR(e,t){e!==void 0&&(J(e)||t.push("scope must be an array of strings when present"))}function Tr(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var ek=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function Hp(e,t){if(!Ge(t))return{status:"none"};let r=ft(t,"utf8").match(ek)?.[1],i=LR(e,t).split(AR).join("/"),o=jR(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(d=>!!d)),a=Ap(t);if(!Ge(a))return{status:"none"};let c=[];for(let d of IR(a)){if(!d.endsWith(".scip-tla.json"))continue;let p=ER(a,d),m;try{m=JSON.parse(ft(p,"utf8"))}catch{continue}q(m)&&typeof m.module=="string"&&s.has(m.module)&&c.push(p)}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 Ir(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((p,m)=>p+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((p,m)=>p.startLine-m.startLine);for(let p of d){let m=p.implicitUsageReason?` [implicit usage: ${p.implicitUsageReason}]`:"";console.log(` ${ie(p.startLine,p.endLine)} (${p.loc} LOC) ${p.shortName}${m}`)}}}var po=20,Wp=K("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:B(t,0)||void 0,minLoc:C(n,"minLoc",1),includeTests:b(n,"includeTests"),skipBarrels:b(n,"skipBarrels"),includeMembers:b(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=gs(e,i),s=o.symbols.filter(F=>F.kind==="dead-code"),a=o.symbols.filter(F=>F.kind==="file-internal"),c=o.symbols.filter(F=>F.kind==="implicit-usage"),l=!b(n,"onlyInternal"),d=!b(n,"onlyDead"),p=!b(n,"onlyDead")&&!b(n,"onlyInternal"),m=l?s:[],f=d?a:[],g=p?c:[],h=m.reduce((F,H)=>F+H.loc,0),y=f.reduce((F,H)=>F+H.loc,0),S=g.reduce((F,H)=>F+H.loc,0),x=b(n,"full"),w=x?m:m.slice(0,po),R=x?f:f.slice(0,po),D=x?g:g.slice(0,po),_=w.reduce((F,H)=>F+H.loc,0),z=R.reduce((F,H)=>F+H.loc,0),T=D.reduce((F,H)=>F+H.loc,0),O={total:m.length+f.length+g.length,deadCode:m.length,fileInternal:f.length,implicitUsage:g.length,loc:h+y+S};if(b(n,"json")){I("dead",t,n,{...o,shown:{deadCode:m,fileInternal:f,implicitUsage:g},shownCounts:O,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&&f.length===0&&g.length===0){j.empty("No matching dead-code symbols found.");return}m.length>0&&(Ir(w,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
401
+ Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,_,{count:m.length,loc:h}),!x&&m.length>w.length&&console.log(`
402
+ Showing top ${w.length} by LOC. Re-run with --full for the remaining ${m.length-w.length}.`)),f.length>0&&(m.length>0&&console.log(""),Ir(R,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
403
403
  single-use helper, an abstraction-in-progress, or a callback registered
404
404
  through a framework path that static analysis cannot trace (signal
405
405
  handlers, event listeners, dependency injection). NOT necessarily dead \u2014
406
406
  review case by case.`,z,{count:f.length,loc:y}),!x&&f.length>R.length&&console.log(`
407
- Showing top ${R.length} by LOC. Re-run with --full for the remaining ${f.length-R.length}.`)),g.length>0&&((m.length>0||f.length>0)&&console.log(""),$r(D,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
407
+ Showing top ${R.length} by LOC. Re-run with --full for the remaining ${f.length-R.length}.`)),g.length>0&&((m.length>0||f.length>0)&&console.log(""),Ir(D,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
408
408
  consumer that the static reference graph cannot trace. Investigation
409
409
  signals only \u2014 not deletion candidates and not counted as dead code.`,T,{count:g.length,loc:S}),!x&&g.length>D.length&&console.log(`
410
- Showing top ${D.length} by LOC. Re-run with --full for the remaining ${g.length-D.length}.`));let Z=[];l&&Z.push(`${m.length} dead code (${h} LOC)`),d&&Z.push(`${f.length} file-internal (${y} LOC)`),u&&Z.push(`${g.length} implicit usage (${S} LOC)`),console.log(`
411
- \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+f.length+g.length} symbols \u2014 ${Z.join(" + ")}`)}),Hp=ue("unused-imports",{query:({db:e,args:t,budget:n})=>ks(e,L(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
412
- ${e.length} unused import(s)`)}),Wp=hc("isolated",{query:({db:e,opts:t,budget:n})=>As(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${oe(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
413
- ${e.length} isolated symbol(s)`)}),Gp=K("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Ks(e,{scope:w(n,"scope"),minLoc:P(n,"minLoc",10),minCallees:P(n,"minCallees",6),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("extract-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return E.empty("No extraction candidates found.");Ce("extraction candidates");for(let o of i){console.log(`
410
+ Showing top ${D.length} by LOC. Re-run with --full for the remaining ${g.length-D.length}.`));let Z=[];l&&Z.push(`${m.length} dead code (${h} LOC)`),d&&Z.push(`${f.length} file-internal (${y} LOC)`),p&&Z.push(`${g.length} implicit usage (${S} LOC)`),console.log(`
411
+ \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+f.length+g.length} symbols \u2014 ${Z.join(" + ")}`)}),Gp=de("unused-imports",{query:({db:e,args:t,budget:n})=>Ss(e,L(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
412
+ ${e.length} unused import(s)`)}),Up=fc("isolated",{query:({db:e,opts:t,budget:n})=>js(e,{scope:k(t,"scope"),minLoc:C(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ie(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
413
+ ${e.length} isolated symbol(s)`)}),Jp=K("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Us(e,{scope:k(n,"scope"),minLoc:C(n,"minLoc",10),minCallees:C(n,"minCallees",6),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("extract-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return j.empty("No extraction candidates found.");Pe("extraction candidates");for(let o of i){console.log(`
414
414
  ${M(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(`
415
- ${i.length} extraction candidate(s) found.`)}),Up=K("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Qs(e,{target:B(t,0)||void 0,scope:w(n,"scope"),minConsumers:P(n,"minConsumers",1),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(b(n,"json")){I("locality-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return E.empty("No locality candidates found.");Ce("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?M(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
415
+ ${i.length} extraction candidate(s) found.`)}),zp=K("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Js(e,{target:B(t,0)||void 0,scope:k(n,"scope"),minConsumers:C(n,"minConsumers",1),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(b(n,"json")){I("locality-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return j.empty("No locality candidates found.");Pe("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?M(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
416
416
  ${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(`
417
- ${i.length} locality candidate(s) found.`)}),Jp=ue("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>ca(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
417
+ ${i.length} locality candidate(s) found.`)}),Kp=de("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>oa(e,{scope:k(t,"scope"),maxLoc:C(t,"maxLoc",15),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
418
418
  Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
419
419
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
420
- ${e.length} wrapper candidate(s).`)}),zp=ue("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>sa(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
420
+ ${e.length} wrapper candidate(s).`)}),Qp=de("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>ra(e,{scope:k(t,"scope"),maxLoc:C(t,"maxLoc",15),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
421
421
  Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
422
422
  Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
423
423
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
424
424
  Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
425
- ${e.length} passthrough candidate(s).`)}),Kp=ue("stale-abstractions",{query:({db:e,opts:t,budget:n})=>aa(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),limit:A(t,"limit",30),includeLowConfidence:b(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}] ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
425
+ ${e.length} passthrough candidate(s).`)}),Yp=de("stale-abstractions",{query:({db:e,opts:t,budget:n})=>ia(e,{scope:k(t,"scope"),minLoc:C(t,"minLoc",3),limit:A(t,"limit",30),includeLowConfidence:b(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}] ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
426
426
  ${e.reason}
427
427
  Kind: ${e.stalenessKind}; tier: ${e.actionTier}
428
428
  Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
429
- ${e.length} stale abstraction(s).`)}),Qp=Dn("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>wa(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",10),limit:A(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]}),Yp=Se("similar",{query:({db:e,args:t,opts:n,budget:r})=>{if(b(n,"plan")){let o=B(t,0),s=B(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:_s(e,o,s,{scanLimit:r.scanLimit,semantic:r.semantic})}}let i=B(t,0);return i?{mode:"target",rows:Ms(e,i,{minSimilarity:P(n,"minSimilarity",.4),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:qs(e,{minSimilarity:P(n,"minSimilarity",.4),limit:A(n,"limit",20),scope:w(n,"scope"),minCallees:P(n,"minCallees",4),crossFileOnly:b(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(`
429
+ ${e.length} stale abstraction(s).`)}),Xp=On("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>xa(e,{scope:k(t,"scope"),minLoc:C(t,"minLoc",10),limit:A(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]}),Zp=Se("similar",{query:({db:e,args:t,opts:n,budget:r})=>{if(b(n,"plan")){let o=B(t,0),s=B(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:Fs(e,o,s,{scanLimit:r.scanLimit,semantic:r.semantic})}}let i=B(t,0);return i?{mode:"target",rows:Os(e,i,{minSimilarity:C(n,"minSimilarity",.4),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Ns(e,{minSimilarity:C(n,"minSimilarity",.4),limit:A(n,"limit",20),scope:k(n,"scope"),minCallees:C(n,"minCallees",4),crossFileOnly:b(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(`
430
430
  ${Math.round(t.similarity*100)}% ${n}
431
431
  `),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}
432
432
  `),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let r of t.sharedEvidence)console.log(` ${r}`);if(t.uniqueToA.length>0){console.log(`
433
433
  Unique to A (${t.uniqueToA.length}):`);for(let r of t.uniqueToA)console.log(` ${r}`)}if(t.uniqueToB.length>0){console.log(`
434
434
  Unique to B (${t.uniqueToB.length}):`);for(let r of t.uniqueToB)console.log(` ${r}`)}console.log(`
435
- Strategy: ${t.consolidationStrategy}`);return}if(e.mode==="target"){E.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=[`
435
+ Strategy: ${t.consolidationStrategy}`);return}if(e.mode==="target"){j.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=[`
436
436
  ${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(`
437
- `)});return}E.list(e.rows,t=>`
437
+ `)});return}j.list(e.rows,t=>`
438
438
  ${Math.round(t.similarity*100)}% similar:
439
439
  A: ${t.shortNameA} (${t.fileA})
440
440
  B: ${t.shortNameB} (${t.fileB})
@@ -442,107 +442,113 @@ ${Math.round(t.similarity*100)}% similar:
442
442
  Recommendation: ${t.recommendation}
443
443
  `+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
444
444
  `:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
445
- ${e.rows.length} similar pair(s) found.`)}}),Xp=it({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Bs(e,{minSimilarity:P(n,"minSimilarity",.5),limit:A(n,"limit",20),scope:w(n,"scope"),minDeps:U(n,"minDeps"),filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{E.list(e,t=>{let n=[`
445
+ ${e.rows.length} similar pair(s) found.`)}}),em=ze({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Ms(e,{minSimilarity:C(n,"minSimilarity",.5),limit:A(n,"limit",20),scope:k(n,"scope"),minDeps:U(n,"minDeps"),filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{j.list(e,t=>{let n=[`
446
446
  ${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(`
447
447
  `)}),console.log(`
448
- ${e.length} similar pair(s) found.`)}}),Zp=it({commandName:"similar-chains",query:({db:e,opts:t})=>zs(e,{minSimilarity:P(t,"minSimilarity",.5),limit:A(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(`
448
+ ${e.length} similar pair(s) found.`)}}),tm=ze({commandName:"similar-chains",query:({db:e,opts:t})=>Gs(e,{minSimilarity:C(t,"minSimilarity",.5),limit:A(t,"limit",15),scope:k(t,"scope"),minChainLength:C(t,"minLength",3),maxChainLength:C(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(`
449
449
  \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(`
450
- ${e.length} similar chain pair(s) found.`)}}),em=Se("drift",{query:({db:e,args:t,opts:n,budget:r})=>oa(e,{scope:B(t,0),minDeviation:P(n,"minDeviation",5),semantic:r.semantic,includePatternDeviations:b(n,"patterns"),limit:A(n,"limit",50)}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),E.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"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(`
451
- `)},t=>t.file),console.log(`
452
- ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)${e.totalResults?` \u2014 showing ${e.results.length} of ${e.totalResults} (use -n to change)`:""}`)}}),tm=Se("convergence",{query:({db:e,args:t,budget:n})=>La(e,L(t,0),L(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(`
450
+ ${e.length} similar chain pair(s) found.`)}}),nm=Se("drift",{query:({db:e,args:t,opts:n,budget:r})=>na(e,{scope:B(t,0),minDeviation:C(n,"minDeviation",5),semantic:r.semantic,includePatternDeviations:b(n,"patterns"),includeArchitecture:b(n,"architecture"),limit:A(n,"limit",50)}),emptyMessage:e=>e.results.length===0&&!e.architecture?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{if(console.log(""),j.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(`
451
+ `)},t=>t.file),e.architecture){let t=e.architecture,n=t.edges.filter(r=>r.policyStatus==="undeclared").length;if(console.log(`
452
+ 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(`
453
+ ${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)`:""}`)}}),rm=Se("convergence",{query:({db:e,args:t,budget:n})=>ja(e,L(t,0),L(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(`
453
454
  ${Math.round(e.similarity*100)}% callee overlap
454
455
  `),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)
455
456
  `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
456
457
  Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
457
458
  Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
458
- Strategy: ${e.consolidationStrategy}`)}}}),nm=ue("similar-signatures",{query:({db:e,opts:t,budget:n})=>Oa(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),maxShapeFrequency:P(t,"maxShapeFrequency",12),limit:A(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
459
+ Strategy: ${e.consolidationStrategy}`)}}}),im=de("similar-signatures",{query:({db:e,opts:t,budget:n})=>Aa(e,{scope:k(t,"scope"),minLoc:C(t,"minLoc",3),maxShapeFrequency:C(t,"maxShapeFrequency",12),limit:A(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
459
460
  Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,r=e.functions.map(i=>` ${M(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
460
461
  `);return`${n}
461
462
  ${r}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
462
- ${e.length} group(s) found.`)}),rm=ue("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>ra(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),minLoc:P(t,"minLoc",3),limit:A(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
463
+ ${e.length} group(s) found.`)}),om=de("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>ea(e,{scope:k(t,"scope"),maxLoc:C(t,"maxLoc",15),minLoc:C(t,"minLoc",3),limit:A(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
463
464
  Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((r,i)=>` ${(i===0?"canonical":"duplicate").padEnd(9)} ${M(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
464
465
  `);return`${t}
465
466
  ${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>console.log(`
466
- ${e.length} group(s) found.`)}),im=ue("twin-drift",{query:({db:e,opts:t,budget:n})=>ia(e,{scope:w(t,"scope"),minSimilarity:P(t,"minSimilarity",.3),includeHomonyms:b(t,"includeHomonyms"),limit:A(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
467
+ ${e.length} group(s) found.`)}),sm=de("twin-drift",{query:({db:e,opts:t,budget:n})=>ta(e,{scope:k(t,"scope"),minSimilarity:C(t,"minSimilarity",.3),includeHomonyms:b(t,"includeHomonyms"),limit:A(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
467
468
  ${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(i=>` ${M(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
468
469
  `),r=e.firstDivergentTokens?`
469
470
  first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
470
471
  ${n}${r}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
471
- ${e.length} group(s) found.`)}),om=ue("not-implemented",{query:({db:e,opts:t,budget:n})=>ha(e,{scope:w(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
472
+ ${e.length} group(s) found.`)}),am=de("not-implemented",{query:({db:e,opts:t,budget:n})=>ma(e,{scope:k(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
472
473
  ${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
473
- ${e.length} reachable placeholder stub(s).`)}),sm=ue("decorative-checkers",{query:({db:e,opts:t,budget:n})=>ya(e,{scope:w(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(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(`
474
- ${e.length} decorative checker candidate(s).`)}),am=K("test-quality",({db:e,args:t,opts:n,budget:r})=>{let i=ba(e,{scope:w(n,"scope"),limit:A(n,"limit",30),scanLimit:r.scanLimit,rotDays:U(n,"rotDays")});if(b(n,"json")){I("test-quality",t,n,i,{analysisBudget:r.analysisBudget});return}if(Ce("test-quality findings"),i.assertionFree.length+i.skipped.length+i.mockEcho.length===0){E.empty("No test-quality findings.");return}i.assertionFree.length>0&&(console.log(`
475
- ASSERTION-FREE (${i.assertionFree.length})`),E.list(i.assertionFree,s=>` ${M(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),i.skipped.length>0&&(console.log(`
476
- SKIPPED (${i.skipped.length})`),E.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(`
477
- MOCK-ECHO (${i.mockEcho.length})`),E.list(i.mockEcho,s=>` ${M(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
478
- ${i.assertionFree.length} assertion-free, ${i.skipped.length} skipped, ${i.mockEcho.length} mock-echo.`)}),cm=it({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let r=L(t,0),i=L(t,1),o=w(n,"out")??fa(r,i),s=pe(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=ga(e,r,i,s);if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=YR(e.config.projectRoot,s);if(!b(n,"force")&&JR(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return zR(QR(s),{recursive:!0}),KR(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
474
+ ${e.length} reachable placeholder stub(s).`)}),cm=de("decorative-checkers",{query:({db:e,opts:t,budget:n})=>fa(e,{scope:k(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(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(`
475
+ ${e.length} decorative checker candidate(s).`)}),lm=K("test-quality",({db:e,args:t,opts:n,budget:r})=>{let i=ga(e,{scope:k(n,"scope"),limit:A(n,"limit",30),scanLimit:r.scanLimit,rotDays:U(n,"rotDays")});if(b(n,"json")){I("test-quality",t,n,i,{analysisBudget:r.analysisBudget});return}if(Pe("test-quality findings"),i.assertionFree.length+i.skipped.length+i.mockEcho.length===0){j.empty("No test-quality findings.");return}i.assertionFree.length>0&&(console.log(`
476
+ ASSERTION-FREE (${i.assertionFree.length})`),j.list(i.assertionFree,s=>` ${M(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),i.skipped.length>0&&(console.log(`
477
+ SKIPPED (${i.skipped.length})`),j.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(`
478
+ MOCK-ECHO (${i.mockEcho.length})`),j.list(i.mockEcho,s=>` ${M(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
479
+ ${i.assertionFree.length} assertion-free, ${i.skipped.length} skipped, ${i.mockEcho.length} mock-echo.`)}),dm=ze({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let r=L(t,0),i=L(t,1),o=k(n,"out")??ua(r,i),s=ue(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=pa(e,r,i,s);if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=ok(e.config.projectRoot,s);if(!b(n,"force")&&tk(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return nk(ik(s),{recursive:!0}),rk(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
479
480
  Wrote behavioral A/B scaffold: ${e.outPath}`),console.log(` A: ${e.a.shortName} (${M(e.a.file,e.a.startLine,e.a.startLine)})`),console.log(` B: ${e.b.shortName} (${M(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(`
480
- Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),lm=K("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=_r(e,{scope:w(n,"scope"),minLoc:P(n,"minLoc",1),maxDepth:P(n,"maxDepth",5),scanLimit:r.scanLimit}),o=Y(),s=b(n,"patch"),a=b(n,"json"),c=b(n,"verify")||s;if(s&&!b(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){I("cleanup-plan",t,n,i,{analysisBudget:r.analysisBudget});return}return E.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=Xr(i),d=c?Kr(o,i):void 0;if(a){I("cleanup-plan",t,n,{result:i,verification:d},{analysisBudget:r.analysisBudget});return}if(s){let u=Zr(d,l);if(u.length>0){for(let f of u)console.error(`error: ${f}`);process.exitCode=1;return}let m=Ec(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.
481
- `);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 f of u.entries)console.log(` ${f.file}:${f.startLine+1}-${f.endLine+1} ${f.shortName} (${f.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(`
482
- 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 f of d.checkers)console.log(` Checker: ${f}`);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 f=d.dirtyWorkingTree.slice(0,5),g=d.dirtyWorkingTree.length-f.length;console.log(` WARNING: verification ran at HEAD; ${d.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${f.join(", ")}${g>0?`, ... ${g} more`:""}`)}let u=XR(d.checkers),m=ZR(d.checkers);for(let f of d.batches)if(f.status==="verified")console.log(` Batch ${f.depth}: VERIFIED (${u})${m}`);else{console.log(` Batch ${f.depth}: FAILED${f.reason?` (${f.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let g of f.errors??[])console.log(` ${g}`)}}}),dm=K("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!b(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let r=b(t,"all"),i=U(t,"batch");if(r===(i!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=_r(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",1),maxDepth:P(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){E.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=Xr(o,{all:r,batch:i});if(s.length===0){console.error(`error: No cleanup batch ${i} exists.`),process.exitCode=1;return}let a=Y(),c=Kr(a,o),l=Zr(c,s,{allowDirty:b(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}Yr(a,s);let d=s.reduce((m,f)=>m+f.entries.length,0),u=s.reduce((m,f)=>m+f.loc,0);console.log(`Applied ${s.length} verified cleanup batch(es): ${d} symbol(s), ${u} LOC.`)});function XR(e){return e.join(", ")}function ZR(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var um=K("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=b(n,"full"),o=Sa(e,{windowCommits:P(n,"window",100),minSimilarity:U(n,"minSimilarity"),limit:A(n,"limit",30),scope:w(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic,historyMode:i?"full":"bounded"});if(b(n,"json")){I("recent-duplicates",t,n,o,{analysisBudget:r.analysisBudget});return}if(!o.available)return E.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return E.empty(`No recent re-implementations found (window: last ${o.windowCommits} commits).`);Ce("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
481
+ Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),um=K("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=Br(e,{scope:k(n,"scope"),minLoc:C(n,"minLoc",1),maxDepth:C(n,"maxDepth",5),scanLimit:r.scanLimit}),o=Y(),s=b(n,"patch"),a=b(n,"json"),c=b(n,"verify")||s;if(s&&!b(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){I("cleanup-plan",t,n,i,{analysisBudget:r.analysisBudget});return}return j.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=ti(i),d=c?Xr(o,i):void 0;if(a){I("cleanup-plan",t,n,{result:i,verification:d},{analysisBudget:r.analysisBudget});return}if(s){let p=ni(d,l);if(p.length>0){for(let f of p)console.error(`error: ${f}`);process.exitCode=1;return}let m=Dc(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.
482
+ `);for(let p of i.batches){let m=p.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${p.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${p.depth}: dead once batch ${p.depth-1} lands (cascade, ${p.loc} LOC) \u2500\u2500`;console.log(m);for(let f of p.entries)console.log(` ${f.file}:${f.startLine+1}-${f.endLine+1} ${f.shortName} (${f.loc} LOC)`);p.filesEmptied.length>0&&console.log(` -> empties: ${p.filesEmptied.join(", ")}`),console.log("")}if(i.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let p of i.blocked)console.log(` ${p.shortName} (${p.file}) blocked by ${p.blockingFiles.join(", ")}`)}if(d){if(console.log(`
483
+ 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 f of d.checkers)console.log(` Checker: ${f}`);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 f=d.dirtyWorkingTree.slice(0,5),g=d.dirtyWorkingTree.length-f.length;console.log(` WARNING: verification ran at HEAD; ${d.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${f.join(", ")}${g>0?`, ... ${g} more`:""}`)}let p=sk(d.checkers),m=ak(d.checkers);for(let f of d.batches)if(f.status==="verified")console.log(` Batch ${f.depth}: VERIFIED (${p})${m}`);else{console.log(` Batch ${f.depth}: FAILED${f.reason?` (${f.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let g of f.errors??[])console.log(` ${g}`)}}}),pm=K("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!b(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let r=b(t,"all"),i=U(t,"batch");if(r===(i!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=Br(e,{scope:k(t,"scope"),minLoc:C(t,"minLoc",1),maxDepth:C(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){j.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=Y(),c=Xr(a,o),l=ni(c,s,{allowDirty:b(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}ei(a,s);let d=s.reduce((m,f)=>m+f.entries.length,0),p=s.reduce((m,f)=>m+f.loc,0);console.log(`Applied ${s.length} verified cleanup batch(es): ${d} symbol(s), ${p} LOC.`)});function sk(e){return e.join(", ")}function ak(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var mm=K("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=b(n,"full"),o=ha(e,{windowCommits:C(n,"window",100),minSimilarity:U(n,"minSimilarity"),limit:A(n,"limit",30),scope:k(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic,historyMode:i?"full":"bounded"});if(b(n,"json")){I("recent-duplicates",t,n,o,{analysisBudget:r.analysisBudget});return}if(!o.available)return j.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return j.empty(`No recent re-implementations found (window: last ${o.windowCommits} commits).`);Pe("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
483
484
  `);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(`
484
- ${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),pm=de(({db:e,args:t,opts:n})=>{let r=b(n,"full"),i=na(e,{doc:t[0]===void 0?void 0:L(t,0),limit:A(n,"limit",20),minCoupling:P(n,"minCoupling",3),includeSnapshotExcluded:r,historyMode:r?"full":"bounded"});if(b(n,"json")){I("doc-drift",t,n,i);return}if(!i.available)return E.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return E.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);Ce("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
485
- `);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: ${Ln(u)}`)}}console.log(`
486
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),mm=ue("unused-params",{query:({db:e,opts:t,budget:n})=>pa(e,{scope:w(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName}
485
+ ${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),fm=le(({db:e,args:t,opts:n})=>{let r=b(n,"full"),i=Zs(e,{doc:t[0]===void 0?void 0:L(t,0),limit:A(n,"limit",20),minCoupling:C(n,"minCoupling",3),includeSnapshotExcluded:r,historyMode:r?"full":"bounded"});if(b(n,"json")){I("doc-drift",t,n,i);return}if(!i.available)return j.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return j.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);Pe("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
486
+ `);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 p=c.citationContexts?.[0];p&&console.log(` cited claim: ${An(p)}`)}}console.log(`
487
+ Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),gm=de("unused-params",{query:({db:e,opts:t,budget:n})=>la(e,{scope:k(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName}
487
488
  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(`
488
- ${e.length} function(s) with trailing unused parameters.`)});var fm=Se("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Vs(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{E.list(e,t=>{let n=[`
489
+ ${e.length} function(s) with trailing unused parameters.`)});var hm=Se("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>_s(e,{minSimilarity:C(n,"minSimilarity",.62),minTokens:C(n,"minTokens",8),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{j.list(e,t=>{let n=[`
489
490
  ${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(`
490
491
  `)}),console.log(`
491
- ${e.length} duplicated React component pair(s) found.`)}}),gm=Se("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Hs(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{E.list(e,t=>{let n=[`
492
+ ${e.length} duplicated React component pair(s) found.`)}}),ym=Se("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>qs(e,{minSimilarity:C(n,"minSimilarity",.45),minSharedBehaviors:C(n,"minSharedBehaviors",6),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{j.list(e,t=>{let n=[`
492
493
  ${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(`
493
494
  `)}),console.log(`
494
- ${e.length} React hook candidate pair(s) found.`)}}),hm=Se("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Ws(e,{minComponentLines:P(n,"minComponentLines",300),minFileLines:P(n,"minFileLines",800),minJsxTokens:P(n,"minJsxTokens",80),minBehaviorTokens:P(n,"minBehaviorTokens",40),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{E.list(e,t=>[`
495
+ ${e.length} React hook candidate pair(s) found.`)}}),bm=Se("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Bs(e,{minComponentLines:C(n,"minComponentLines",300),minFileLines:C(n,"minFileLines",800),minJsxTokens:C(n,"minJsxTokens",80),minBehaviorTokens:C(n,"minBehaviorTokens",40),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{j.list(e,t=>[`
495
496
  ${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(`
496
497
  `)),console.log(`
497
- ${e.length} large React component(s) found.`)}}),ym=Se("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Gs(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{E.list(e,t=>{let n=[`
498
+ ${e.length} large React component(s) found.`)}}),Sm=Se("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Vs(e,{minSimilarity:C(n,"minSimilarity",.62),minTokens:C(n,"minTokens",8),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{j.list(e,t=>{let n=[`
498
499
  ${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(`
499
500
  `)}),console.log(`
500
- ${e.length} duplicated Vue component pair(s) found.`)}}),bm=Se("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Us(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{E.list(e,t=>{let n=[`
501
+ ${e.length} duplicated Vue component pair(s) found.`)}}),vm=Se("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Hs(e,{minSimilarity:C(n,"minSimilarity",.45),minSharedBehaviors:C(n,"minSharedBehaviors",6),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{j.list(e,t=>{let n=[`
501
502
  ${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(`
502
503
  `)}),console.log(`
503
- ${e.length} Vue composable candidate pair(s) found.`)}}),Sm=Se("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Js(e,{minTotalLines:b(n,"reviewThresholds")&&yc(n,"minTotalLines")==="default"?300:P(n,"minTotalLines",800),minTemplateLines:P(n,"minTemplateLines",300),minScriptLines:P(n,"minScriptLines",300),minStyleLines:P(n,"minStyleLines",500),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{E.list(e,t=>{let n=[`
504
+ ${e.length} Vue composable candidate pair(s) found.`)}}),xm=Se("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Ws(e,{minTotalLines:b(n,"reviewThresholds")&&gc(n,"minTotalLines")==="default"?300:C(n,"minTotalLines",800),minTemplateLines:C(n,"minTemplateLines",300),minScriptLines:C(n,"minScriptLines",300),minStyleLines:C(n,"minStyleLines",500),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{j.list(e,t=>{let n=[`
504
505
  ${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(`
505
506
  `)}),console.log(`
506
- ${e.length} large Vue view pressure file(s) found.`)}});function ie(e){return{docs:$("Cleanup"),...e}}function X({heuristicLabel:e,...t}){return ie({...t,heuristic:{label:e}})}var Pr=[ie({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings",v,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:mm}),ie({id:"cleanup-plan",command:"cleanup-plan",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",v,1),p("--max-depth <n>","Maximum cascade depth",v,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:lm}),ie({id:"cleanup-apply",command:"cleanup-apply",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",v,1),p("--max-depth <n>","Maximum cascade depth",v,5),p("--verified","Required: verify the selected cleanup batch before applying it"),p("--batch <n>","Apply one batch depth",v),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:dm}),ie({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:C([p("--window <n>",'How many commits back counts as "recent"',v,100),p("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",ge),p("-n, --limit <n>","Maximum findings",v,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:um}),ie({id:"doc-drift",command:"doc-drift [doc]",description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:C([p("-n, --limit <n>","Maximum docs to report",v,20),p("--min-coupling <n>","Minimum historical co-changes to track a subject",v,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:pm}),ie({id:"dead",command:"dead [scope]",description:"Find repository-dead code, file-internal symbols, and implicit-usage signals",options:C([p("--min-loc <n>","Only show symbols >= N lines",v,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:Vp}),ie({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Hp}),ie({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum lines of code",v,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:Wp}),X({id:"similar",command:"similar [symbol] [other]",description:"Find heuristic function similarity candidates from callee fingerprints",options:C([p("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",ge,.4),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-callees <n>","Minimum callees to consider",v,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:Yp}),X({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:C([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ge,.5),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-deps <n>","Minimum dependencies to consider",v),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Xp}),X({id:"react-component-duplicates",command:"react-component-duplicates [file]",description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:C([p("--min-similarity <n>","Minimum JSX structure similarity (0-1)",ge,.62),p("--min-tokens <n>","Minimum structural tokens to consider",v,8),p("-n, --limit <n>","Number of results",v,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:fm}),X({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:C([p("--min-similarity <n>","Minimum behavior similarity (0-1)",ge,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),p("-n, --limit <n>","Number of results",v,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:gm}),X({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:C([p("--min-component-lines <n>","Minimum component lines",v,300),p("--min-file-lines <n>","Minimum file lines",v,800),p("--min-jsx-tokens <n>","Minimum JSX structure tokens",v,80),p("--min-behavior-tokens <n>","Minimum behavior tokens",v,40),p("-n, --limit <n>","Number of results",v,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:hm}),X({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:C([p("--min-similarity <n>","Minimum template similarity (0-1)",ge,.62),p("--min-tokens <n>","Minimum structural tokens to consider",v,8),p("-n, --limit <n>","Number of results",v,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:ym}),X({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:C([p("--min-similarity <n>","Minimum behavior similarity (0-1)",ge,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),p("-n, --limit <n>","Number of results",v,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:bm}),X({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:C([p("--min-total-lines <n>","Minimum total component lines",v,800),p("--min-template-lines <n>","Minimum template lines",v,300),p("--min-script-lines <n>","Minimum script lines",v,300),p("--min-style-lines <n>","Minimum style lines",v,500),p("--review-thresholds","Use lower review thresholds without changing health scoring"),p("-n, --limit <n>","Number of results",v,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:Sm}),X({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:C([p("--min-similarity <n>","Minimum chain similarity (0-1)",ge,.5),p("-n, --limit <n>","Number of results",v,15),p("-s, --scope <path>","Limit to files matching path"),p("--min-length <n>","Minimum chain length",v,3),p("--max-length <n>","Maximum chain length",v,8),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Zp}),X({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum function LOC",v,10),p("--min-callees <n>","Minimum callees to analyze",v,6),p("-n, --limit <n>","Number of results",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Gp}),X({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:C([p("-s, --scope <path>","Limit scan mode to files matching path"),p("--min-consumers <n>","Minimum consumers in scan mode",v,1),p("-n, --limit <n>","Number of results",v,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:Up}),X({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports and layer violations by default; pass --patterns for pattern deviations too",options:C([p("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",_e,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("-n, --limit <n>","Number of results",v,50),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:em}),X({id:"wrapper-candidates",command:"wrapper-candidates",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:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",v,15),p("-n, --limit <n>","Number of results",v,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:Jp}),X({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",v,15),p("-n, --limit <n>","Number of results",v,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:zp}),X({id:"stale-abstractions",command:"stale-abstractions",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:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",v,3),p("-n, --limit <n>","Number of results",v,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:Kp}),X({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",v,10),p("-n, --limit <n>","Number of results",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Qp}),ie({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:tm}),kp({id:"redundant-reexports",command:"redundant-reexports",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",v,30),p("--full","Run unbounded analysis on large indexes")],docs:$("Cleanup"),query:({db:e,opts:t})=>Aa(e,{scope:w(t,"scope"),limit:A(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
507
+ ${e.length} large Vue view pressure file(s) found.`)}});function re(e){return{docs:$("Cleanup"),...e}}function X({heuristicLabel:e,...t}){return re({...t,heuristic:{label:e}})}var jr=[re({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Maximum findings",v,30),u("--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:gm}),re({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Only include symbols >= N lines",v,1),u("--max-depth <n>","Maximum cascade depth",v,5),u("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),u("--patch","With --verify, print the compiler-verified deletion patch to stdout"),u("--json","Output as JSON for programmatic consumption"),u("--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:um}),re({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Only include symbols >= N lines",v,1),u("--max-depth <n>","Maximum cascade depth",v,5),u("--verified","Required: verify the selected cleanup batch before applying it"),u("--batch <n>","Apply one batch depth",v),u("--all","Apply every compiler-verified batch in the plan"),u("--force-dirty","Allow applying when plan files already have working-tree edits"),u("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:pm}),re({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:P([u("--window <n>",'How many commits back counts as "recent"',v,100),u("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",fe),u("-n, --limit <n>","Maximum findings",v,30),u("-s, --scope <path>","Limit to files matching path"),u("--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:mm}),re({id:"doc-drift",command:"doc-drift [doc]",description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:P([u("-n, --limit <n>","Maximum docs to report",v,20),u("--min-coupling <n>","Minimum historical co-changes to track a subject",v,3),u("--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:fm}),re({id:"dead",command:"dead [scope]",description:"Find repository-dead code, file-internal symbols, and implicit-usage signals",options:P([u("--min-loc <n>","Only show symbols >= N lines",v,1),u("--include-tests","Include definitions from test files (test references always count)"),u("--skip-barrels","Ignore refs from barrel re-export files"),u("--include-members","Include class members"),u("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),u("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query dead --min-loc 10"]),handler:Wp}),re({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Gp}),re({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum lines of code",v,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:Up}),X({id:"similar",command:"similar [symbol] [other]",description:"Find heuristic function similarity candidates from callee fingerprints",options:P([u("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",fe,.4),u("-n, --limit <n>","Number of results",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-callees <n>","Minimum callees to consider",v,4),u("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),u("--plan","Render a consolidation preview for two symbols"),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:Zp}),X({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:P([u("--min-similarity <n>","Minimum Jaccard similarity (0-1)",fe,.5),u("-n, --limit <n>","Number of results",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-deps <n>","Minimum dependencies to consider",v),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:em}),X({id:"react-component-duplicates",command:"react-component-duplicates [file]",description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:P([u("--min-similarity <n>","Minimum JSX structure similarity (0-1)",fe,.62),u("--min-tokens <n>","Minimum structural tokens to consider",v,8),u("-n, --limit <n>","Number of results",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:hm}),X({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:P([u("--min-similarity <n>","Minimum behavior similarity (0-1)",fe,.45),u("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),u("-n, --limit <n>","Number of results",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:ym}),X({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:P([u("--min-component-lines <n>","Minimum component lines",v,300),u("--min-file-lines <n>","Minimum file lines",v,800),u("--min-jsx-tokens <n>","Minimum JSX structure tokens",v,80),u("--min-behavior-tokens <n>","Minimum behavior tokens",v,40),u("-n, --limit <n>","Number of results",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:bm}),X({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:P([u("--min-similarity <n>","Minimum template similarity (0-1)",fe,.62),u("--min-tokens <n>","Minimum structural tokens to consider",v,8),u("-n, --limit <n>","Number of results",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Sm}),X({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:P([u("--min-similarity <n>","Minimum behavior similarity (0-1)",fe,.45),u("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),u("-n, --limit <n>","Number of results",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:vm}),X({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:P([u("--min-total-lines <n>","Minimum total component lines",v,800),u("--min-template-lines <n>","Minimum template lines",v,300),u("--min-script-lines <n>","Minimum script lines",v,300),u("--min-style-lines <n>","Minimum style lines",v,500),u("--review-thresholds","Use lower review thresholds without changing health scoring"),u("-n, --limit <n>","Number of results",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:xm}),X({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:P([u("--min-similarity <n>","Minimum chain similarity (0-1)",fe,.5),u("-n, --limit <n>","Number of results",v,15),u("-s, --scope <path>","Limit to files matching path"),u("--min-length <n>","Minimum chain length",v,3),u("--max-length <n>","Maximum chain length",v,8),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:tm}),X({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum function LOC",v,10),u("--min-callees <n>","Minimum callees to analyze",v,6),u("-n, --limit <n>","Number of results",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Jp}),X({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:P([u("-s, --scope <path>","Limit scan mode to files matching path"),u("--min-consumers <n>","Minimum consumers in scan mode",v,1),u("-n, --limit <n>","Number of results",v,20),u("--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:zp}),X({id:"drift",command:"drift [module]",description:"Detect drift candidates: unused imports and declared architecture violations; pass --architecture for boundary context",options:P([u("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",qe,5),u("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),u("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),u("-n, --limit <n>","Number of results",v,50),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:nm}),X({id:"wrapper-candidates",command:"wrapper-candidates",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:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC for candidates",v,15),u("-n, --limit <n>","Number of results",v,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:Kp}),X({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC for candidates",v,15),u("-n, --limit <n>","Number of results",v,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Qp}),X({id:"stale-abstractions",command:"stale-abstractions",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:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC",v,3),u("-n, --limit <n>","Number of results",v,30),u("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:Yp}),X({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC",v,10),u("-n, --limit <n>","Number of results",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Xp}),re({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:rm}),$p({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",v,30),u("--full","Run unbounded analysis on large indexes")],docs:$("Cleanup"),query:({db:e,opts:t})=>Ea(e,{scope:k(t,"scope"),limit:A(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
507
508
  barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
508
509
  Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
509
510
  Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
510
- ${e.length} redundant re-export(s).`)}),ie({id:"duplicate-bodies",command:"duplicate-bodies",description:"Find exact duplicate small-body candidates across files",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC per function body",v,15),p("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",v,3),p("-n, --limit <n>","Number of groups",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:rm}),ie({id:"twin-drift",command:"twin-drift",description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",ge,.3),p("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),p("-n, --limit <n>","Number of groups",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:im}),X({id:"not-implemented",command:"not-implemented",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:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,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:om}),X({id:"decorative-checkers",command:"decorative-checkers",description:"Decorative checker candidates: validate*/verify*/check*/assert*/is*/has* callables with no reachable failure exit anywhere in their body",options:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,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:sm}),ie({id:"test-quality",command:"test-quality",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:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings per sub-check",v,30),p("--rot-days <n>","Skips older than this many days are reported as rot",v,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:am}),ie({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",description:"Generate a behavioral A/B scaffold comparing two same-concept twins (scip-integrity-audit drill 5) \u2014 a ready-to-fill vitest file, not an auto-executor",options:C([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:cm}),ie({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC per function",v,3),p("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",v,12),p("-n, --limit <n>","Number of groups",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:nm})];var ek=de(({db:e,args:t,opts:n})=>{let r=bt(e);if(b(n,"json")){I("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: ${Ue(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),vm=[{id:"stats",command:"stats",description:"Show index statistics",options:[dc()],renderShape:"custom",docs:$("Core"),handler:ek}];var tk=Dn("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Ls(e,{limit:A(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."}),nk=de(({db:e,args:t,opts:n})=>{let r=B(t,0),i=A(n,"limit",30);if(r){let c=$s(e,r);if(b(n,"json")){I("fan-in",t,n,{mode:"symbol",symbol:r,rows:c});return}if(c.length===0)return E.empty(`No fan-in for ${r}.`);E.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let o=Cs(e,{limit:i,scope:w(n,"scope")});if(b(n,"json")){I("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));E.table(["files","symbol"],o.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),rk=de(({db:e,args:t,opts:n})=>{let r=B(t,0),i=A(n,"limit",30);if(r){let s=Ps(e,r);if(b(n,"json")){I("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return E.empty(`No fan-out for ${r}.`);E.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Ts(e,{limit:i,scope:w(n,"scope")});if(b(n,"json")){I("fan-out",t,n,{mode:"top",rows:o});return}E.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),ik=de(({db:e,args:t,opts:n})=>{let r=B(t,0),i=B(t,1),o=A(n,"limit",20);if(r&&i){let a=Is(e,r,i);if(b(n,"json")){I("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=Es(e,{limit:o,scope:w(n,"scope")});if(b(n,"json")){I("coupling",t,n,{mode:"top",rows:s});return}E.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}`))}),ok=it({commandName:"cycles",query:({db:e,opts:t})=>js(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(`
511
+ ${e.length} redundant re-export(s).`)}),re({id:"duplicate-bodies",command:"duplicate-bodies",description:"Find exact duplicate small-body candidates across files",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC per function body",v,15),u("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",v,3),u("-n, --limit <n>","Number of groups",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:om}),re({id:"twin-drift",command:"twin-drift",description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",fe,.3),u("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),u("-n, --limit <n>","Number of groups",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:sm}),X({id:"not-implemented",command:"not-implemented",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:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",v,30),u("--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:am}),X({id:"decorative-checkers",command:"decorative-checkers",description:"Decorative checker candidates: validate*/verify*/check*/assert*/is*/has* callables with no reachable failure exit anywhere in their body",options:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",v,30),u("--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:cm}),re({id:"test-quality",command:"test-quality",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:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Maximum findings per sub-check",v,30),u("--rot-days <n>","Skips older than this many days are reported as rot",v,60),u("--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:lm}),re({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",description:"Generate a behavioral A/B scaffold comparing two same-concept twins (scip-integrity-audit drill 5) \u2014 a ready-to-fill vitest file, not an auto-executor",options:P([u("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),u("--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:dm}),re({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC per function",v,3),u("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",v,12),u("-n, --limit <n>","Number of groups",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:im})];var ck=le(({db:e,args:t,opts:n})=>{let r=vt(e);if(b(n,"json")){I("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: ${Je(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Rm=[{id:"stats",command:"stats",description:"Show index statistics",options:[cc()],renderShape:"custom",docs:$("Core"),handler:ck}];var lk=On("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Is(e,{limit:A(t,"limit",20),scope:k(t,"scope"),minFanIn:C(t,"minFanIn",2),minFanOut:C(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."}),dk=le(({db:e,args:t,opts:n})=>{let r=B(t,0),i=A(n,"limit",30);if(r){let c=xs(e,r);if(b(n,"json")){I("fan-in",t,n,{mode:"symbol",symbol:r,rows:c});return}if(c.length===0)return j.empty(`No fan-in for ${r}.`);j.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let o=ks(e,{limit:i,scope:k(n,"scope")});if(b(n,"json")){I("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));j.table(["files","symbol"],o.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),uk=le(({db:e,args:t,opts:n})=>{let r=B(t,0),i=A(n,"limit",30);if(r){let s=Rs(e,r);if(b(n,"json")){I("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return j.empty(`No fan-out for ${r}.`);j.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=ws(e,{limit:i,scope:k(n,"scope")});if(b(n,"json")){I("fan-out",t,n,{mode:"top",rows:o});return}j.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),pk=le(({db:e,args:t,opts:n})=>{let r=B(t,0),i=B(t,1),o=A(n,"limit",20);if(r&&i){let a=$s(e,r,i);if(b(n,"json")){I("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=Cs(e,{limit:o,scope:k(n,"scope")});if(b(n,"json")){I("coupling",t,n,{mode:"top",rows:s});return}j.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}`))}),mk=ze({commandName:"cycles",query:({db:e,opts:t})=>Ps(e,{scope:k(t,"scope"),maxDepth:C(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(`
511
512
  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(`
512
- ${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.)`)}}),sk=it({commandName:"deep-chains",query:({db:e,opts:t})=>Ns(e,{limit:A(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(`
513
- 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("; ")}`)}}}),xm=[Sr({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[p("-n, --limit <n>","Number of results",v,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})=>vs(e,{limit:A(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",options:C([p("-n, --limit <n>","Number of results for top mode",v,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:nk},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:C([p("-n, --limit <n>","Number of results for top mode",v,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:rk},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:C([p("-n, --limit <n>","Number of results for top mode",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:ik},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-depth <n>","Bound DFS search depth",v,10)]),renderShape:"custom",docs:$("Graph"),handler:ok},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:C([p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-fan-in <n>","Minimum fan-in",v,2),p("--min-fan-out <n>","Minimum fan-out",v,2),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:$("Graph"),handler:tk},{id:"deep-chains",command:"deep-chains",description:"Find the longest condensed dependency-component chains",options:C([p("-n, --limit <n>","Number of chains to show",v,10),p("-s, --scope <path>","Limit to files matching path"),p("--min-depth <n>","Minimum chain depth",v,3),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:sk},vr({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:$("Graph"),query:({db:e,args:t,budget:n})=>Bt(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:ae(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(se(t,String(n[0])),console.log(`Symbol: ${e.shortName}
514
- `))},toJson:(e,{db:t,args:n})=>ve(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 ak=K("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=va(e,i,{semantic:r.semantic});if(b(n,"json")){I("complexity",t,n,ve(e,i,o,"complexity"),{analysisBudget:r.analysisBudget});return}if(!o)return E.empty(ae(e,i,"Symbol not found."));se(e,i),console.log(`${M(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
515
- `),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}`)}),ck=de(({db:e,args:t,opts:n})=>{let r=Da(e,{samples:P(n,"samples",50),scope:w(n,"scope")});if(b(n,"json")){I("self-audit",t,n,r);return}if(!r.available)return E.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)}%.
513
+ ${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.)`)}}),fk=ze({commandName:"architecture",query:({db:e,opts:t})=>Ts(e,{scope:k(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(`
514
+ 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(`
515
+ No declared boundary violations found.`);if(e.edges.length>0){console.log(`
516
+ 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(`
517
+ 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(`
518
+ 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)`)}}}}),gk=ze({commandName:"deep-chains",query:({db:e,opts:t})=>As(e,{limit:A(t,"limit",10),scope:k(t,"scope"),minDepth:C(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(`
519
+ 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("; ")}`)}}}),km=[kr({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[u("-n, --limit <n>","Number of results",v,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")],docs:$("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>hs(e,{limit:A(t,"limit",30),scope:k(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",options:P([u("-n, --limit <n>","Number of results for top mode",v,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:dk},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:P([u("-n, --limit <n>","Number of results for top mode",v,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:uk},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:P([u("-n, --limit <n>","Number of results for top mode",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:pk},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-depth <n>","Bound DFS search depth",v,10)]),renderShape:"custom",docs:$("Graph"),handler:mk},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",options:P([u("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",renderShape:"custom",docs:$("Graph",["scip-query architecture --json"]),handler:fk},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:P([u("-n, --limit <n>","Number of results",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-fan-in <n>","Minimum fan-in",v,2),u("--min-fan-out <n>","Minimum fan-out",v,2),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:$("Graph"),handler:lk},{id:"deep-chains",command:"deep-chains",description:"Find the longest condensed dependency-component chains",options:P([u("-n, --limit <n>","Number of chains to show",v,10),u("-s, --scope <path>","Limit to files matching path"),u("--min-depth <n>","Minimum chain depth",v,3),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:gk},wr({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:$("Graph"),query:({db:e,args:t,budget:n})=>Wt(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:se(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(oe(t,String(n[0])),console.log(`Symbol: ${e.shortName}
520
+ `))},toJson:(e,{db:t,args:n})=>ve(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 hk=K("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=ya(e,i,{semantic:r.semantic});if(b(n,"json")){I("complexity",t,n,ve(e,i,o,"complexity"),{analysisBudget:r.analysisBudget});return}if(!o)return j.empty(se(e,i,"Symbol not found."));oe(e,i),console.log(`${M(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
521
+ `),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}`)}),yk=le(({db:e,args:t,opts:n})=>{let r=La(e,{samples:C(n,"samples",50),scope:k(n,"scope")});if(b(n,"json")){I("self-audit",t,n,r);return}if(!r.available)return j.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)}%.
516
522
  `),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(`
517
- 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(", ")}`)}}),Rm=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",options:C([p("--samples <n>","Number of symbols to sample",v,50),p("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:$("Health",["scip-query self-audit --samples 100"]),handler:ck},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Health"),handler:ak}];var lk=de(({db:e,args:t,opts:n})=>{let r=L(t,0),i=Ys(e,r,{maxDepth:P(n,"maxDepth",5),scope:w(n,"scope")});if(b(n,"json")){I("affected",t,n,ve(e,r,i,"affected"));return}if(i.length===0)return E.empty(ae(e,r,"No affected symbols found."));se(e,r);let o=-1;for(let s of i)s.depth!==o&&(console.log(`
523
+ 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(", ")}`)}}),wm=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",options:P([u("--samples <n>","Number of symbols to sample",v,50),u("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:$("Health",["scip-query self-audit --samples 100"]),handler:yk},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Health"),handler:hk}];var bk=le(({db:e,args:t,opts:n})=>{let r=L(t,0),i=zs(e,r,{maxDepth:C(n,"maxDepth",5),scope:k(n,"scope")});if(b(n,"json")){I("affected",t,n,ve(e,r,i,"affected"));return}if(i.length===0)return j.empty(se(e,r,"No affected symbols found."));oe(e,r);let o=-1;for(let s of i)s.depth!==o&&(console.log(`
518
524
  \u2500\u2500 Depth ${s.depth} \u2500\u2500`),o=s.depth),console.log(` ${s.file} ${s.shortName}`);console.log(`
519
- ${i.length} affected symbol(s) across ${new Set(i.map(s=>s.file)).size} files.`)}),dk=K("co-change",({db:e,args:t,opts:n,budget:r})=>{let i=t[0]===void 0?void 0:L(t,0),o=b(n,"full"),s=Zs(e,i,{minTogether:P(n,"minTogether",4),limit:A(n,"limit",30),includeLinked:n.all===!0,scanLimit:r.scanLimit,historyMode:o?"full":"bounded"});if(b(n,"json")){I("co-change",t,n,s,{analysisBudget:r.analysisBudget});return}if(!s.available)return E.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return E.empty(i?`No co-change partners found for ${i} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);Ce("co-change candidates"),console.log(i?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
525
+ ${i.length} affected symbol(s) across ${new Set(i.map(s=>s.file)).size} files.`)}),Sk=K("co-change",({db:e,args:t,opts:n,budget:r})=>{let i=t[0]===void 0?void 0:L(t,0),o=b(n,"full"),s=Qs(e,i,{minTogether:C(n,"minTogether",4),limit:A(n,"limit",30),includeLinked:n.all===!0,scanLimit:r.scanLimit,historyMode:o?"full":"bounded"});if(b(n,"json")){I("co-change",t,n,s,{analysisBudget:r.analysisBudget});return}if(!s.available)return j.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return j.empty(i?`No co-change partners found for ${i} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);Pe("co-change candidates"),console.log(i?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
520
526
  `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
521
527
  `),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.
522
- `);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 ${uk(a.lastTogetherAt)}`),console.log(` subjects: ${pk(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
523
- ${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function uk(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function pk(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 mk=K("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=Xs(e,L(t,0),{semantic:r.semantic});if(b(n,"json")){I("change-surface",t,n,i,{analysisBudget:r.analysisBudget});return}if(!i)return E.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
524
- `),E.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${oe(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),fk=K("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=ua(e,{base:w(n,"base"),minContainment:P(n,"minContainment",.7),maxHelpers:U(n,"maxHelpers"),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("incomplete-migration",t,n,i,{analysisBudget:r.analysisBudget}),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return E.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return E.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(`
525
- No incomplete migrations detected.`);return}Ce("incomplete migration candidates");for(let o of i.findings){console.log(`
528
+ `);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 ${vk(a.lastTogetherAt)}`),console.log(` subjects: ${xk(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
529
+ ${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function vk(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function xk(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 Rk=K("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=Ks(e,L(t,0),{semantic:r.semantic});if(b(n,"json")){I("change-surface",t,n,i,{analysisBudget:r.analysisBudget});return}if(!i)return j.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
530
+ `),j.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${ie(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),kk=K("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=ca(e,{base:k(n,"base"),minContainment:C(n,"minContainment",.7),maxHelpers:U(n,"maxHelpers"),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("incomplete-migration",t,n,i,{analysisBudget:r.analysisBudget}),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return j.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return j.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(`
531
+ No incomplete migrations detected.`);return}Pe("incomplete migration candidates");for(let o of i.findings){console.log(`
526
532
  ${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(`
527
- ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function gk(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!Br.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Br.join(", ")}`),process.exit(1)),t}var hk=de(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Nn(Ht()))return;let r=b(t,"full"),i=oc(e,"diff-gate",r,{quiet:n||b(t,"json")}),o={base:w(t,"base"),minTogether:P(t,"minTogether",6),maxEchoChecks:U(t,"maxEchoChecks"),maxHelpers:U(t,"maxHelpers"),includeBaseline:b(t,"baseline"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:r?"full":"bounded",skip:gk(t.skip)},s=St(e,o),a=In(s.findings),c=Tn(s),l=Hn(e,s,{replayGate:f=>St(e,{...o,base:f})});if(l.warning&&console.error(`note: ${l.warning}`),!n&&b(t,"json")){I("diff-gate",[],t,{exitCode:a.length>0||c?1:0,...c?{gateError:"git diff unavailable - zero checks ran; the gate fails closed"}:{},advisoryFindingCount:s.findings.length-a.length,...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},...s}),(a.length>0||c)&&(process.exitCode=1);return}if(n){let{ledger:f,observed:g,now:h}=l;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(a.length===0)return;let y=$a(f,g,h),S=Pa(f,s.checksRun),x=sc(i.analysisBudget),k=[...y?[y]:[],Wt(s),...S,...x?[x]:[]];console.error(k.join(`
528
- `)),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(s.changedFiles.length===0)return E.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 d=s.attributionNotes.filter(f=>f.method==="unattributed");if(d.length>0)for(let f of[...new Set(d.map(g=>g.file))]){let g=d.filter(h=>h.file===f).length;console.log(`note: ${g} changed line-range(s) in ${f} belong to no indexed symbol`)}console.log(`Checks: ${s.checksRun.join(", ")}
529
- `);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}Ce("diff gate candidates");let u=s.rootCauseGroups?.filter(f=>f.count>1)??[];if(u.length>0){console.log(`Root-cause groups (${u.length}):`);for(let f of u){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 g=[...new Set([...f.files,...f.relatedFiles])].slice(0,6);g.length>0&&console.log(` files: ${g.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 g of f.partnerClassReasons??[])console.log(` reason: ${g}`)}f.citationKind&&console.log(` citation kind: ${f.citationKind}${f.actionTier?` (tier: ${f.actionTier})`:""}`);for(let g of f.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${Ln(g)}`);f.declaredCouplingSuggestion&&console.log(` declare coupling: ${f.declaredCouplingSuggestion.name} (${f.declaredCouplingSuggestion.reason})`),console.log(` -> ${f.remediation}`)}if(a.length===0){console.log(`
533
+ ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function wk(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!Vr.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Vr.join(", ")}`),process.exit(1)),t}var $k=le(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Mn(Jt()))return;let r=b(t,"full"),i=rc(e,"diff-gate",r,{quiet:n||b(t,"json")}),o={base:k(t,"base"),minTogether:C(t,"minTogether",6),maxEchoChecks:U(t,"maxEchoChecks"),maxHelpers:U(t,"maxHelpers"),includeBaseline:b(t,"baseline"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:r?"full":"bounded",skip:wk(t.skip)},s=xt(e,o),a=jn(s.findings),c=In(s),l=Gn(e,s,{replayGate:f=>xt(e,{...o,base:f})});if(l.warning&&console.error(`note: ${l.warning}`),!n&&b(t,"json")){I("diff-gate",[],t,{exitCode:a.length>0||c?1:0,...c?{gateError:"git diff unavailable - zero checks ran; the gate fails closed"}:{},advisoryFindingCount:s.findings.length-a.length,...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},...s}),(a.length>0||c)&&(process.exitCode=1);return}if(n){let{ledger:f,observed:g,now:h}=l;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(a.length===0)return;let y=ka(f,g,h),S=wa(f,s.checksRun),x=ic(i.analysisBudget),w=[...y?[y]:[],zt(s),...S,...x?[x]:[]];console.error(w.join(`
534
+ `)),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(s.changedFiles.length===0)return j.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 d=s.attributionNotes.filter(f=>f.method==="unattributed");if(d.length>0)for(let f of[...new Set(d.map(g=>g.file))]){let g=d.filter(h=>h.file===f).length;console.log(`note: ${g} changed line-range(s) in ${f} belong to no indexed symbol`)}console.log(`Checks: ${s.checksRun.join(", ")}
535
+ `);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}Pe("diff gate candidates");let p=s.rootCauseGroups?.filter(f=>f.count>1)??[];if(p.length>0){console.log(`Root-cause groups (${p.length}):`);for(let f of p){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 g=[...new Set([...f.files,...f.relatedFiles])].slice(0,6);g.length>0&&console.log(` files: ${g.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 g of f.partnerClassReasons??[])console.log(` reason: ${g}`)}f.citationKind&&console.log(` citation kind: ${f.citationKind}${f.actionTier?` (tier: ${f.actionTier})`:""}`);for(let g of f.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${An(g)}`);f.declaredCouplingSuggestion&&console.log(` declare coupling: ${f.declaredCouplingSuggestion.name} (${f.declaredCouplingSuggestion.reason})`),console.log(` -> ${f.remediation}`)}if(a.length===0){console.log(`
530
536
  PASS (advisory only): ${s.findings.length} advisory finding(s) recorded \u2014 none block this diff.`);return}let m=s.findings.length-a.length;console.log(`
531
- FAIL: ${a.length} finding(s)${m>0?` (+${m} advisory)`:""}, ${s.rootCauseGroups?.length??s.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),km=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:C([p("--max-depth <n>","Maximum traversal depth",v,5),p("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:$("Impact"),handler:lk},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:$("Impact"),handler:mk},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, incomplete migrations, missing co-change partners, unedited twin partners (advisory), uncited doc updates, unused params, new dead symbols; 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",v,6),p("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",v),p("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",v),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, doc-reference, unused-params, new-dead, baseline",rt,[]),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")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:$("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:hk},{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",options:C([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)",ge,.7),p("--max-helpers <n>","Maximum new helpers to score (default: all)",v),p("-n, --limit <n>","Maximum findings to report",v,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:fk},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:C([p("--min-together <n>","Minimum commits where both files changed",v,4),p("-n, --limit <n>","Maximum pairs to report",v,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:dk}];function yk(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${M(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
532
- `).map((s,a)=>` ${Me(i.startLine+a)} ${s}`).join(`
533
- `))}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 ${Me(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var bk=ue("imports",{query:({db:e,args:t,budget:n})=>xs(e,L(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)."}),Sk=K("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=xa(e,i,{semantic:r.semantic});if(b(n,"json")){I("dataflow",t,n,ve(e,i,o,"dataflow"),{analysisBudget:r.analysisBudget});return}if(!o)return E.empty(ae(e,i,"No dataflow found."));if(se(e,i),console.log(`${o.shortName} (${o.relativePath})
534
- `),o.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of o.definitionSites)console.log(` ${s.file}:${Me(s.line)}`)}if(o.usageSites.length>0){console.log(`
535
- \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of o.usageSites)console.log(` ${s.file}:${Me(s.line)} in ${s.enclosingShort}`)}if(o.producers.length>0){console.log(`
537
+ FAIL: ${a.length} finding(s)${m>0?` (+${m} advisory)`:""}, ${s.rootCauseGroups?.length??s.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),$m=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:P([u("--max-depth <n>","Maximum traversal depth",v,5),u("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:$("Impact"),handler:bk},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:$("Impact"),handler:Rk},{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:[u("--base <ref>","Git ref to diff against (default: HEAD)"),u("--min-together <n>","Minimum historical co-changes for the partner check",v,6),u("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",v),u("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",v),u("--baseline","Also run the full health-baseline ratchet"),u("--full","Run unbounded semantic and git-history analysis on large indexes"),u("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, twin-partner, coverage-contract, architecture, doc-reference, unused-params, new-dead, baseline",ot,[]),u("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),u("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:$("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:$k},{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",options:P([u("--base <ref>","Git ref to diff against (default: HEAD)"),u("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",fe,.7),u("--max-helpers <n>","Maximum new helpers to score (default: all)",v),u("-n, --limit <n>","Maximum findings to report",v,20),u("--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:kk},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:P([u("--min-together <n>","Minimum commits where both files changed",v,4),u("-n, --limit <n>","Maximum pairs to report",v,30),u("--all","Include pairs that already have a dependency edge"),u("--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:Sk}];function Ck(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${M(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
538
+ `).map((s,a)=>` ${_e(i.startLine+a)} ${s}`).join(`
539
+ `))}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 ${_e(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var Pk=de("imports",{query:({db:e,args:t,budget:n})=>ys(e,L(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)."}),Tk=K("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=ba(e,i,{semantic:r.semantic});if(b(n,"json")){I("dataflow",t,n,ve(e,i,o,"dataflow"),{analysisBudget:r.analysisBudget});return}if(!o)return j.empty(se(e,i,"No dataflow found."));if(oe(e,i),console.log(`${o.shortName} (${o.relativePath})
540
+ `),o.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of o.definitionSites)console.log(` ${s.file}:${_e(s.line)}`)}if(o.usageSites.length>0){console.log(`
541
+ \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of o.usageSites)console.log(` ${s.file}:${_e(s.line)} in ${s.enclosingShort}`)}if(o.producers.length>0){console.log(`
536
542
  \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(`
537
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),vk=K("slice",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=b(n,"forward")?"forward":"backward",s=Ra(e,i,{direction:o,maxDepth:P(n,"depth",3),semantic:r.semantic});if(b(n,"json")){I("slice",t,n,ve(e,i,s,"slice"),{analysisBudget:r.analysisBudget});return}if(!s)return E.empty(ae(e,i,"No slice found."));if(se(e,i),console.log(`${s.direction} slice of ${s.shortName}
538
- `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}E.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
543
+ \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),Ik=K("slice",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=b(n,"forward")?"forward":"backward",s=Sa(e,i,{direction:o,maxDepth:C(n,"depth",3),semantic:r.semantic});if(b(n,"json")){I("slice",t,n,ve(e,i,s,"slice"),{analysisBudget:r.analysisBudget});return}if(!s)return j.empty(se(e,i,"No slice found."));if(oe(e,i),console.log(`${s.direction} slice of ${s.shortName}
544
+ `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}j.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
539
545
  ${a.relationship}`),console.log(`
540
- ${s.connectedSymbols.length} connected symbol(s).`)}),wm=[...Sc,Ie({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:$("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>ps(e,L(t,0)),format:e=>e.relativePath}),Ie({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:$("Navigation"),query:({db:e,args:t})=>ms(e,L(t,0)),format:e=>` ${oe(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")],budget:"semantic",docs:$("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>fs(e,L(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?ae(t,L(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>se(t,L(n,0)),toJson:(e,{db:t,args:n})=>({...Vt(t,L(n,0)),...e}),sections:yk}),Ie({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:$("Navigation"),query:({db:e,args:t})=>gs(e,L(t,0)),format:e=>e.relativePath}),Ie({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:$("Navigation"),query:({db:e,args:t})=>hs(e,L(t,0)),format:e=>e.relativePath}),wp({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:$("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>ys(e,L(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${oe(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}`)}]}),Ie({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:$("Navigation"),query:({db:e,args:t})=>bs(e,L(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",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:bk},Ie({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:$("Navigation"),query:({db:e,args:t})=>Rs(e,L(t,0)),format:e=>` ${e.fromFile}`}),Ie({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:$("Navigation"),query:({db:e,args:t})=>ws(e,L(t,0)),format:e=>` ${oe(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>se(t,L(n,0)),emptyMessage:({db:e,args:t})=>ae(e,L(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>ve(t,L(n,0),e,"members")}),Ie({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,100),p("--full","Run unbounded analysis on large indexes")],docs:$("Navigation"),query:({db:e,args:t,opts:n})=>Ds(e,L(t,0),{scope:w(n,"scope"),limit:A(n,"limit",100)}),format:e=>` ${M(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${L(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
541
- ${e.length} symbol(s)`)}),Sr({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[p("-s, --scope <path>","Limit to files matching path")],docs:$("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>Os(e,{scope:w(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Ie({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:$("Navigation"),query:({db:e,args:t})=>Fs(e,L(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>se(t,L(n,0)),emptyMessage:({db:e,args:t})=>ae(e,L(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>ve(t,L(n,0),e,"hierarchy")}),{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:Sk},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:C([p("--forward","Forward slice (what does this affect). Default is backward."),p("--depth <n>","Max transitive depth for backward slice",v,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:vk}];var xk=K("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=A(n,"limit",20),o=Fe(e.config.projectRoot).gitContext?.headCommit,s=ka(e,L(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(b(n,"json")){I("plan-context",t,n,{...Vt(e,L(t,0)),...s},{analysisBudget:r.analysisBudget});return}return E.empty(ae(e,L(t,0)))}if(b(n,"json")){I("plan-context",t,n,s.matched.symbol?{...Vt(e,L(t,0)),...s}:s,{analysisBudget:r.analysisBudget});return}s.matched.symbol&&se(e,L(t,0));let a=[{title:"TARGET",rows:Rk(s)},{title:"DEFINITIONS",rows:kk(s,i),skipIfEmpty:!0},{title:"REFERENCES",rows:wk(s,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:$k(s,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:Pk(s,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:Ck(s,i),skipIfEmpty:!0},{title:"SURFACE",rows:Tk(s,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:Ik(s,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:Ek(s,i),skipIfEmpty:!0},{title:"HISTORY",rows:jk(s),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:Lk(s),skipIfEmpty:!0}];E.sectionedReport(a)}),$m=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:C([p("--impact-depth <n>","Maximum affected traversal depth",v,3),p("--slice-depth <n>","Maximum backward slice depth",v,3),p("-s, --scope <path>","Limit downstream impact to files matching path"),p("-n, --limit <n>","Rows per section",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Planning",["scip-query plan-context parseSymbol"]),handler:xk}];function Rk(e){return[`Target: ${e.target}`,`Matched: symbol=${lo(e.matched.symbol)} file=${lo(e.matched.file)} module=${lo(e.matched.module)}`]}function kk(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${M(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
542
- `).map((o,s)=>` ${String(Me(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${oe(r.startLine,r.endLine)} ${r.shortName}`)),Ze(n,t).rows}function wk(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${Me(r.line)} in ${r.enclosingShort}`);return mt(Ze(n,t))}function $k(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 mt(Ze([...n,...r],t))}function Pk(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}:${Me(o.line)} in ${o.enclosingShort}`);return mt(Ze([...n,...r,...i],t))}function Ck(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 mt(Ze(n,t))}function Tk(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${oe(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return mt(Ze(n,t))}function Ik(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 mt(Ze(n,t))}function Ek(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` ${oe(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${M(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}`)),mt(Ze(n,t))}function jk(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 Lk(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 Ze(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function mt(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function lo(e){return e?"yes":"no"}import{existsSync as ln}from"fs";import{existsSync as Bk,mkdtempSync as Vk,rmSync as Hk}from"fs";import{tmpdir as Wk}from"os";import{dirname as po,join as mo}from"path";import{performance as Im}from"perf_hooks";import{spawnSync as Gk}from"child_process";import{createHash as Ak}from"crypto";import{existsSync as Dk,mkdirSync as Ok,readFileSync as Nk,renameSync as Fk,writeFileSync as Mk}from"fs";import{homedir as _k}from"os";import{dirname as qk,join as uo}from"path";function Pm(e){return Ak("sha256").update(e).digest("hex")}function Cm(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?uo(t.XDG_CACHE_HOME,"scip-query"):uo(_k(),".cache","scip-query"));return uo(n,e)}async function Tm(e){let{cachePath:t,url:n,expectedSha256:r}=e;if(Dk(t)){let l=Pm(Nk(t));if(l===r)return{status:"cached",path:t,sha256:l}}let o=await(e.fetchImpl??fetch)(n);if(!o.ok)throw new Error(`failed to download ${n}: HTTP ${o.status}`);let s=Buffer.from(await o.arrayBuffer()),a=Pm(s);if(a!==r)throw new Error(`downloaded ${n} checksum mismatch: expected ${r}, got ${a}`);Ok(qk(t),{recursive:!0});let c=`${t}.tmp-${process.pid}`;return Mk(c,s),Fk(c,t),{status:"downloaded",path:t,sha256:a}}var Uk=12e4,Lm="v1.8.0",Jk=`https://github.com/tlaplus/tlaplus/releases/download/${Lm}/tla2tools.jar`,zk="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Tr(e){let t=e.spawn??Gk,n=Kk(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??Uk,i=Im.now(),o;try{o=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:r,maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])Hk(l,{recursive:!0,force:!0})}let s=Math.round(Im.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:Qk(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function Kk(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"&&qe(Em(e),t)){let o=Em(e);return qe(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:po(e.specPath)}:Cr("apalache",`Apalache binary is not available: ${o}`)}let r=fo(e),i=qe("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return Cr(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return Cr(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:po(e.specPath)};let s=e.metaDir??Vk(mo(Wk(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:po(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Cr("none",`unknown checker mode: ${n}`)}function Em(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function fo(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Am(t),mo(e.projectRoot,"tla2tools.jar"),mo(e.projectRoot,"tools","tla2tools.jar")].filter(r=>typeof r=="string"&&r.length>0).find(r=>Bk(r))??null}function Am(e=process.env){return Cm("tla2tools.jar",e)}async function Dm(e={}){let t=e.cachePath??Am(e.env),n=e.expectedSha256??zk,r=e.version??Lm,i=e.url??Jk;return{...await Tm({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl}),version:r,url:i}}function Qk(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=[...jm(n),...jm(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function jm(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Cr(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as Yk}from"crypto";import{readFileSync as Nm}from"fs";import{join as Fm}from"path";var Mm=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),_m=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),qm=new Set(["readFileSync","existsSync","statSync"]),Xk=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,Zk=/^\s*SELECT\b/i;function Bm(e){return Xk.test(e)?"write":Zk.test(e)?"read":null}var ew=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function tw(e,t){let n=e.match(ew);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${Le(t)}\\b`).test(r)}function Vm(e,t,n,r=[],i=[]){let o=[],s=iw(e,t,o),a=s.aliases,c=ow(t),l=sw(t),d=aw(t),u=dw(e,t,o),m=pw(e,t,o);n&&mw(t,n,i,o);let f=new Map((n?.actions??[]).map(x=>[x.name,x])),g=new Set(u.flatMap(x=>x.referents.map(k=>k.match?.symbol).filter(Boolean))),h=new Set((m?.referents??[]).map(x=>x.match?.symbol).filter(Boolean)),y=fw(e,t,u,a,c,l,d,g,h,o,f),S=yw(e,u,a,c,l,d,o,f);return Sw(e,u,o),vw(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:ho(u.flatMap(x=>x.referents))+ho(s.referents)+ho(m?.referents??[]),staticWrites:y,staticReads:S,waivers:qw(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:nw(o)}}function nw(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=rw(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||Ir(r.severity)-Ir(n.severity)||n.groupKey.localeCompare(r.groupKey))}function rw(e,t){return Ir(t)>Ir(e)?t:e}function Ir(e){return e==="error"?2:e==="warning"?1:0}function iw(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=Lr(e,l,n,o);i.push(d);let u=d.match;if(!u){c||n.push(W("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}Dw(e,o,l,u,n,c),s.aliases.length===0&&a.add(Lo(u.symbol))}for(let l of a)r.push({variable:o,alias:l})}return{aliases:_w(r),referents:i}}function ow(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 sw(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 aw(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=io(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function cw(e,t,n,r,i,o){return Hm(e,t,(s,a,c)=>ft(e,s,a,c,n,r,i,o))}function lw(e,t,n,r,i,o){return Hm(e,t,(s,a,c)=>jr(e,s,a,c,n,r,i,o))}function Hm(e,t,n){let r=Bt(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=yn(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 dw(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=oo(s),c="error"in a?s:a.ref,d=Lr(e,c,n,r).match;return d?(Ow(e,r,s,d,n),"error"in a||!a.window?{ref:s,match:d}:uw(a.window,d)?(n.push(W("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 ${Q(d.symbol)}'s actual span L${d.startLine+1}-L${d.endLine+1} in ${d.relativePath}.`,why:[`${s} resolves to ${Q(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(W("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 uw(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function pw(e,t,n){let r=t.init;if(!r)return;let i=!!r.waive,o=r.codeRefs.map(s=>{let a=Lr(e,s,n,"Init"),c=a.match;return c?Nw(e,s,c,n,i):i||n.push(W("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 mw(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(W("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(W("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&&(Om({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)}),Om({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(W("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 Om(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(W(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(W(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 fw(e,t,n,r,i,o,s,a,c,l,d){let u=[];for(let f of n){let g=[];for(let h of f.referents){if(!h.match)continue;let y=h.window??{startLine:h.match.startLine,endLine:h.match.endLine},S=ft(e,h.match.relativePath,y.startLine,y.endLine,r,i,o,s);g.push(...S),u.push(...S);let x=new Set(f.mapping.writes),k=cw(e,h.match.symbol,r,i,o,s).filter(R=>x.has(R.variable));g.push(...k),u.push(...k)}hw(f,g,l,d.get(f.name))}let m=t.unmappedWriteScope==="actions"?[]:jw(e,t);for(let f of m)for(let g of ft(e,f,0,Number.POSITIVE_INFINITY,r,i,o,s))u.push(g),gw(g)&&(g.enclosingSymbol&&(a.has(g.enclosingSymbol)||c.has(g.enclosingSymbol))||l.push(W("unmapped-write","error","static-action",{modelElement:g.variable,codeRef:g.enclosingSymbol??`${g.file}:${g.line+1}`,file:g.file,startLine:g.line,endLine:g.line,message:`Modeled variable ${g.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${g.target} at ${g.file}:${g.line+1}.`,g.enclosingShort?`The write is inside ${g.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 ${g.variable} from the modeled slice if it is intentionally out of scope.`})));return So(u)}function gw(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function hw(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)&&!an(e,"write",a.variable)&&n.push(W("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}${Er(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)&&!an(e,"write",a.variable)&&n.push(W("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}${Er(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)&&!an(e,"write",a)&&n.push(W("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 yw(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},f=jr(e,u.match.relativePath,m.startLine,m.endLine,n,r,i,o);d.push(...f),c.push(...f);let g=new Set(l.mapping.reads),h=lw(e,u.match.symbol,n,r,i,o).filter(y=>g.has(y.variable));d.push(...h),c.push(...h)}bw(l,d,s,a.get(l.name))}return vo(c)}function bw(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(W("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}${Er(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)&&!an(e,"read",a.variable)&&n.push(W("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}${Er(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)&&!an(e,"read",a)&&n.push(W("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 Sw(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>Lr(e,s,n,r.name));for(let s of i)s.match||n.push(W("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=Bt(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of o)c.has(l)||n.push(W("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 ${Q(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 vw(e,t,n){for(let[r,i]of t.entries()){let o=e.actions[i.action];if(!o){n.push(W("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=Mw(i),a=new Set(o.writes);for(let c of s)a.has(c)||n.push(W("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 ft(e,t,n,r,i,o=[],s=[],a=[]){let c=xw(e,t,n,r,i,o,s,a);return c||Iw(e,t,n,r,i,o,s,a)}function jr(e,t,n,r,i,o=[],s=[],a=[]){let c=Rw(e,t,n,r,i,o,s,a);return c||Ew(e,t,n,r,i,o,s,a)}function xw(e,t,n,r,i,o=[],s=[],a=[]){let c=Or(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){kw(e,t,u,i,l),Wm(e,t,u,o,"write",l),Gm(e,t,u,s,"write",l),Um(e,t,u,a,"write",l);for(let m of u.children)d(m)}};return d(c.rootNode),So(l)}function Rw(e,t,n,r,i,o=[],s=[],a=[]){let c=Or(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){Pw(e,t,u,i,l),Wm(e,t,u,o,"read",l),Gm(e,t,u,s,"read",l),Um(e,t,u,a,"read",l);for(let m of u.children)d(m)}};return d(c.rootNode),vo(l)}function kw(e,t,n,r,i){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&sn(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&&sn(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&&sn(e,t,o,"update",r,i);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&sn(e,t,o,"delete",r,i);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!zm(o))return;sn(e,t,o,"mutation-call",r,i)}}}function Wm(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?yo(s):null;if(!a||!(i==="write"?_m:qm).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 f=Ee(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:f?.symbol,enclosingShort:f?Q(f.symbol):void 0})}}function yo(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 Gm(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=ww(a);if(c!==null&&Bm(c)===i)for(let l of r){if(!l.regex.test(c))continue;let d=Ee(e,t,n.startPosition.row),u=n.childForFieldName("function")??n.namedChild(0),m=(u&&yo(u))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${m}(${$w(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?Q(d.symbol):void 0})}}}function ww(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function $w(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function Um(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?yo(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(!Jm(u,a,d,i))continue;let m=Ee(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?Q(m.symbol):void 0})}}function Jm(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 Pw(e,t,n,r,i){if(!(!Cw(n)||Tw(n)))for(let o of r){if(n.text!==o.alias)continue;let s=Ee(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?Q(s.symbol):void 0})}}function Cw(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function Tw(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&&go(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&&go(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&zm(n)&&go(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 go(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function zm(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&Mm.has(t.text))}function sn(e,t,n,r,i,o){for(let s of i){if(!Fw(s.alias,n.text))continue;let a=Ee(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?Q(a.symbol):void 0})}}function Iw(e,t,n,r,i,o=[],s=[],a=[]){let l=Nm(Fm(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 f=l[m]??"";for(let g of i){if(tw(f,g.alias))continue;let h=Le(g.alias);if(!new RegExp(`(?:\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${h}\\b\\s*\\.\\s*(?:${[...Mm].join("|")})\\s*\\(|\\b${h}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(f))continue;let S=Ee(e,t,m);d.push({variable:g.variable,alias:g.alias,file:t,line:m,target:f.trim(),kind:"source-scan",enclosingSymbol:S?.symbol,enclosingShort:S?Q(S.symbol):void 0})}Km(e,t,m,f,o,_m,d),Qm(e,t,m,f,s,"write",d),Ym(e,t,m,f,a,"write",d)}return So(d)}function Ew(e,t,n,r,i,o=[],s=[],a=[]){let l=Nm(Fm(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 f=l[m]??"";for(let g of i){let h=Le(g.alias);if(!new RegExp(`\\b${h}\\b`).test(f)||new RegExp(`\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(f))continue;let y=Ee(e,t,m);d.push({variable:g.variable,alias:g.alias,file:t,line:m,target:f.trim(),kind:"source-scan",enclosingSymbol:y?.symbol,enclosingShort:y?Q(y.symbol):void 0})}Km(e,t,m,f,o,qm,d),Qm(e,t,m,f,s,"read",d),Ym(e,t,m,f,a,"read",d)}return vo(d)}function Km(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=Ee(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?Q(u.symbol):void 0})}}}function Qm(e,t,n,r,i,o,s){if(i.length!==0&&Bm(r)===o)for(let a of i){if(!a.regex.test(r))continue;let c=Ee(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?Q(c.symbol):void 0})}}function Ym(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(!Jm(d,c,l,o))continue;let u=Ee(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?Q(u.symbol):void 0})}}}function jw(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 Lr(e,t,n,r){let i=yn(e,t),o=i.match??(t.includes("#")?yn(e,t.replace("#","/")).match:null);return i.match&&i.total>1&&!Lw(t)&&n.push(W("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 ${Q(i.match.symbol)}.`,why:[`${i.total} indexed definitions share this lookup shape.`,Aw(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 Lw(e){return/[/#:]/.test(e)}function Aw(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function Dw(e,t,n,r,i,o=!1){let s=bo(e,r);if(s===null||Bw.has(s)||o)return;let a=xo.has(s);i.push(W("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 ${qt(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${Q(r.symbol)} with SCIP kind ${qt(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function Ow(e,t,n,r,i){let o=bo(e,r);o===null||Xm.has(o)||xo.has(o)&&i.push(W("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 ${Q(r.symbol)} with SCIP kind ${qt(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function Nw(e,t,n,r,i){let o=bo(e,n);o===null||Xm.has(o)||i||xo.has(o)&&r.push(W("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 ${Q(n.symbol)} with SCIP kind ${qt(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function bo(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function Ee(e,t,n){return hn(e,t).filter(i=>i.startLine<=n&&i.endLine>=n).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine))[0]??null}function Fw(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Le(e)}([^A-Za-z0-9_$]|$)`).test(t)}function Mw(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 So(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 vo(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 _w(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 ho(e){return e.filter(t=>t.match).length}function Er(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function an(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function qw(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 xo=new Set(ds()),Xm=new Set(ls()),Bw=new Set(us());function W(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${Yk("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{readFileSync as Vw}from"fs";import{basename as Hw,join as Zm}from"path";var Ro=/^[A-Za-z_][A-Za-z0-9_]*$/;function ef(e,t,n={}){let r=[],i=hn(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=Vw(Zm(e.config.projectRoot,t),"utf8").split(/\r?\n/),a=T=>T.symbol.trimEnd().endsWith("()."),c=i.filter(T=>!a(T)&&!T.isTypeLike&&T.parentTypeName===null&&Ro.test(T.leaf)),l=c.map(T=>({variable:T.leaf,alias:T.leaf})),d=l.length>0?ft(e,t,0,Number.POSITIVE_INFINITY,l):[],u=new Set(d.map(T=>T.variable)),m=c.filter(T=>u.has(T.leaf)?!0:Uw(s,T)),f=null,g;if(m.length>0)g=i.filter(T=>a(T)&&T.parentTypeName===null);else{if(f=Ww(e,t,i,a),!f){let T=i.some(O=>!a(O)&&!O.isTypeLike&&O.parentTypeName!==null&&Ro.test(O.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 `+(T?"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=f.fields,g=f.methods,r.push(`state scoped to class ${f.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(T=>Jw(T,s,t,r,f?.className)),y=h.map(T=>({variable:T.name,alias:T.leaf})),S=[],x=new Set;for(let T of g){let O=ft(e,t,T.startLine,T.endLine,y);if(O.length===0)continue;let Z=jr(e,t,T.startLine,T.endLine,y),N=Yw(tf(T.leaf),x);S.push({name:N,leaf:T.leaf,codeRef:Gw(t,T,f?.className),startLine:T.startLine,writes:[...new Set(O.map(H=>H.variable))].sort(),reads:[...new Set(Z.map(H=>H.variable))].sort()})}S.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 k=n.moduleName??Xw(t),R=n.specDir??Zm("specs",k),D=Zw(k,h,S,t),_=e$(),z=t$(k,R,t,h,S);return{moduleName:k,file:t,variables:h,actions:S,warnings:r,spec:D,cfg:_,map:z}}function Ww(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!Ro.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 f of ft(e,t,m.startLine,m.endLine,l))d.add(f.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 Gw(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function Uw(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function Jw(e,t,n,r,i){let o=zw(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=Kw(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 zw(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function Kw(e,t){let r=t.match(new RegExp(`\\b${n$(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=Qw(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 Qw(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 tf(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function Yw(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function Xw(e){let n=Hw(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return tf(n||"Model")}function Zw(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(`
543
- `)}function e$(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
544
- `)}function t$(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)}
545
- `}function n$(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nf(e,t){let n=Object.keys(t.variables),r=Object.entries(t.actions).map(([i,o])=>{let s=o.code[0]??"",a=s?Do(e,s):null;return{action:i,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:r$(n),wiring:r,variables:n}}function r$(e){return`/**
546
+ ${s.connectedSymbols.length} connected symbol(s).`)}),Cm=[...yc,Ie({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:$("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>cs(e,L(t,0)),format:e=>e.relativePath}),Ie({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:$("Navigation"),query:({db:e,args:t})=>ls(e,L(t,0)),format:e=>` ${ie(e.startLine,e.endLine)} ${e.name}`}),wr({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:$("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>ds(e,L(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?se(t,L(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>oe(t,L(n,0)),toJson:(e,{db:t,args:n})=>({...Ut(t,L(n,0)),...e}),sections:Ck}),Ie({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:$("Navigation"),query:({db:e,args:t})=>us(e,L(t,0)),format:e=>e.relativePath}),Ie({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:$("Navigation"),query:({db:e,args:t})=>ps(e,L(t,0)),format:e=>e.relativePath}),Cp({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:$("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>ms(e,L(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${ie(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}`)}]}),Ie({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:$("Navigation"),query:({db:e,args:t})=>fs(e,L(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[u("--full","Run unbounded semantic analysis on large indexes"),u("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:$("Navigation"),handler:Pk},Ie({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:$("Navigation"),query:({db:e,args:t})=>bs(e,L(t,0)),format:e=>` ${e.fromFile}`}),Ie({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:$("Navigation"),query:({db:e,args:t})=>vs(e,L(t,0)),format:e=>` ${ie(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>oe(t,L(n,0)),emptyMessage:({db:e,args:t})=>se(e,L(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>ve(t,L(n,0),e,"members")}),Ie({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",v,100),u("--full","Run unbounded analysis on large indexes")],docs:$("Navigation"),query:({db:e,args:t,opts:n})=>Es(e,L(t,0),{scope:k(n,"scope"),limit:A(n,"limit",100)}),format:e=>` ${M(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${L(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
547
+ ${e.length} symbol(s)`)}),kr({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[u("-s, --scope <path>","Limit to files matching path")],docs:$("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>Ls(e,{scope:k(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Ie({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:$("Navigation"),query:({db:e,args:t})=>Ds(e,L(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>oe(t,L(n,0)),emptyMessage:({db:e,args:t})=>se(e,L(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>ve(t,L(n,0),e,"hierarchy")}),{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:Tk},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:P([u("--forward","Forward slice (what does this affect). Default is backward."),u("--depth <n>","Max transitive depth for backward slice",v,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:Ik}];var jk=K("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=A(n,"limit",20),o=Me(e.config.projectRoot).gitContext?.headCommit,s=va(e,L(t,0),{semantic:r.semantic,impactDepth:C(n,"impactDepth",3),sliceDepth:C(n,"sliceDepth",3),scope:k(n,"scope"),...o?{gitHead:o}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(b(n,"json")){I("plan-context",t,n,{...Ut(e,L(t,0)),...s},{analysisBudget:r.analysisBudget});return}return j.empty(se(e,L(t,0)))}if(b(n,"json")){I("plan-context",t,n,s.matched.symbol?{...Ut(e,L(t,0)),...s}:s,{analysisBudget:r.analysisBudget});return}s.matched.symbol&&oe(e,L(t,0));let a=[{title:"TARGET",rows:Ek(s)},{title:"DEFINITIONS",rows:Lk(s,i),skipIfEmpty:!0},{title:"REFERENCES",rows:Ak(s,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:Dk(s,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:Ok(s,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:Fk(s,i),skipIfEmpty:!0},{title:"SURFACE",rows:Nk(s,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:Mk(s,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:_k(s,i),skipIfEmpty:!0},{title:"HISTORY",rows:qk(s),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:Bk(s),skipIfEmpty:!0}];j.sectionedReport(a)}),Pm=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:P([u("--impact-depth <n>","Maximum affected traversal depth",v,3),u("--slice-depth <n>","Maximum backward slice depth",v,3),u("-s, --scope <path>","Limit downstream impact to files matching path"),u("-n, --limit <n>","Rows per section",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Planning",["scip-query plan-context parseSymbol"]),handler:jk}];function Ek(e){return[`Target: ${e.target}`,`Matched: symbol=${mo(e.matched.symbol)} file=${mo(e.matched.file)} module=${mo(e.matched.module)}`]}function Lk(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${M(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
548
+ `).map((o,s)=>` ${String(_e(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${ie(r.startLine,r.endLine)} ${r.shortName}`)),tt(n,t).rows}function Ak(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${_e(r.line)} in ${r.enclosingShort}`);return gt(tt(n,t))}function Dk(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 gt(tt([...n,...r],t))}function Ok(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}:${_e(o.line)} in ${o.enclosingShort}`);return gt(tt([...n,...r,...i],t))}function Fk(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 gt(tt(n,t))}function Nk(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${ie(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return gt(tt(n,t))}function Mk(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 gt(tt(n,t))}function _k(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` ${ie(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${M(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}`)),gt(tt(n,t))}function qk(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 Bk(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 tt(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function gt(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function mo(e){return e?"yes":"no"}import{existsSync as pn}from"fs";import{existsSync as Qk,mkdtempSync as Yk,rmSync as Xk}from"fs";import{tmpdir as Zk}from"os";import{dirname as go,join as ho}from"path";import{performance as Em}from"perf_hooks";import{spawnSync as ew}from"child_process";import{createHash as Vk}from"crypto";import{existsSync as Hk,mkdirSync as Wk,readFileSync as Gk,renameSync as Uk,writeFileSync as Jk}from"fs";import{homedir as zk}from"os";import{dirname as Kk,join as fo}from"path";function Tm(e){return Vk("sha256").update(e).digest("hex")}function Im(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?fo(t.XDG_CACHE_HOME,"scip-query"):fo(zk(),".cache","scip-query"));return fo(n,e)}async function jm(e){let{cachePath:t,url:n,expectedSha256:r}=e;if(Hk(t)){let l=Tm(Gk(t));if(l===r)return{status:"cached",path:t,sha256:l}}let o=await(e.fetchImpl??fetch)(n);if(!o.ok)throw new Error(`failed to download ${n}: HTTP ${o.status}`);let s=Buffer.from(await o.arrayBuffer()),a=Tm(s);if(a!==r)throw new Error(`downloaded ${n} checksum mismatch: expected ${r}, got ${a}`);Wk(Kk(t),{recursive:!0});let c=`${t}.tmp-${process.pid}`;return Jk(c,s),Uk(c,t),{status:"downloaded",path:t,sha256:a}}var tw=12e4,Dm="v1.8.0",nw=`https://github.com/tlaplus/tlaplus/releases/download/${Dm}/tla2tools.jar`,rw="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Lr(e){let t=e.spawn??ew,n=iw(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??tw,i=Em.now(),o;try{o=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:r,maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])Xk(l,{recursive:!0,force:!0})}let s=Math.round(Em.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:ow(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function iw(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"&&Ae(Lm(e),t)){let o=Lm(e);return Ae(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:go(e.specPath)}:Er("apalache",`Apalache binary is not available: ${o}`)}let r=yo(e),i=Ae("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return Er(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return Er(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:go(e.specPath)};let s=e.metaDir??Yk(ho(Zk(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:go(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Er("none",`unknown checker mode: ${n}`)}function Lm(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function yo(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Om(t),ho(e.projectRoot,"tla2tools.jar"),ho(e.projectRoot,"tools","tla2tools.jar")].filter(r=>typeof r=="string"&&r.length>0).find(r=>Qk(r))??null}function Om(e=process.env){return Im("tla2tools.jar",e)}async function Fm(e={}){let t=e.cachePath??Om(e.env),n=e.expectedSha256??rw,r=e.version??Dm,i=e.url??nw;return{...await jm({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl}),version:r,url:i}}function ow(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=[...Am(n),...Am(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function Am(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Er(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as sw}from"crypto";import{readFileSync as Mm}from"fs";import{join as _m}from"path";var qm=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),Bm=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),Vm=new Set(["readFileSync","existsSync","statSync"]),aw=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,cw=/^\s*SELECT\b/i;function Hm(e){return aw.test(e)?"write":cw.test(e)?"read":null}var lw=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function dw(e,t){let n=e.match(lw);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${Le(t)}\\b`).test(r)}function Wm(e,t,n,r=[],i=[]){let o=[],s=mw(e,t,o),a=s.aliases,c=fw(t),l=gw(t),d=hw(t),p=Sw(e,t,o),m=xw(e,t,o);n&&Rw(t,n,i,o);let f=new Map((n?.actions??[]).map(x=>[x.name,x])),g=new Set(p.flatMap(x=>x.referents.map(w=>w.match?.symbol).filter(Boolean))),h=new Set((m?.referents??[]).map(x=>x.match?.symbol).filter(Boolean)),y=kw(e,t,p,a,c,l,d,g,h,o,f),S=Cw(e,p,a,c,l,d,o,f);return Tw(e,p,o),Iw(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:So(p.flatMap(x=>x.referents))+So(s.referents)+So(m?.referents??[]),staticWrites:y,staticReads:S,waivers:Kw(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:uw(o)}}function uw(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=pw(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||Ar(r.severity)-Ar(n.severity)||n.groupKey.localeCompare(r.groupKey))}function pw(e,t){return Ar(t)>Ar(e)?t:e}function Ar(e){return e==="error"?2:e==="warning"?1:0}function mw(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=Fr(e,l,n,o);i.push(d);let p=d.match;if(!p){c||n.push(W("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}Hw(e,o,l,p,n,c),s.aliases.length===0&&a.add(Oo(p.symbol))}for(let l of a)r.push({variable:o,alias:l})}return{aliases:zw(r),referents:i}}function fw(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 gw(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 hw(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=ao(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function yw(e,t,n,r,i,o){return Gm(e,t,(s,a,c)=>ht(e,s,a,c,n,r,i,o))}function bw(e,t,n,r,i,o){return Gm(e,t,(s,a,c)=>Or(e,s,a,c,n,r,i,o))}function Gm(e,t,n){let r=Wt(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=vn(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 Sw(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=co(s),c="error"in a?s:a.ref,d=Fr(e,c,n,r).match;return d?(Ww(e,r,s,d,n),"error"in a||!a.window?{ref:s,match:d}:vw(a.window,d)?(n.push(W("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 ${Q(d.symbol)}'s actual span L${d.startLine+1}-L${d.endLine+1} in ${d.relativePath}.`,why:[`${s} resolves to ${Q(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(W("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 vw(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function xw(e,t,n){let r=t.init;if(!r)return;let i=!!r.waive,o=r.codeRefs.map(s=>{let a=Fr(e,s,n,"Init"),c=a.match;return c?Gw(e,s,c,n,i):i||n.push(W("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 Rw(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(W("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(W("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&&(Nm({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)}),Nm({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(W("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 Nm(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(W(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(W(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 kw(e,t,n,r,i,o,s,a,c,l,d){let p=[];for(let f of n){let g=[];for(let h of f.referents){if(!h.match)continue;let y=h.window??{startLine:h.match.startLine,endLine:h.match.endLine},S=ht(e,h.match.relativePath,y.startLine,y.endLine,r,i,o,s);g.push(...S),p.push(...S);let x=new Set(f.mapping.writes),w=yw(e,h.match.symbol,r,i,o,s).filter(R=>x.has(R.variable));g.push(...w),p.push(...w)}$w(f,g,l,d.get(f.name))}let m=t.unmappedWriteScope==="actions"?[]:qw(e,t);for(let f of m)for(let g of ht(e,f,0,Number.POSITIVE_INFINITY,r,i,o,s))p.push(g),ww(g)&&(g.enclosingSymbol&&(a.has(g.enclosingSymbol)||c.has(g.enclosingSymbol))||l.push(W("unmapped-write","error","static-action",{modelElement:g.variable,codeRef:g.enclosingSymbol??`${g.file}:${g.line+1}`,file:g.file,startLine:g.line,endLine:g.line,message:`Modeled variable ${g.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${g.target} at ${g.file}:${g.line+1}.`,g.enclosingShort?`The write is inside ${g.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 ${g.variable} from the modeled slice if it is intentionally out of scope.`})));return Ro(p)}function ww(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function $w(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)&&!dn(e,"write",a.variable)&&n.push(W("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}${Dr(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)&&!dn(e,"write",a.variable)&&n.push(W("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}${Dr(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)&&!dn(e,"write",a)&&n.push(W("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 Cw(e,t,n,r,i,o,s,a){let c=[];for(let l of t){let d=[];for(let p of l.referents){if(!p.match)continue;let m=p.window??{startLine:p.match.startLine,endLine:p.match.endLine},f=Or(e,p.match.relativePath,m.startLine,m.endLine,n,r,i,o);d.push(...f),c.push(...f);let g=new Set(l.mapping.reads),h=bw(e,p.match.symbol,n,r,i,o).filter(y=>g.has(y.variable));d.push(...h),c.push(...h)}Pw(l,d,s,a.get(l.name))}return ko(c)}function Pw(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(W("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}${Dr(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)&&!dn(e,"read",a.variable)&&n.push(W("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}${Dr(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)&&!dn(e,"read",a)&&n.push(W("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 Tw(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>Fr(e,s,n,r.name));for(let s of i)s.match||n.push(W("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=Wt(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of o)c.has(l)||n.push(W("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 ${Q(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 Iw(e,t,n){for(let[r,i]of t.entries()){let o=e.actions[i.action];if(!o){n.push(W("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=Jw(i),a=new Set(o.writes);for(let c of s)a.has(c)||n.push(W("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 ht(e,t,n,r,i,o=[],s=[],a=[]){let c=jw(e,t,n,r,i,o,s,a);return c||Mw(e,t,n,r,i,o,s,a)}function Or(e,t,n,r,i,o=[],s=[],a=[]){let c=Ew(e,t,n,r,i,o,s,a);return c||_w(e,t,n,r,i,o,s,a)}function jw(e,t,n,r,i,o=[],s=[],a=[]){let c=_r(e,t);if(!c)return null;let l=[],d=p=>{if(!(p.startPosition.row>r||p.endPosition.row<n)){Lw(e,t,p,i,l),Um(e,t,p,o,"write",l),Jm(e,t,p,s,"write",l),zm(e,t,p,a,"write",l);for(let m of p.children)d(m)}};return d(c.rootNode),Ro(l)}function Ew(e,t,n,r,i,o=[],s=[],a=[]){let c=_r(e,t);if(!c)return null;let l=[],d=p=>{if(!(p.startPosition.row>r||p.endPosition.row<n)){Ow(e,t,p,i,l),Um(e,t,p,o,"read",l),Jm(e,t,p,s,"read",l),zm(e,t,p,a,"read",l);for(let m of p.children)d(m)}};return d(c.rootNode),ko(l)}function Lw(e,t,n,r,i){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&ln(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&&ln(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&&ln(e,t,o,"update",r,i);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&ln(e,t,o,"delete",r,i);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!Qm(o))return;ln(e,t,o,"mutation-call",r,i)}}}function Um(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?vo(s):null;if(!a||!(i==="write"?Bm:Vm).has(a))return;let d=n.childForFieldName("arguments")?.namedChild(0);if(!d)return;let p=d.text;for(let m of r){if(!p.includes(m.path))continue;let f=je(e,t,n.startPosition.row);o.push({variable:m.variable,alias:m.path,file:t,line:n.startPosition.row,target:`${a}(${p})`,kind:"resource",enclosingSymbol:f?.symbol,enclosingShort:f?Q(f.symbol):void 0})}}function vo(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 Jm(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=Aw(a);if(c!==null&&Hm(c)===i)for(let l of r){if(!l.regex.test(c))continue;let d=je(e,t,n.startPosition.row),p=n.childForFieldName("function")??n.namedChild(0),m=(p&&vo(p))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${m}(${Dw(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?Q(d.symbol):void 0})}}}function Aw(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function Dw(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function zm(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?vo(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let d=l.text.trim();for(let p of r){if(!Km(p,a,d,i))continue;let m=je(e,t,n.startPosition.row);o.push({variable:p.variable,alias:p.table,file:t,line:n.startPosition.row,target:`${a}(${d})`,kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?Q(m.symbol):void 0})}}function Km(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 Ow(e,t,n,r,i){if(!(!Fw(n)||Nw(n)))for(let o of r){if(n.text!==o.alias)continue;let s=je(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?Q(s.symbol):void 0})}}function Fw(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function Nw(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&&bo(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&&bo(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&Qm(n)&&bo(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 bo(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function Qm(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&qm.has(t.text))}function ln(e,t,n,r,i,o){for(let s of i){if(!Uw(s.alias,n.text))continue;let a=je(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?Q(a.symbol):void 0})}}function Mw(e,t,n,r,i,o=[],s=[],a=[]){let l=Mm(_m(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],p=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=p;m+=1){let f=l[m]??"";for(let g of i){if(dw(f,g.alias))continue;let h=Le(g.alias);if(!new RegExp(`(?:\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${h}\\b\\s*\\.\\s*(?:${[...qm].join("|")})\\s*\\(|\\b${h}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(f))continue;let S=je(e,t,m);d.push({variable:g.variable,alias:g.alias,file:t,line:m,target:f.trim(),kind:"source-scan",enclosingSymbol:S?.symbol,enclosingShort:S?Q(S.symbol):void 0})}Ym(e,t,m,f,o,Bm,d),Xm(e,t,m,f,s,"write",d),Zm(e,t,m,f,a,"write",d)}return Ro(d)}function _w(e,t,n,r,i,o=[],s=[],a=[]){let l=Mm(_m(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],p=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=p;m+=1){let f=l[m]??"";for(let g of i){let h=Le(g.alias);if(!new RegExp(`\\b${h}\\b`).test(f)||new RegExp(`\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(f))continue;let y=je(e,t,m);d.push({variable:g.variable,alias:g.alias,file:t,line:m,target:f.trim(),kind:"source-scan",enclosingSymbol:y?.symbol,enclosingShort:y?Q(y.symbol):void 0})}Ym(e,t,m,f,o,Vm,d),Xm(e,t,m,f,s,"read",d),Zm(e,t,m,f,a,"read",d)}return ko(d)}function Ym(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 p=je(e,t,n);s.push({variable:d.variable,alias:d.path,file:t,line:n,target:r.trim(),kind:"resource",enclosingSymbol:p?.symbol,enclosingShort:p?Q(p.symbol):void 0})}}}function Xm(e,t,n,r,i,o,s){if(i.length!==0&&Hm(r)===o)for(let a of i){if(!a.regex.test(r))continue;let c=je(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?Q(c.symbol):void 0})}}function Zm(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(!Km(d,c,l,o))continue;let p=je(e,t,n);s.push({variable:d.variable,alias:d.table,file:t,line:n,target:r.trim(),kind:"orm-call",enclosingSymbol:p?.symbol,enclosingShort:p?Q(p.symbol):void 0})}}}function qw(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 Fr(e,t,n,r){let i=vn(e,t),o=i.match??(t.includes("#")?vn(e,t.replace("#","/")).match:null);return i.match&&i.total>1&&!Bw(t)&&n.push(W("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 ${Q(i.match.symbol)}.`,why:[`${i.total} indexed definitions share this lookup shape.`,Vw(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 Bw(e){return/[/#:]/.test(e)}function Vw(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function Hw(e,t,n,r,i,o=!1){let s=xo(e,r);if(s===null||Qw.has(s)||o)return;let a=wo.has(s);i.push(W("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 ${Bt(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${Q(r.symbol)} with SCIP kind ${Bt(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function Ww(e,t,n,r,i){let o=xo(e,r);o===null||ef.has(o)||wo.has(o)&&i.push(W("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 ${Q(r.symbol)} with SCIP kind ${Bt(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function Gw(e,t,n,r,i){let o=xo(e,n);o===null||ef.has(o)||i||wo.has(o)&&r.push(W("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 ${Q(n.symbol)} with SCIP kind ${Bt(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function xo(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function je(e,t,n){return Sn(e,t).filter(i=>i.startLine<=n&&i.endLine>=n).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine))[0]??null}function Uw(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Le(e)}([^A-Za-z0-9_$]|$)`).test(t)}function Jw(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 Ro(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 ko(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 zw(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 So(e){return e.filter(t=>t.match).length}function Dr(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function dn(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function Kw(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 wo=new Set(_o()),ef=new Set(Mo()),Qw=new Set(qo());function W(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${sw("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{readFileSync as Yw}from"fs";import{basename as Xw,join as tf}from"path";var $o=/^[A-Za-z_][A-Za-z0-9_]*$/;function nf(e,t,n={}){let r=[],i=Sn(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=Yw(tf(e.config.projectRoot,t),"utf8").split(/\r?\n/),a=T=>T.symbol.trimEnd().endsWith("()."),c=i.filter(T=>!a(T)&&!T.isTypeLike&&T.parentTypeName===null&&$o.test(T.leaf)),l=c.map(T=>({variable:T.leaf,alias:T.leaf})),d=l.length>0?ht(e,t,0,Number.POSITIVE_INFINITY,l):[],p=new Set(d.map(T=>T.variable)),m=c.filter(T=>p.has(T.leaf)?!0:t$(s,T)),f=null,g;if(m.length>0)g=i.filter(T=>a(T)&&T.parentTypeName===null);else{if(f=Zw(e,t,i,a),!f){let T=i.some(O=>!a(O)&&!O.isTypeLike&&O.parentTypeName!==null&&$o.test(O.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 `+(T?"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=f.fields,g=f.methods,r.push(`state scoped to class ${f.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(T=>n$(T,s,t,r,f?.className)),y=h.map(T=>({variable:T.name,alias:T.leaf})),S=[],x=new Set;for(let T of g){let O=ht(e,t,T.startLine,T.endLine,y);if(O.length===0)continue;let Z=Or(e,t,T.startLine,T.endLine,y),F=s$(rf(T.leaf),x);S.push({name:F,leaf:T.leaf,codeRef:e$(t,T,f?.className),startLine:T.startLine,writes:[...new Set(O.map(H=>H.variable))].sort(),reads:[...new Set(Z.map(H=>H.variable))].sort()})}S.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 w=n.moduleName??a$(t),R=n.specDir??tf("specs",w),D=c$(w,h,S,t),_=l$(),z=d$(w,R,t,h,S);return{moduleName:w,file:t,variables:h,actions:S,warnings:r,spec:D,cfg:_,map:z}}function Zw(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!$o.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 f of ht(e,t,m.startLine,m.endLine,l))d.add(f.variable);let p=a.filter(m=>d.has(m.leaf));p.length!==0&&(!o||p.length>o.fields.length)&&(o={className:s,fields:p,methods:c})}return o}function e$(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function t$(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function n$(e,t,n,r,i){let o=r$(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=i$(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 r$(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function i$(e,t){let r=t.match(new RegExp(`\\b${u$(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=o$(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 o$(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 rf(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function s$(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function a$(e){let n=Xw(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return rf(n||"Model")}function c$(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(p=>p.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(`
549
+ `)}function l$(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
550
+ `)}function d$(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)}
551
+ `}function u$(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function of(e,t){let n=Object.keys(t.variables),r=Object.entries(t.actions).map(([i,o])=>{let s=o.code[0]??"",a=s?No(e,s):null;return{action:i,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:p$(n),wiring:r,variables:n}}function p$(e){return`/**
546
552
  * Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
547
553
  *
548
554
  * Usage inside a mapped action (record the model-visible slice around the
@@ -585,15 +591,15 @@ export function tlaRecord(action: string, before: Record<string, unknown>, after
585
591
  steps.push({ action, before, after });
586
592
  writeFileSync(tracePath, JSON.stringify(steps, null, 2));
587
593
  }
588
- `}import{copyFileSync as i$,mkdtempSync as o$,readdirSync as s$,rmSync as a$,writeFileSync as rf}from"fs";import{tmpdir as c$}from"os";import{basename as l$,dirname as d$,join as cn}from"path";function Ar(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 u$(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 y={};for(let[S,x]of Object.entries(h)){if(!t.includes(S))continue;let k=m$(x);k!==void 0&&(y[S]=k)}return y};s.push(c(a));for(let h of n){if(h.before)for(let[y,S]of Object.entries(h.before))y in a||(a[y]=S);Object.assign(a,h.after??{}),s.push(c(a))}let l=t.filter(h=>s.every(y=>h in y)),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(y=>`${y} |-> ${sf(h[y])}`).join(", ")}]`).join(`,
589
- `),f=[`---- 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(`
594
+ `}import{copyFileSync as m$,mkdtempSync as f$,readdirSync as g$,rmSync as h$,writeFileSync as sf}from"fs";import{tmpdir as y$}from"os";import{basename as b$,dirname as S$,join as un}from"path";function Nr(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 v$(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 y={};for(let[S,x]of Object.entries(h)){if(!t.includes(S))continue;let w=R$(x);w!==void 0&&(y[S]=w)}return y};s.push(c(a));for(let h of n){if(h.before)for(let[y,S]of Object.entries(h.before))y in a||(a[y]=S);Object.assign(a,h.after??{}),s.push(c(a))}let l=t.filter(h=>s.every(y=>h in y)),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 p=`${e}Trace`,m=s.map(h=>` [${l.map(y=>`${y} |-> ${cf(h[y])}`).join(", ")}]`).join(`,
595
+ `),f=[`---- MODULE ${p} ----`,"\\* 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(`
590
596
  `),g=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
591
- `);return{moduleName:u,moduleText:f,cfgText:g,variables:l,skippedVariables:d,states:s.length,warnings:i}}function of(e){let t=e.mappedActions??[],n=u$(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:Ar(t,[])};let r=o$(cn(c$(),"scip-tla-trace-"));try{let i=d$(e.specPath);for(let d of s$(i))d.endsWith(".tla")&&i$(cn(i,d),cn(r,d));let o=cn(r,`${n.moduleName}.tla`),s=cn(r,`${n.moduleName}.cfg`);rf(o,n.moduleText),rf(s,n.cfgText);let a=Tr({...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:Ar(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:Ar(t,e.steps)};let c=p$(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:Ar(t,l)}}finally{a$(r,{recursive:!0,force:!0})}}function p$(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 m$(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 sf(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>sf(t)).join(", ")}>>`}function af(e){return l$(e).replace(/\.tla$/i,"")}import{mkdirSync as lf,writeFileSync as df}from"fs";import{dirname as f$,join as Dt}from"path";var g$=async(...e)=>{let{args:t,opts:n}=bc(e),r=L(t,0);if(r==="fetch-tools"){let o=await Dm();if(b(n,"json")){I("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=B(t,1);if(!o)throw new Error("tla scaffold requires a target source file");le(s=>h$(s,t,n,o));return}if(r==="instrument"){let o=B(t,1);le(s=>y$(s,t,n,o));return}if(r==="trace-check"){let o=B(t,1);if(!o)throw new Error("tla trace-check requires a spec path");le(s=>b$(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=B(t,1);if(!i)throw new Error("tla verify requires a spec path");le(o=>x$(o,t,n,i))};function h$(e,t,n,r){let i=e.config.projectRoot,o=ef(e,r,{moduleName:w(n,"moduleName"),specDir:w(n,"out")}),s=w(n,"out")??Dt("specs",o.moduleName),a=pe(i,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=b(n,"force"),l=[{path:Dt(a,`${o.moduleName}.tla`),body:o.spec},{path:Dt(a,`${o.moduleName}.cfg`),body:o.cfg},{path:Dt(a,`${o.moduleName}.scip-tla.json`),body:o.map}];for(let d of l)if(!c&&ln(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);lf(a,{recursive:!0});for(let d of l)df(d.path,d.body);if(b(n,"json")){I("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 ${Dt(s,`${o.moduleName}.tla`)}'.`)}function y$(e,t,n,r){let i=e.config.projectRoot,o=w(n,"map")??(r?wr(r):void 0);if(!o)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=kr(i,o);if(!s.loaded)throw new Error(s.errors.join(`
592
- `));let{contract:a,mapDir:c}=s.loaded,l=nf(e,a),d=w(n,"out")??Dt(c,"scip-tla-recorder.ts"),u=pe(i,d);if(!u)throw new Error(`instrument output escapes the project root: ${d}`);if(!b(n,"force")&&ln(u))throw new Error(`refusing to overwrite ${u} (pass --force to replace the recorder)`);if(lf(f$(u),{recursive:!0}),df(u,l.recorderSource),b(n,"json")){I("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 f=m.file?`${m.file}:${m.line}`:`UNRESOLVED (${m.codeRef})`;console.log(` - ${m.action} -> ${f} writes: ${m.writes.join(", ")||"-"}`)}}function b$(e,t,n,r){let i=e.config.projectRoot,o=pe(i,r);if(!o||!ln(o))throw new Error(`TLA+ spec not found: ${r}`);let s=w(n,"map")??wr(r),a=kr(i,s);if(!a.loaded)throw new Error(a.errors.join(`
593
- `));let{contract:c}=a.loaded,l=wt(n,"trace"),u=ao(i,[...c.traces,...l]).flatMap(g=>so(i,g).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=of({specPath:o,baseModuleName:af(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:U(n,"timeoutMs")}}),f=m.status==="accepted"||m.status==="unavailable"&&b(n,"allowUnknown")?0:1;if(b(n,"json")){I("tla",t,n,{operation:"trace-check",...m,exitCode:f}),process.exitCode=f;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 g of m.generation.warnings)console.log(`WARNING: ${g}`)}console.log(`${m.status.toUpperCase()}: ${m.detail}`),b(n,"coverage")&&S$(m.actionCoverage),process.exitCode=f}function S$(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 v$(e,t,n,r){let i=w(r,"map");if(i)return{mapArg:i};let o=wr(t),s=pe(e,o);if(s&&ln(s))return{mapArg:o};let a=Bp(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 x$(e,t,n,r){let i=e.config.projectRoot,o=pe(i,r);if(!o||!ln(o))throw new Error(`TLA+ spec not found: ${r}`);let{mapArg:s,mappingDiscoveredBy:a}=v$(i,r,o,n),c=kr(i,s);if(!c.loaded)throw new Error(c.errors.join(`
594
- `));let{contract:l,mapPath:d,mapDir:u}=c.loaded,m=w(n,"config")??l.config,f=Np(i,u,m),g=k$(w(n,"checker")??"auto"),h=w(n,"tlaTools"),y=R$(i,r,o,h)??Fp(i,r),S=_p(f),x=wt(n,"trace"),R=ao(i,[...l.traces,...x]).map(N=>({tracePath:N,...so(i,N)})),D=R.flatMap(N=>N.steps),_=new Set(x),z=R.filter(N=>_.has(N.tracePath)).flatMap(N=>N.errors),T=Vm(e,l,y,D,S);for(let N of[...c.errors,...z])T.findings.push({id:`TLA-CONTRACT-${T.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 O=Tr({projectRoot:i,specPath:o,configPath:f??void 0,checker:g,tlaToolsJar:h,apalacheBin:w(n,"apalache"),length:P(n,"length",10),timeoutMs:U(n,"timeoutMs")});O.status==="skipped"&&g!=="none"&&T.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:O.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 Z={operation:"verify",specPath:o,mapPath:d,...a?{mappingDiscoveredBy:a}:{},...f?{configPath:f}:{},checker:O,conformance:T,exitCode:w$(O,T,b(n,"allowUnknown"))};if(b(n,"json")){I("tla",t,n,Z),process.exitCode=Z.exitCode;return}$$(Z,b(n,"full")),process.exitCode=Z.exitCode}function R$(e,t,n,r){let i=fo({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=Pp({specPath:n,jarPath:i});return o?Mp(e,t,o):null}var uf=[{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",options:C([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",v,10),p("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",_e),p("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",rt,[]),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:g$}];function k$(e){if(!Op(e))throw new Error(`unknown checker mode: ${e}`);return e}function w$(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 cf=3;function $$(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=C$(e);console.log(`
595
- 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 T$(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)pf(o);return}P$(e.conformance)}function P$(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
597
+ `);return{moduleName:p,moduleText:f,cfgText:g,variables:l,skippedVariables:d,states:s.length,warnings:i}}function af(e){let t=e.mappedActions??[],n=v$(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:Nr(t,[])};let r=f$(un(y$(),"scip-tla-trace-"));try{let i=S$(e.specPath);for(let d of g$(i))d.endsWith(".tla")&&m$(un(i,d),un(r,d));let o=un(r,`${n.moduleName}.tla`),s=un(r,`${n.moduleName}.cfg`);sf(o,n.moduleText),sf(s,n.cfgText);let a=Lr({...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:Nr(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:Nr(t,e.steps)};let c=x$(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:Nr(t,l)}}finally{h$(r,{recursive:!0,force:!0})}}function x$(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 R$(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 cf(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>cf(t)).join(", ")}>>`}function lf(e){return b$(e).replace(/\.tla$/i,"")}import{mkdirSync as uf,writeFileSync as pf}from"fs";import{dirname as k$,join as Ft}from"path";var w$=async(...e)=>{let{args:t,opts:n}=hc(e),r=L(t,0);if(r==="fetch-tools"){let o=await Fm();if(b(n,"json")){I("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=B(t,1);if(!o)throw new Error("tla scaffold requires a target source file");ce(s=>$$(s,t,n,o));return}if(r==="instrument"){let o=B(t,1);ce(s=>C$(s,t,n,o));return}if(r==="trace-check"){let o=B(t,1);if(!o)throw new Error("tla trace-check requires a spec path");ce(s=>P$(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=B(t,1);if(!i)throw new Error("tla verify requires a spec path");ce(o=>j$(o,t,n,i))};function $$(e,t,n,r){let i=e.config.projectRoot,o=nf(e,r,{moduleName:k(n,"moduleName"),specDir:k(n,"out")}),s=k(n,"out")??Ft("specs",o.moduleName),a=ue(i,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=b(n,"force"),l=[{path:Ft(a,`${o.moduleName}.tla`),body:o.spec},{path:Ft(a,`${o.moduleName}.cfg`),body:o.cfg},{path:Ft(a,`${o.moduleName}.scip-tla.json`),body:o.map}];for(let d of l)if(!c&&pn(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);uf(a,{recursive:!0});for(let d of l)pf(d.path,d.body);if(b(n,"json")){I("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 ${Ft(s,`${o.moduleName}.tla`)}'.`)}function C$(e,t,n,r){let i=e.config.projectRoot,o=k(n,"map")??(r?Tr(r):void 0);if(!o)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=Pr(i,o);if(!s.loaded)throw new Error(s.errors.join(`
598
+ `));let{contract:a,mapDir:c}=s.loaded,l=of(e,a),d=k(n,"out")??Ft(c,"scip-tla-recorder.ts"),p=ue(i,d);if(!p)throw new Error(`instrument output escapes the project root: ${d}`);if(!b(n,"force")&&pn(p))throw new Error(`refusing to overwrite ${p} (pass --force to replace the recorder)`);if(uf(k$(p),{recursive:!0}),pf(p,l.recorderSource),b(n,"json")){I("tla",t,n,{operation:"instrument",recorder:p,variables:l.variables,wiring:l.wiring});return}console.log(`Wrote trace recorder: ${p}`),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 f=m.file?`${m.file}:${m.line}`:`UNRESOLVED (${m.codeRef})`;console.log(` - ${m.action} -> ${f} writes: ${m.writes.join(", ")||"-"}`)}}function P$(e,t,n,r){let i=e.config.projectRoot,o=ue(i,r);if(!o||!pn(o))throw new Error(`TLA+ spec not found: ${r}`);let s=k(n,"map")??Tr(r),a=Pr(i,s);if(!a.loaded)throw new Error(a.errors.join(`
599
+ `));let{contract:c}=a.loaded,l=Ct(n,"trace"),p=uo(i,[...c.traces,...l]).flatMap(g=>lo(i,g).steps);if(p.length===0)throw new Error("no trace steps found: pass --trace <file> (repeatable) or list traces in the mapping contract");let m=af({specPath:o,baseModuleName:lf(o),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:p,nextOperator:k(n,"next"),toolOptions:{projectRoot:i,tlaToolsJar:k(n,"tlaTools"),timeoutMs:U(n,"timeoutMs")}}),f=m.status==="accepted"||m.status==="unavailable"&&b(n,"allowUnknown")?0:1;if(b(n,"json")){I("tla",t,n,{operation:"trace-check",...m,exitCode:f}),process.exitCode=f;return}if(console.log(`TLA+ trace-check: ${o}`),console.log(`Trace: ${p.length} step(s) -> ${m.states} pinned state(s)`),m.generation){console.log(`Pinned variables: ${m.generation.variables.join(", ")}`);for(let g of m.generation.warnings)console.log(`WARNING: ${g}`)}console.log(`${m.status.toUpperCase()}: ${m.detail}`),b(n,"coverage")&&T$(m.actionCoverage),process.exitCode=f}function T$(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 I$(e,t,n,r){let i=k(r,"map");if(i)return{mapArg:i};let o=Tr(t),s=ue(e,o);if(s&&pn(s))return{mapArg:o};let a=Hp(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 j$(e,t,n,r){let i=e.config.projectRoot,o=ue(i,r);if(!o||!pn(o))throw new Error(`TLA+ spec not found: ${r}`);let{mapArg:s,mappingDiscoveredBy:a}=I$(i,r,o,n),c=Pr(i,s);if(!c.loaded)throw new Error(c.errors.join(`
600
+ `));let{contract:l,mapPath:d,mapDir:p}=c.loaded,m=k(n,"config")??l.config,f=Mp(i,p,m),g=L$(k(n,"checker")??"auto"),h=k(n,"tlaTools"),y=E$(i,r,o,h)??_p(i,r),S=Bp(f),x=Ct(n,"trace"),R=uo(i,[...l.traces,...x]).map(F=>({tracePath:F,...lo(i,F)})),D=R.flatMap(F=>F.steps),_=new Set(x),z=R.filter(F=>_.has(F.tracePath)).flatMap(F=>F.errors),T=Wm(e,l,y,D,S);for(let F of[...c.errors,...z])T.findings.push({id:`TLA-CONTRACT-${T.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:F,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 O=Lr({projectRoot:i,specPath:o,configPath:f??void 0,checker:g,tlaToolsJar:h,apalacheBin:k(n,"apalache"),length:C(n,"length",10),timeoutMs:U(n,"timeoutMs")});O.status==="skipped"&&g!=="none"&&T.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:O.diagnostics.map(F=>F.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 Z={operation:"verify",specPath:o,mapPath:d,...a?{mappingDiscoveredBy:a}:{},...f?{configPath:f}:{},checker:O,conformance:T,exitCode:A$(O,T,b(n,"allowUnknown"))};if(b(n,"json")){I("tla",t,n,Z),process.exitCode=Z.exitCode;return}D$(Z,b(n,"full")),process.exitCode=Z.exitCode}function E$(e,t,n,r){let i=yo({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=Tp({specPath:n,jarPath:i});return o?qp(e,t,o):null}var mf=[{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",options:P([u("--map <file>","scip-query TLA mapping JSON file"),u("--config <file>","TLA+ checker config file"),u("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),u("--tla-tools <jar>","Path to tla2tools.jar"),u("--apalache <binary>","Path to apalache-mc binary"),u("--length <n>","Bounded checker length for Apalache",v,10),u("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",qe),u("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",ot,[]),u("--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"),u("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),u("--allow-unknown","Exit zero when only unknown findings remain"),u("--out <path>","Output directory (scaffold) or file (instrument)"),u("--module-name <name>","Module name for scaffolded specs"),u("--force","Overwrite existing scaffold/instrument output"),u("--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:w$}];function L$(e){if(!Np(e))throw new Error(`unknown checker mode: ${e}`);return e}function A$(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 df=3;function D$(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=F$(e);console.log(`
601
+ 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 N$(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)ff(o);return}O$(e.conformance)}function O$(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
596
602
  Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
597
- [${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let i of n.findingIds.slice(0,cf)){let o=t.get(i);o&&pf(o)}let r=n.count-cf;r>0&&console.log(` ... and ${r} more in this group (use --full to show all)`)}}function C$(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 T$(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 pf(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${M(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
598
- [${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 mf=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","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"],I$=[vm,wm,xm,Pr,km,$m,uf,Rm],ff=I$.flat(),E$=new Map(ff.map(e=>[e.id,e]));for(let e of ff)if(!mf.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Ot=mf.map(e=>j$(e));function j$(e){let t=E$.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var L$=Ot.slice(0,ko("plan-context")),A$=Ot.slice(Dr("drift"),ko("self-audit")),D$=Ot.slice(Dr("convergence"),ko("slice")),O$=Ot.slice(Dr("redundant-reexports")),zA=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[p("-l, --language <lang>","Index only this language (can be repeated)",rt,[]),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",_e),p("--json","Output as JSON, including per-shard reuse diagnostics")],renderShape:"custom",docs:$("Indexing",["scip-query reindex"]),handler:Hu},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:$("Indexing"),handler:Wu},{id:"augment-vue",command:"augment-vue",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:Gu},...L$,{id:Ur,command:Ur,description:"Internal diff-impact batch worker",hidden:!0,options:[p("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Uu},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:C([p("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:$("Impact"),handler:Ju},...A$,{id:Gr,command:Gr,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:zu},{id:"health",command:"health",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:Ku},{id:"bench",command:"bench",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)",rt,[]),p("--timeout-ms <n>","Per-command timeout in milliseconds",_e,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:Qu},{id:"work-audit",command:"work-audit <profile>",description:"Rank exact repeated computations in a profiling JSONL file by measured avoidable time",options:[p("--top <n>","Maximum repeated-work groups to show",_e,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:Yu},{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",_e),p("--max-mismatches <n>","Maximum mismatch details to include in output",kt),p("--full","Compare every indexed TypeScript-like definition"),p("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:Xu},...D$,{id:"install-skills",command:"install-skills",description:`Install skills (${Kn.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:$("Maintenance"),handler:tp},{id:"setup-hooks",command:"setup-hooks",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:np},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:cl},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:ll},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:$("Maintenance"),handler:rp},{id:"capabilities",command:"capabilities",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:ip},{id:"capability-matrix",command:"capability-matrix",description:"Deprecated alias for capabilities --matrix",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:op},...O$,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:$("Maintenance"),handler:ap},{id:"config-validate",command:"config-validate",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:cp},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding as a file under .scipquery/suppressions/ with a required reason",options:C([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")]),renderShape:"custom",docs:$("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:lp},{id:"effectiveness",command:"effectiveness",description:"Per-check effectiveness from the committed outcome ledger: caught, comparison-verified fixes, suppressed, unverified disappearances, and precision",options:C([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:dp},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:up},{id:"setup",command:"setup",description:"Bootstrap this project: enable automatic indexing, install agent skills, refresh the index, verify capabilities, and report health",options:C([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:fp},{id:"setup-agent",command:"setup-agent",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:mp},{id:"setup-ci",command:"setup-ci",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:gp},{id:"uninstall",command:"uninstall",description:"Remove scip-query-owned skill links, project hooks, and managed agent setup blocks",options:C([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:hp},{id:"watch",command:"watch",description:"Watch in the foreground or manage the per-project background refresh service",options:C([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)",kt),p("--cooldown <ms>","Min ms between reindexes; 0 disables spacing (default: 0)",kt),p("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",kt),p("--idle-timeout <ms>","Ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",kt)]),renderShape:"custom",docs:$("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:yp},{id:"status",command:"status",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:vp}];function Dr(e){let t=Ot.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function ko(e){return Dr(e)+1}export{zA as commandDescriptors};
599
- //# sourceMappingURL=command-descriptors-AQWWJNTT.js.map
603
+ [${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let i of n.findingIds.slice(0,df)){let o=t.get(i);o&&ff(o)}let r=n.count-df;r>0&&console.log(` ... and ${r} more in this group (use --full to show all)`)}}function F$(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 N$(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 ff(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${M(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
604
+ [${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 gf=["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"],M$=[Rm,Cm,km,jr,$m,Pm,mf,wm],hf=M$.flat(),_$=new Map(hf.map(e=>[e.id,e]));for(let e of hf)if(!gf.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Nt=gf.map(e=>q$(e));function q$(e){let t=_$.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var B$=Nt.slice(0,Co("plan-context")),V$=Nt.slice(Mr("drift"),Co("self-audit")),H$=Nt.slice(Mr("convergence"),Co("slice")),W$=Nt.slice(Mr("redundant-reexports")),SD=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[u("-l, --language <lang>","Index only this language (can be repeated)",ot,[]),u("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),u("--force","Rebuild even if source inputs are unchanged"),u("--allow-partial","Write an incomplete index when one or more detected languages fail"),u("--indexer-concurrency <n>","Number of language indexers to run at once",qe),u("--json","Output as JSON, including per-shard reuse diagnostics")],renderShape:"custom",docs:$("Indexing",["scip-query reindex"]),handler:Gu},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:$("Indexing"),handler:Uu},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[u("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:$("Indexing"),handler:Ju},...B$,{id:Jr,command:Jr,description:"Internal diff-impact batch worker",hidden:!0,options:[u("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:zu},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:P([u("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:$("Impact"),handler:Ku},...V$,{id:Ur,command:Ur,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:Qu},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded candidate analyses on large indexes"),u("--json","Output as JSON for programmatic consumption"),u("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),u("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:$("Health",["scip-query health --json","scip-query health --baseline"]),handler:Yu},{id:"bench",command:"bench",description:"Benchmark indexing and command runtimes for this repository",options:[u("--json","Output as JSON for programmatic consumption"),u("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),u("--include-heavy","Include expensive full-detector commands in the command matrix"),u("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",ot,[]),u("--timeout-ms <n>","Per-command timeout in milliseconds",qe,18e4),u("--progress","Print benchmark command start/finish progress to stderr"),u("--profile","Enable low-overhead phase profiling in benchmarked commands"),u("--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:Xu},{id:"work-audit",command:"work-audit <profile>",description:"Rank exact repeated computations in a profiling JSONL file by measured avoidable time",options:[u("--top <n>","Maximum repeated-work groups to show",qe,20),u("--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:Zu},{id:"typescript-semantic-compare",command:"typescript-semantic-compare",description:"Compare tsserver reference answers against the ts-morph baseline",hidden:!0,options:[u("-s, --scope <path>","Limit compared definitions to files matching path"),u("--limit <n>","Maximum definitions to compare unless --full is set",qe),u("--max-mismatches <n>","Maximum mismatch details to include in output",$t),u("--full","Compare every indexed TypeScript-like definition"),u("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:ep},...H$,{id:"install-skills",command:"install-skills",description:`Install skills (${Yn.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:$("Maintenance"),handler:rp},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[u("--shared","Deprecated compatibility flag; hooks remain checkout-local and untracked"),u("--remove","Remove managed project hooks and remember the opt-out"),u("--force","Reinstall hooks even after a previous --remove opt-out"),u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:ip},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:ll},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:dl},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:$("Maintenance"),handler:op},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[u("--matrix","Render the project capability matrix (default output)"),u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:sp},{id:"capability-matrix",command:"capability-matrix",description:"Deprecated alias for capabilities --matrix",options:[u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:ap},...W$,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:$("Maintenance"),handler:lp},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query config-validate"]),handler:dp},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding as a file under .scipquery/suppressions/ with a required reason",options:P([u("--reason <text>","Required human reason for accepting the finding"),u("--check <check>","Optional detector/check name to narrow the suppression"),u("--file <path>","Optional file path to narrow the suppression"),u("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:$("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:up},{id:"effectiveness",command:"effectiveness",description:"Per-check effectiveness from the committed outcome ledger: caught, comparison-verified fixes, suppressed, unverified disappearances, and precision",options:P([u("--since <window>","Only count findings first caught in this window (30d, 12w, or an ISO date)"),u("--check <check>","Restrict to one diff-gate check")]),renderShape:"custom",docs:$("Maintenance",["scip-query effectiveness --since 30d","scip-query effectiveness --check echo --json"]),handler:pp},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:mp},{id:"setup",command:"setup",description:"Bootstrap this project: enable automatic indexing, install agent skills, refresh the index, verify capabilities, and report health",options:P([u("--guided","Open the interactive checklist (the default in a terminal)"),u("--yes","Accept recommended setup defaults without prompting"),u("--git-hook","Also install a git pre-commit hook that runs diff-gate"),u("--no-hooks","Skip Codex and Claude Code lifecycle hook installation"),u("--no-skills","Skip user-level agent skill installation"),u("--no-parsers","Skip Tree-sitter AST parser installation and repair"),u("--no-health","Skip the optional full health audit and dossier"),u("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:$("Maintenance",["scip-query setup","scip-query setup --json"]),handler:hp},{id:"setup-agent",command:"setup-agent",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:[u("--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:gp},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[u("--force","Overwrite an existing workflow"),u("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-ci"]),handler:yp},{id:"uninstall",command:"uninstall",description:"Remove scip-query-owned skill links, project hooks, and managed agent setup blocks",options:P([u("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),u("--project","Remove project-local hooks and managed AGENTS.md/CLAUDE.md blocks"),u("--dry-run","List what would be removed without changing files")]),renderShape:"custom",docs:$("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:bp},{id:"watch",command:"watch",description:"Watch in the foreground or manage the per-project background refresh service",options:P([u("--daemon","Ensure the demand-started background service is running"),u("--status","Show background/foreground watcher state"),u("--stop","Stop the watcher or background service for this project"),u("--debounce <ms>","Ms to wait after last change (default: 250)",$t),u("--cooldown <ms>","Min ms between reindexes; 0 disables spacing (default: 0)",$t),u("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",$t),u("--idle-timeout <ms>","Ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",$t)]),renderShape:"custom",docs:$("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:Sp},{id:"status",command:"status",description:"Show index status for this project",options:[u("--json","Output as JSON for programmatic consumption"),u("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:$("Maintenance"),handler:Rp}];function Mr(e){let t=Nt.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function Co(e){return Mr(e)+1}export{SD as commandDescriptors};
605
+ //# sourceMappingURL=command-descriptors-3EJHQLQZ.js.map