scip-query 0.23.0 → 0.26.0

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 (650) hide show
  1. package/CHANGELOG.md +491 -2
  2. package/README.md +111 -122
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-PRVFAGTQ.js +2 -0
  5. package/dist/call-graph-DVPAQV2F.js +2 -0
  6. package/dist/call-graph-evidence-CUtj8V2I.d.ts +19 -0
  7. package/dist/chunk-2FSBGL5P.js +2 -0
  8. package/dist/chunk-2HLAFUCY.js +2 -0
  9. package/dist/chunk-2IWUT6CJ.js +3 -0
  10. package/dist/chunk-2KNN7GTQ.js +2 -0
  11. package/dist/chunk-2LHXRE2B.js +8 -0
  12. package/dist/{chunk-EG2CPZMJ.js → chunk-2YXE77TJ.js} +2 -2
  13. package/dist/chunk-36SGVCGX.js +2 -0
  14. package/dist/chunk-3ABBFPTP.js +2 -0
  15. package/dist/chunk-3IVFU4FD.js +3 -0
  16. package/dist/chunk-3JIQS44J.js +7 -0
  17. package/dist/chunk-3ZRB6DNK.js +7 -0
  18. package/dist/{chunk-6YTSKJJ3.js → chunk-42EOW5VI.js} +1 -1
  19. package/dist/{chunk-6I6L7Z62.js → chunk-4BHGBMNO.js} +2 -2
  20. package/dist/chunk-4BP3UBDG.js +2 -0
  21. package/dist/chunk-4D6RO7G4.js +2 -0
  22. package/dist/chunk-4FEWQ6RH.js +2 -0
  23. package/dist/chunk-4IGEOBG7.js +2 -0
  24. package/dist/chunk-4QZXBUKC.js +2 -0
  25. package/dist/chunk-4WBDEVX2.js +4 -0
  26. package/dist/chunk-4WCUBZU3.js +8 -0
  27. package/dist/chunk-4WTUBQ36.js +40 -0
  28. package/dist/chunk-4XQ4O6IM.js +3 -0
  29. package/dist/chunk-55UQAMZO.js +4 -0
  30. package/dist/chunk-5D2LVK7O.js +125 -0
  31. package/dist/chunk-5IYJ56TT.js +2 -0
  32. package/dist/chunk-5PLMJC7Q.js +2 -0
  33. package/dist/chunk-5TNQJUR2.js +5 -0
  34. package/dist/chunk-62BDNPMI.js +2 -0
  35. package/dist/chunk-64DZ5TXR.js +7 -0
  36. package/dist/chunk-65245JCM.js +2 -0
  37. package/dist/chunk-6FFVZZL4.js +2 -0
  38. package/dist/chunk-6KO5JHAR.js +2 -0
  39. package/dist/chunk-6LRXOOSX.js +2 -0
  40. package/dist/chunk-6LSEIIF7.js +2 -0
  41. package/dist/chunk-6YMNWD3H.js +6 -0
  42. package/dist/chunk-72AD6ZRR.js +5 -0
  43. package/dist/chunk-73AAKPUC.js +4 -0
  44. package/dist/chunk-76CZ77DF.js +2 -0
  45. package/dist/chunk-7VPEEAAG.js +2 -0
  46. package/dist/chunk-7WTPQ4NX.js +14 -0
  47. package/dist/chunk-7Y5T6XDP.js +2 -0
  48. package/dist/chunk-A2IIGFMJ.js +5 -0
  49. package/dist/chunk-AB5KCTEV.js +2 -0
  50. package/dist/chunk-AC566WBP.js +6 -0
  51. package/dist/chunk-AGWFSTXC.js +3 -0
  52. package/dist/chunk-AOSIYPTA.js +2 -0
  53. package/dist/chunk-AUVEWPIF.js +2 -0
  54. package/dist/chunk-B56T42J3.js +25 -0
  55. package/dist/chunk-BIQEF5NE.js +2 -0
  56. package/dist/chunk-BL6XJKTA.js +3 -0
  57. package/dist/chunk-BMKOQJRI.js +2 -0
  58. package/dist/chunk-BOZ4EXBB.js +3 -0
  59. package/dist/chunk-BUTWYEPH.js +2 -0
  60. package/dist/chunk-BZB4QPIP.js +2 -0
  61. package/dist/{chunk-ILTDAWEF.js → chunk-CE357GEE.js} +4 -4
  62. package/dist/chunk-CFN45HFP.js +2 -0
  63. package/dist/chunk-CFYMZFXT.js +368 -0
  64. package/dist/chunk-CN5EH7O3.js +2 -0
  65. package/dist/chunk-D254DNNQ.js +4 -0
  66. package/dist/chunk-D3FDISIC.js +2 -0
  67. package/dist/chunk-D3NX5XIE.js +3 -0
  68. package/dist/chunk-DA7RPPDF.js +3 -0
  69. package/dist/chunk-DDMC3FON.js +3 -0
  70. package/dist/chunk-DIO3FUSG.js +2 -0
  71. package/dist/chunk-DJ2NNSUK.js +3 -0
  72. package/dist/chunk-DKYQIM3C.js +18 -0
  73. package/dist/{chunk-JTQVMR42.js → chunk-DOOEL2IV.js} +2 -2
  74. package/dist/chunk-DVFP6PZI.js +2 -0
  75. package/dist/chunk-E3FDPXZK.js +2 -0
  76. package/dist/chunk-E7YNJLCB.js +2 -0
  77. package/dist/chunk-EFGW5JPH.js +2 -0
  78. package/dist/chunk-EJVTR244.js +13 -0
  79. package/dist/chunk-EOV7RTRZ.js +2 -0
  80. package/dist/chunk-ETOIKRHO.js +2 -0
  81. package/dist/chunk-EYK3ZAO2.js +3 -0
  82. package/dist/chunk-F2V2LPET.js +52 -0
  83. package/dist/chunk-F4LUHJTF.js +2 -0
  84. package/dist/chunk-F4PUT6IT.js +2 -0
  85. package/dist/chunk-F56GCXXS.js +5 -0
  86. package/dist/chunk-FC2EVQRM.js +2 -0
  87. package/dist/chunk-FL7NBMHP.js +3 -0
  88. package/dist/chunk-FMRN2TRL.js +3 -0
  89. package/dist/chunk-FVULPZDF.js +20 -0
  90. package/dist/chunk-GCKCF5FL.js +43 -0
  91. package/dist/chunk-GH2PYF46.js +2 -0
  92. package/dist/chunk-GHJAGXIP.js +2 -0
  93. package/dist/{chunk-WIWY3CRX.js → chunk-GMVSHUKZ.js} +2 -2
  94. package/dist/chunk-GS6KDO4R.js +2 -0
  95. package/dist/chunk-GUUBXNN7.js +2 -0
  96. package/dist/chunk-GVWX5T43.js +80 -0
  97. package/dist/chunk-GZKFETP5.js +2 -0
  98. package/dist/chunk-H4EQHO6J.js +9 -0
  99. package/dist/chunk-H73WY2RM.js +2 -0
  100. package/dist/chunk-H75GSPRV.js +60 -0
  101. package/dist/chunk-HDR3AHSV.js +61 -0
  102. package/dist/chunk-HQBSL74Y.js +2 -0
  103. package/dist/chunk-HRRFKWPZ.js +2 -0
  104. package/dist/chunk-HXENDJC6.js +2 -0
  105. package/dist/chunk-IIBAZNSW.js +21 -0
  106. package/dist/chunk-INLMWEUU.js +12 -0
  107. package/dist/chunk-IWQPAF4F.js +2 -0
  108. package/dist/chunk-IZJ6YUKP.js +35 -0
  109. package/dist/chunk-J2TMAIN5.js +60 -0
  110. package/dist/chunk-J5FJMODQ.js +142 -0
  111. package/dist/chunk-J7HZPIO3.js +2 -0
  112. package/dist/chunk-JEVRKFRL.js +2 -0
  113. package/dist/chunk-JFXSGAEB.js +30 -0
  114. package/dist/chunk-JVRTHGFS.js +3 -0
  115. package/dist/chunk-JYWEX7RR.js +360 -0
  116. package/dist/chunk-K3YL22N6.js +2 -0
  117. package/dist/chunk-K4CN7GXK.js +12 -0
  118. package/dist/chunk-K5TBVXU4.js +30 -0
  119. package/dist/chunk-KDDIE2DP.js +9 -0
  120. package/dist/chunk-KHWRRPV4.js +2 -0
  121. package/dist/chunk-KI6NBKDY.js +14 -0
  122. package/dist/chunk-KU3QRSTH.js +2 -0
  123. package/dist/chunk-KZBJWZJB.js +2 -0
  124. package/dist/chunk-L7GFM3NP.js +3 -0
  125. package/dist/chunk-LMO6PK3V.js +35 -0
  126. package/dist/chunk-LN4YXJJU.js +2 -0
  127. package/dist/chunk-LOVIZBJ4.js +43 -0
  128. package/dist/chunk-LPCRK4A2.js +11 -0
  129. package/dist/chunk-MMHZKBFA.js +2 -0
  130. package/dist/{chunk-M2O5NY6W.js → chunk-MOQQBQRD.js} +2 -2
  131. package/dist/chunk-N2WN6I3L.js +2 -0
  132. package/dist/chunk-N3ORQT7L.js +2 -0
  133. package/dist/chunk-NAZ3RAIW.js +2 -0
  134. package/dist/chunk-NDUNO5JQ.js +2 -0
  135. package/dist/chunk-NEIWRNAZ.js +4 -0
  136. package/dist/chunk-NJJMVD65.js +2 -0
  137. package/dist/chunk-NLOQOBXI.js +20 -0
  138. package/dist/chunk-NOLZOVCU.js +2 -0
  139. package/dist/chunk-NOWINRRN.js +2 -0
  140. package/dist/chunk-NZAXKGRL.js +16 -0
  141. package/dist/chunk-O2C4UILI.js +2 -0
  142. package/dist/chunk-O3RHA6ZT.js +3 -0
  143. package/dist/chunk-O4UZSPPI.js +3 -0
  144. package/dist/chunk-OGFV2BUX.js +2 -0
  145. package/dist/chunk-OZCJXZK6.js +499 -0
  146. package/dist/chunk-P6ODM7BY.js +2 -0
  147. package/dist/{chunk-XBGWL66K.js → chunk-PAVGPRHJ.js} +2 -2
  148. package/dist/chunk-PH52RA7D.js +2 -0
  149. package/dist/chunk-PKN354TH.js +3 -0
  150. package/dist/chunk-PWOASWEG.js +11 -0
  151. package/dist/chunk-QIWXRW72.js +2 -0
  152. package/dist/chunk-QJRMOK5N.js +2 -0
  153. package/dist/{chunk-YXPUP5G2.js → chunk-QOIXNWQR.js} +2 -2
  154. package/dist/chunk-QXEUDXBT.js +3 -0
  155. package/dist/chunk-QYUVVBMR.js +6 -0
  156. package/dist/chunk-QZ7KQZRN.js +2 -0
  157. package/dist/chunk-R6LQBUDH.js +2 -0
  158. package/dist/chunk-RBS42E55.js +20 -0
  159. package/dist/chunk-RSJKPCFX.js +26 -0
  160. package/dist/chunk-S6CZA3MV.js +2 -0
  161. package/dist/chunk-STMVAHJP.js +2 -0
  162. package/dist/chunk-SYVPTTVW.js +2 -0
  163. package/dist/chunk-T3I6NHBH.js +2 -0
  164. package/dist/chunk-T6DK3ZP7.js +2 -0
  165. package/dist/chunk-TKD34PHN.js +4 -0
  166. package/dist/chunk-TNNQFH7W.js +2 -0
  167. package/dist/chunk-TNV7SSUF.js +2 -0
  168. package/dist/chunk-TO7ZR3EH.js +8 -0
  169. package/dist/chunk-TOU3CHK4.js +2 -0
  170. package/dist/chunk-TRBI4UKT.js +2 -0
  171. package/dist/chunk-TZCVNCAN.js +4 -0
  172. package/dist/chunk-U4LZA5LL.js +3 -0
  173. package/dist/chunk-U5RIG3JP.js +3 -0
  174. package/dist/chunk-UP5KXN2I.js +2 -0
  175. package/dist/chunk-UQFR3NDH.js +5 -0
  176. package/dist/chunk-UXYXF7GV.js +2 -0
  177. package/dist/chunk-VB3GOKOS.js +2 -0
  178. package/dist/chunk-VF5JZICY.js +2 -0
  179. package/dist/chunk-VTY3VK6E.js +2 -0
  180. package/dist/chunk-VX2O4RIS.js +2 -0
  181. package/dist/chunk-WKPV2TDZ.js +2 -0
  182. package/dist/chunk-WOFQ5DTB.js +2 -0
  183. package/dist/chunk-WS4C6TCK.js +2 -0
  184. package/dist/chunk-WXU3DGPU.js +2 -0
  185. package/dist/chunk-X6RMKHJQ.js +81 -0
  186. package/dist/{chunk-4ILJCCXV.js → chunk-XHMN6ZX7.js} +2 -2
  187. package/dist/chunk-XHTVFLWW.js +2 -0
  188. package/dist/chunk-XKIDJCIK.js +2 -0
  189. package/dist/chunk-XTYTYZPT.js +2 -0
  190. package/dist/chunk-Y2JHHTTA.js +2 -0
  191. package/dist/chunk-YGVRMGYN.js +4 -0
  192. package/dist/chunk-YNQCGEQE.js +2 -0
  193. package/dist/chunk-YOQVEXVE.js +14 -0
  194. package/dist/chunk-YRT2WLYY.js +2 -0
  195. package/dist/chunk-YTAP5Y2G.js +2 -0
  196. package/dist/chunk-YTYWI7VB.js +2 -0
  197. package/dist/chunk-YULZRALL.js +2 -0
  198. package/dist/chunk-Z33WQG4Q.js +2 -0
  199. package/dist/chunk-ZGTYGDMF.js +16 -0
  200. package/dist/chunk-ZHMRSZFD.js +43 -0
  201. package/dist/chunk-ZHSP366W.js +10 -0
  202. package/dist/chunk-ZIBYCYKK.js +7 -0
  203. package/dist/{chunk-GAS2LJMP.js → chunk-ZLADLUE6.js} +3 -3
  204. package/dist/chunk-ZO4YXUT6.js +4 -0
  205. package/dist/{chunk-HYO3NP5Q.js → chunk-ZR4HBC2H.js} +2 -2
  206. package/dist/cli-main.js +6 -6
  207. package/dist/cli.js +1 -1
  208. package/dist/{code-B17qEMbt.d.ts → code-BNyrCF3_.d.ts} +3 -2
  209. package/dist/code-IL5WH3NZ.js +2 -0
  210. package/dist/code-result-json-ANTBEDFP.js +4 -0
  211. package/dist/command-descriptors-HEEMDHTU.js +222 -0
  212. package/dist/deps-EOWFC6FD.js +2 -0
  213. package/dist/direct-navigation-Y5B6OSIQ.js +3 -0
  214. package/dist/{exploration-topology-BG4v30HZ.d.ts → exploration-topology-CSgEyAz-.d.ts} +3 -1
  215. package/dist/files-K4AI3JUM.js +2 -0
  216. package/dist/frontend-profile-roles-D7eCum8P.d.ts +10 -0
  217. package/dist/{health-CPp2Jf1Z.d.ts → health-BtfmNrfa.d.ts} +58 -74
  218. package/dist/hierarchy-6W5NDIFI.js +2 -0
  219. package/dist/imports-WH365QY4.js +2 -0
  220. package/dist/index.d.ts +13 -1
  221. package/dist/index.js +1 -1
  222. package/dist/members-K3PHMF5S.js +2 -0
  223. package/dist/methods-E7KVMBX4.js +2 -0
  224. package/dist/output-continuation-command-BJSY67SN.js +3 -0
  225. package/dist/output-pagination-UZJ5ACIX.js +24 -0
  226. package/dist/postinstall.js +1 -1
  227. package/dist/project-reindex-EP24WT4X.js +3 -0
  228. package/dist/queries/affected.js +1 -1
  229. package/dist/queries/architecture.d.ts +15 -4
  230. package/dist/queries/architecture.js +1 -1
  231. package/dist/queries/bottlenecks.js +1 -1
  232. package/dist/queries/by-kind.js +1 -1
  233. package/dist/queries/call-graph.d.ts +3 -1
  234. package/dist/queries/call-graph.js +1 -1
  235. package/dist/queries/change-surface.d.ts +1 -0
  236. package/dist/queries/change-surface.js +1 -1
  237. package/dist/queries/cleanup-plan.d.ts +3 -3
  238. package/dist/queries/cleanup-plan.js +1 -1
  239. package/dist/queries/co-change.d.ts +20 -2
  240. package/dist/queries/co-change.js +1 -1
  241. package/dist/queries/code.d.ts +1 -1
  242. package/dist/queries/code.js +1 -1
  243. package/dist/queries/complexity.d.ts +6 -3
  244. package/dist/queries/complexity.js +1 -1
  245. package/dist/queries/context.d.ts +1 -7
  246. package/dist/queries/context.js +1 -1
  247. package/dist/queries/coupling.js +1 -1
  248. package/dist/queries/cycles.js +1 -1
  249. package/dist/queries/dead.d.ts +2 -0
  250. package/dist/queries/dead.js +1 -1
  251. package/dist/queries/decorative-checkers.js +1 -1
  252. package/dist/queries/dependence-slice.d.ts +46 -22
  253. package/dist/queries/dependence-slice.js +1 -1
  254. package/dist/queries/dependency-depth.d.ts +1 -7
  255. package/dist/queries/dependency-depth.js +1 -1
  256. package/dist/queries/deps.js +1 -1
  257. package/dist/queries/diff-impact.d.ts +3 -1
  258. package/dist/queries/diff-impact.js +1 -1
  259. package/dist/queries/doc-drift.js +1 -1
  260. package/dist/queries/drift.d.ts +1 -1
  261. package/dist/queries/drift.js +1 -1
  262. package/dist/queries/duplicate-bodies.d.ts +29 -2
  263. package/dist/queries/duplicate-bodies.js +1 -1
  264. package/dist/queries/entry-map.d.ts +2 -4
  265. package/dist/queries/entry-map.js +1 -1
  266. package/dist/queries/evidence.d.ts +121 -61
  267. package/dist/queries/evidence.js +1 -1
  268. package/dist/queries/fan.js +1 -1
  269. package/dist/queries/files.js +1 -1
  270. package/dist/queries/health.d.ts +1 -1
  271. package/dist/queries/health.js +1 -1
  272. package/dist/queries/hierarchy.d.ts +2 -2
  273. package/dist/queries/hierarchy.js +1 -1
  274. package/dist/queries/hotspots.d.ts +1 -1
  275. package/dist/queries/hotspots.js +1 -1
  276. package/dist/queries/imports.d.ts +1 -0
  277. package/dist/queries/imports.js +1 -1
  278. package/dist/queries/incomplete-migration.d.ts +3 -3
  279. package/dist/queries/incomplete-migration.js +1 -1
  280. package/dist/queries/index.d.ts +17 -65
  281. package/dist/queries/index.js +1 -1
  282. package/dist/queries/locality-candidates.d.ts +4 -4
  283. package/dist/queries/locality-candidates.js +1 -1
  284. package/dist/queries/members.d.ts +2 -2
  285. package/dist/queries/members.js +1 -1
  286. package/dist/queries/methods.js +1 -1
  287. package/dist/queries/not-implemented.d.ts +2 -6
  288. package/dist/queries/not-implemented.js +1 -1
  289. package/dist/queries/outline.js +1 -1
  290. package/dist/queries/passthrough-candidates.d.ts +9 -1
  291. package/dist/queries/passthrough-candidates.js +1 -1
  292. package/dist/queries/react-component-duplicates.d.ts +19 -3
  293. package/dist/queries/react-component-duplicates.js +1 -1
  294. package/dist/queries/react-hook-candidates.d.ts +22 -3
  295. package/dist/queries/react-hook-candidates.js +1 -1
  296. package/dist/queries/react-large-component-pressure.d.ts +17 -3
  297. package/dist/queries/react-large-component-pressure.js +1 -1
  298. package/dist/queries/recent-duplicates.js +1 -1
  299. package/dist/queries/redundant-reexports.d.ts +4 -14
  300. package/dist/queries/redundant-reexports.js +1 -1
  301. package/dist/queries/refs.d.ts +4 -1
  302. package/dist/queries/refs.js +1 -1
  303. package/dist/queries/review.d.ts +188 -0
  304. package/dist/queries/review.js +2 -0
  305. package/dist/queries/similar-files.d.ts +7 -10
  306. package/dist/queries/similar-files.js +1 -1
  307. package/dist/queries/similar-signatures.js +1 -1
  308. package/dist/queries/similar.d.ts +19 -1
  309. package/dist/queries/similar.js +1 -1
  310. package/dist/queries/slice-cohesion.d.ts +205 -0
  311. package/dist/queries/slice-cohesion.js +2 -0
  312. package/dist/queries/source-inspection.d.ts +6 -202
  313. package/dist/queries/source-inspection.js +1 -1
  314. package/dist/queries/source-search.d.ts +2 -3
  315. package/dist/queries/source-search.js +1 -1
  316. package/dist/queries/stats.d.ts +1 -0
  317. package/dist/queries/stats.js +1 -1
  318. package/dist/queries/surface.js +1 -1
  319. package/dist/queries/symbols.js +1 -1
  320. package/dist/queries/system.d.ts +4 -2
  321. package/dist/queries/system.js +1 -1
  322. package/dist/queries/test-quality.d.ts +1 -1
  323. package/dist/queries/test-quality.js +1 -1
  324. package/dist/queries/twin-drift.d.ts +23 -7
  325. package/dist/queries/twin-drift.js +1 -1
  326. package/dist/queries/unused-imports.js +1 -1
  327. package/dist/queries/unused-params.d.ts +3 -15
  328. package/dist/queries/unused-params.js +1 -1
  329. package/dist/queries/vue-component-duplicates.js +1 -1
  330. package/dist/queries/vue-composable-candidates.js +1 -1
  331. package/dist/queries/vue-large-view-pressure.js +1 -1
  332. package/dist/query-service-fastpath.js +5 -5
  333. package/dist/query-service-server.js +4 -4
  334. package/dist/refs-CCBJG7WK.js +2 -0
  335. package/dist/refs-pagination-DRNLVU4S.js +2 -0
  336. package/dist/reindex-worker.js +79 -29
  337. package/dist/reindex.js +45 -45
  338. package/dist/repository-cache-worker.js +2 -0
  339. package/dist/runtime.d.ts +8 -8
  340. package/dist/runtime.js +3 -4
  341. package/dist/rust-semantic-session-server.js +1 -1
  342. package/dist/rust-semantic-session-worker.js +1 -1
  343. package/dist/rust-semantic-worker.js +1 -1
  344. package/dist/service-queries-2WAJI7R6.js +6 -0
  345. package/dist/source-inspection-91U9zdO3.d.ts +341 -0
  346. package/dist/{source-search-types-Dwz8KeuW.d.ts → source-search-types-DWGYNg8M.d.ts} +15 -2
  347. package/dist/stats-G7DIV6VU.js +2 -0
  348. package/dist/surface-IO55UALI.js +2 -0
  349. package/dist/system-ZBMSHJXU.js +2 -0
  350. package/dist/{queries/trace.d.ts → trace-BMjw3prn.d.ts} +1 -18
  351. package/dist/typescript-indexer.js +2 -0
  352. package/dist/typescript-mailbox-worker.js +1 -1
  353. package/dist/watch-server.js +3 -3
  354. package/docs/AGENT_GUIDE.md +19 -128
  355. package/docs/CLI_JSON_OUTPUT.md +21 -17
  356. package/docs/COMMAND_REFERENCE.md +34 -49
  357. package/docs/CURRENT_COMMANDS.md +123 -0
  358. package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +0 -40
  359. package/docs/DETECTOR_GUIDE.md +55 -12
  360. package/docs/PRODUCT_VISION.md +135 -0
  361. package/docs/PROPERTY_TESTING.md +73 -0
  362. package/docs/REVIEW.md +76 -0
  363. package/docs/SKILLS.md +51 -0
  364. package/docs/WINDOWS_SIDECAR_RELEASE.md +12 -3
  365. package/docs/accuracy-audit-checklist.md +70 -13
  366. package/docs/analyzer-inventory.md +2 -2
  367. package/docs/locality-analyzer-design.md +9 -9
  368. package/package.json +18 -80
  369. package/scripts/evidence-product-contract.mjs +7 -3
  370. package/scripts/record-review-coverage.mjs +118 -0
  371. package/scripts/scip-windows-provenance.mjs +29 -19
  372. package/skills/scip-architecture-review/SKILL.md +57 -0
  373. package/skills/scip-architecture-review/agents/openai.yaml +4 -0
  374. package/skills/scip-architecture-review/references/design-checks.md +17 -0
  375. package/skills/scip-explore/SKILL.md +15 -59
  376. package/skills/scip-explore/agents/openai.yaml +3 -3
  377. package/skills/scip-explore/references/external-evidence.md +2 -2
  378. package/skills/scip-explore/references/information-model.md +26 -29
  379. package/skills/scip-explore/scripts/capture-evidence.mjs +68 -34
  380. package/skills/scip-integrity-audit/SKILL.md +53 -181
  381. package/skills/scip-integrity-audit/agents/openai.yaml +3 -3
  382. package/skills/scip-integrity-audit/references/integrity-probes.md +27 -0
  383. package/skills/scip-plan/SKILL.md +39 -65
  384. package/skills/scip-plan/agents/openai.yaml +2 -2
  385. package/skills/scip-query/SKILL.md +28 -81
  386. package/skills/scip-query/agents/openai.yaml +2 -2
  387. package/skills/scip-query/references/command-guide.md +169 -0
  388. package/skills/scip-setup/SKILL.md +4 -2
  389. package/skills/scip-setup/agents/openai.yaml +3 -3
  390. package/dist/by-kind-XI2CSWEY.js +0 -2
  391. package/dist/call-graph-UONR6JR5.js +0 -2
  392. package/dist/call-graph-evidence-lZa2dwQA.d.ts +0 -11
  393. package/dist/chunk-26CT72HM.js +0 -2
  394. package/dist/chunk-2E7CX53V.js +0 -2
  395. package/dist/chunk-2GRUZAQF.js +0 -43
  396. package/dist/chunk-2LDBDR6J.js +0 -29
  397. package/dist/chunk-2OOY75BW.js +0 -2
  398. package/dist/chunk-2R3V3PSD.js +0 -4
  399. package/dist/chunk-2WC2OEDO.js +0 -4
  400. package/dist/chunk-35NLDRZC.js +0 -2
  401. package/dist/chunk-3AF4TUFK.js +0 -3
  402. package/dist/chunk-3D3QG236.js +0 -2
  403. package/dist/chunk-3FHOF22C.js +0 -21
  404. package/dist/chunk-3JKSW6LJ.js +0 -2
  405. package/dist/chunk-3L2ZBPEX.js +0 -133
  406. package/dist/chunk-3PJABJSU.js +0 -2
  407. package/dist/chunk-3SVF22I5.js +0 -2
  408. package/dist/chunk-3WR4E3A3.js +0 -3
  409. package/dist/chunk-4FTZ4P5G.js +0 -2
  410. package/dist/chunk-4UX2F3JX.js +0 -2
  411. package/dist/chunk-4WNW27SX.js +0 -2
  412. package/dist/chunk-5ENOG4VP.js +0 -61
  413. package/dist/chunk-64BFSI5I.js +0 -2
  414. package/dist/chunk-66DVSJQG.js +0 -455
  415. package/dist/chunk-6HFCYNYE.js +0 -9
  416. package/dist/chunk-6PQNKL3G.js +0 -3
  417. package/dist/chunk-6V5CNXL6.js +0 -2
  418. package/dist/chunk-6VVV4WRR.js +0 -4
  419. package/dist/chunk-7BWFZPPZ.js +0 -2
  420. package/dist/chunk-7CYG22FH.js +0 -2
  421. package/dist/chunk-7F45LJKI.js +0 -2
  422. package/dist/chunk-7IWV2EG3.js +0 -3
  423. package/dist/chunk-7KCZELVM.js +0 -2
  424. package/dist/chunk-AFHTBORT.js +0 -2
  425. package/dist/chunk-AVRYW5OZ.js +0 -2
  426. package/dist/chunk-B3X6KU75.js +0 -2
  427. package/dist/chunk-B5D7QPBE.js +0 -4
  428. package/dist/chunk-BBCIS4DX.js +0 -16
  429. package/dist/chunk-BDUVI7TO.js +0 -3
  430. package/dist/chunk-BE7ZZTMC.js +0 -2
  431. package/dist/chunk-BHVUJOCQ.js +0 -3
  432. package/dist/chunk-BJT7LSPK.js +0 -3
  433. package/dist/chunk-BKVWUP7Y.js +0 -2
  434. package/dist/chunk-BQGB4HBD.js +0 -2
  435. package/dist/chunk-BRV7PIFF.js +0 -2
  436. package/dist/chunk-CEEZJXEF.js +0 -2
  437. package/dist/chunk-CIYLO6SI.js +0 -7
  438. package/dist/chunk-CJZXN4NU.js +0 -2
  439. package/dist/chunk-CNO7TOKL.js +0 -2
  440. package/dist/chunk-COF23M5F.js +0 -2
  441. package/dist/chunk-CWFP7GM5.js +0 -2
  442. package/dist/chunk-D2DHWI3D.js +0 -2
  443. package/dist/chunk-D4N5SQ2M.js +0 -4
  444. package/dist/chunk-DBRSYFXR.js +0 -2
  445. package/dist/chunk-DHUIOLDT.js +0 -2
  446. package/dist/chunk-DIRJWYBM.js +0 -6
  447. package/dist/chunk-DIUFNHRJ.js +0 -35
  448. package/dist/chunk-DRENNWRG.js +0 -2
  449. package/dist/chunk-DTZCKZEU.js +0 -4
  450. package/dist/chunk-DULC3QFP.js +0 -5
  451. package/dist/chunk-DYGHBZ2N.js +0 -16
  452. package/dist/chunk-E5R6AQ73.js +0 -40
  453. package/dist/chunk-E73UNJTF.js +0 -38
  454. package/dist/chunk-EKV5HX33.js +0 -2
  455. package/dist/chunk-EQHFIL6T.js +0 -3
  456. package/dist/chunk-ESIQ66Z7.js +0 -2
  457. package/dist/chunk-EVFUMY4R.js +0 -3
  458. package/dist/chunk-F7DY272B.js +0 -2
  459. package/dist/chunk-FBN2FGXG.js +0 -2
  460. package/dist/chunk-FDLOBR6P.js +0 -4
  461. package/dist/chunk-FESCRNVV.js +0 -5
  462. package/dist/chunk-FFRKR4EQ.js +0 -2
  463. package/dist/chunk-FGA2U4OR.js +0 -8
  464. package/dist/chunk-FIQRSHVM.js +0 -2
  465. package/dist/chunk-FPYLNQPT.js +0 -2
  466. package/dist/chunk-FRUSVINH.js +0 -2
  467. package/dist/chunk-GSP44ENC.js +0 -2
  468. package/dist/chunk-GUFSG5TX.js +0 -2
  469. package/dist/chunk-GYIZ4NXB.js +0 -2
  470. package/dist/chunk-GZIUDL6G.js +0 -2
  471. package/dist/chunk-H5EXS3HM.js +0 -2
  472. package/dist/chunk-HCXEQRFF.js +0 -18
  473. package/dist/chunk-HEHOQQKH.js +0 -2
  474. package/dist/chunk-HKGFPJ4T.js +0 -4
  475. package/dist/chunk-HLZTEXRA.js +0 -2
  476. package/dist/chunk-HOENASQM.js +0 -3
  477. package/dist/chunk-HVF5VBG6.js +0 -2
  478. package/dist/chunk-I55I7XXP.js +0 -2
  479. package/dist/chunk-IDFEUFKS.js +0 -2
  480. package/dist/chunk-IHGQTTVW.js +0 -2
  481. package/dist/chunk-IICPE7B2.js +0 -20
  482. package/dist/chunk-IL676XCC.js +0 -18
  483. package/dist/chunk-IW5XQG5G.js +0 -2
  484. package/dist/chunk-IZDPJ2QI.js +0 -2
  485. package/dist/chunk-J66VOFW6.js +0 -5
  486. package/dist/chunk-JFMEXGFE.js +0 -2
  487. package/dist/chunk-JGKUET5J.js +0 -3
  488. package/dist/chunk-JS4PGXMV.js +0 -3
  489. package/dist/chunk-JWTGMPIT.js +0 -80
  490. package/dist/chunk-JYR66JN5.js +0 -5
  491. package/dist/chunk-KFOYCQAJ.js +0 -9
  492. package/dist/chunk-KLFEXGQA.js +0 -2
  493. package/dist/chunk-KMVGRIO2.js +0 -2
  494. package/dist/chunk-KYSDI3GE.js +0 -5
  495. package/dist/chunk-L6PJPETJ.js +0 -29
  496. package/dist/chunk-LDVT66YM.js +0 -2
  497. package/dist/chunk-LEECKFCJ.js +0 -2
  498. package/dist/chunk-LMZ5PRUV.js +0 -2
  499. package/dist/chunk-LQRQN2XA.js +0 -2
  500. package/dist/chunk-LXABEJX3.js +0 -2
  501. package/dist/chunk-MNV5FSBW.js +0 -3
  502. package/dist/chunk-MPQ4OTBM.js +0 -2
  503. package/dist/chunk-MTDBHTSF.js +0 -2
  504. package/dist/chunk-MV3CDXPI.js +0 -38
  505. package/dist/chunk-MWN53KRN.js +0 -60
  506. package/dist/chunk-MXNGIEPU.js +0 -3
  507. package/dist/chunk-N2ZSIIGR.js +0 -117
  508. package/dist/chunk-N5B2NILC.js +0 -5
  509. package/dist/chunk-NJITK2GP.js +0 -2
  510. package/dist/chunk-NOGJXYFO.js +0 -2
  511. package/dist/chunk-NOYBFVJA.js +0 -554
  512. package/dist/chunk-NWQXSFFU.js +0 -3
  513. package/dist/chunk-ODDUPDP7.js +0 -13
  514. package/dist/chunk-OLIWTZI3.js +0 -3
  515. package/dist/chunk-OLNV6I6U.js +0 -2
  516. package/dist/chunk-OR2E3AGZ.js +0 -2
  517. package/dist/chunk-OSR2GEHQ.js +0 -2
  518. package/dist/chunk-OSSESPDX.js +0 -3
  519. package/dist/chunk-OWOOWNJ5.js +0 -7
  520. package/dist/chunk-P42EIXTA.js +0 -2
  521. package/dist/chunk-PJFGPYTU.js +0 -2
  522. package/dist/chunk-PP7KNN7L.js +0 -2
  523. package/dist/chunk-PU7T5QYQ.js +0 -2
  524. package/dist/chunk-PWWAJSKV.js +0 -74
  525. package/dist/chunk-PZL5T7SU.js +0 -73
  526. package/dist/chunk-QBE3YX64.js +0 -23
  527. package/dist/chunk-QGVTFRY2.js +0 -7
  528. package/dist/chunk-QOJONDS7.js +0 -2
  529. package/dist/chunk-QU5XRYB5.js +0 -4
  530. package/dist/chunk-QUU5OBVK.js +0 -11
  531. package/dist/chunk-RBLQNW26.js +0 -20
  532. package/dist/chunk-RTQ7NEKG.js +0 -81
  533. package/dist/chunk-SQXRS7BG.js +0 -4
  534. package/dist/chunk-SSK6LDPC.js +0 -2
  535. package/dist/chunk-SZHGTCPP.js +0 -7
  536. package/dist/chunk-T4N4P2K5.js +0 -16
  537. package/dist/chunk-TA3QKLLU.js +0 -2
  538. package/dist/chunk-TEBQMNVI.js +0 -43
  539. package/dist/chunk-TPFHAQ2G.js +0 -2
  540. package/dist/chunk-TQPCBMWT.js +0 -5
  541. package/dist/chunk-TQZV7KV4.js +0 -2
  542. package/dist/chunk-TRNAEQ6P.js +0 -3
  543. package/dist/chunk-TY7CRN3Z.js +0 -2
  544. package/dist/chunk-UHFYCMZO.js +0 -35
  545. package/dist/chunk-UICY4GTQ.js +0 -7
  546. package/dist/chunk-UVGEWT4Y.js +0 -26
  547. package/dist/chunk-UXW33INU.js +0 -29
  548. package/dist/chunk-VMPRET3I.js +0 -5
  549. package/dist/chunk-VNLGKHS6.js +0 -6
  550. package/dist/chunk-VQILFTEH.js +0 -2
  551. package/dist/chunk-VUPHCS7Y.js +0 -57
  552. package/dist/chunk-VVZSBTSU.js +0 -23
  553. package/dist/chunk-VZRNID6A.js +0 -2
  554. package/dist/chunk-W5OXRYGE.js +0 -7
  555. package/dist/chunk-W6STWDQI.js +0 -57
  556. package/dist/chunk-W7CXK74K.js +0 -2
  557. package/dist/chunk-WB3WYIRE.js +0 -4
  558. package/dist/chunk-WDNVY4E7.js +0 -20
  559. package/dist/chunk-WK46TNUM.js +0 -3
  560. package/dist/chunk-WNTFFKAX.js +0 -12
  561. package/dist/chunk-WOIKCX6A.js +0 -2
  562. package/dist/chunk-WUN6KBHV.js +0 -2
  563. package/dist/chunk-WYCTJDVR.js +0 -2
  564. package/dist/chunk-WYPL7GF7.js +0 -2
  565. package/dist/chunk-XDAUYDFT.js +0 -2
  566. package/dist/chunk-XDQMU3BT.js +0 -2
  567. package/dist/chunk-XFA4SSO3.js +0 -3
  568. package/dist/chunk-XGZEP6GR.js +0 -8
  569. package/dist/chunk-XPDPNWTQ.js +0 -368
  570. package/dist/chunk-XRYABF57.js +0 -8
  571. package/dist/chunk-YBGKCQIS.js +0 -2
  572. package/dist/chunk-YEN6CYC7.js +0 -16
  573. package/dist/chunk-YF5IB2LF.js +0 -2
  574. package/dist/chunk-YI2AWIHC.js +0 -3
  575. package/dist/chunk-YPWBKGFU.js +0 -2
  576. package/dist/chunk-YPWHBBIS.js +0 -2
  577. package/dist/chunk-YSH6U3L4.js +0 -3
  578. package/dist/chunk-YU5DZUZI.js +0 -10
  579. package/dist/chunk-YWO5DDRC.js +0 -16
  580. package/dist/chunk-Z4CDXYNQ.js +0 -2
  581. package/dist/chunk-ZF5KHH7C.js +0 -2
  582. package/dist/chunk-ZOHS7AQV.js +0 -21
  583. package/dist/chunk-ZTI4SBFV.js +0 -3
  584. package/dist/code-MI6F2TTU.js +0 -2
  585. package/dist/code-result-json-FXALY4HE.js +0 -2
  586. package/dist/command-descriptors-P34VABY5.js +0 -343
  587. package/dist/dataflow-4KEMJPC6.js +0 -2
  588. package/dist/dependence-slice-R7FPWD5M.js +0 -2
  589. package/dist/deps-7EMQUYUT.js +0 -2
  590. package/dist/direct-navigation-6YO234F2.js +0 -3
  591. package/dist/entry-map-KOOLR26E.js +0 -2
  592. package/dist/files-OPIPJIGZ.js +0 -2
  593. package/dist/graph-evidence-Bjyky2V4.d.ts +0 -126
  594. package/dist/hierarchy-QPD2CAER.js +0 -2
  595. package/dist/imports-M6HUXRXC.js +0 -2
  596. package/dist/members-I5MEFOCT.js +0 -2
  597. package/dist/methods-5JYGGHXA.js +0 -2
  598. package/dist/next-anchor-candidates-BwMczMvX.d.ts +0 -90
  599. package/dist/output-continuation-command-UPQAAKBP.js +0 -3
  600. package/dist/output-pagination-3OFL2MJV.js +0 -19
  601. package/dist/project-reindex-UKKQ5PLS.js +0 -3
  602. package/dist/queries/anchors.d.ts +0 -123
  603. package/dist/queries/anchors.js +0 -2
  604. package/dist/queries/complexity-hotspots.d.ts +0 -40
  605. package/dist/queries/complexity-hotspots.js +0 -2
  606. package/dist/queries/convergence.d.ts +0 -33
  607. package/dist/queries/convergence.js +0 -2
  608. package/dist/queries/dataflow.d.ts +0 -77
  609. package/dist/queries/dataflow.js +0 -2
  610. package/dist/queries/deep-chains.d.ts +0 -5
  611. package/dist/queries/deep-chains.js +0 -2
  612. package/dist/queries/extract-candidates.d.ts +0 -52
  613. package/dist/queries/extract-candidates.js +0 -2
  614. package/dist/queries/isolated.d.ts +0 -24
  615. package/dist/queries/isolated.js +0 -2
  616. package/dist/queries/plan-context.d.ts +0 -33
  617. package/dist/queries/plan-context.js +0 -2
  618. package/dist/queries/reference-neighborhood.d.ts +0 -4
  619. package/dist/queries/reference-neighborhood.js +0 -2
  620. package/dist/queries/reference-reachability.d.ts +0 -48
  621. package/dist/queries/reference-reachability.js +0 -2
  622. package/dist/queries/self-audit.d.ts +0 -63
  623. package/dist/queries/self-audit.js +0 -2
  624. package/dist/queries/similar-chains.d.ts +0 -48
  625. package/dist/queries/similar-chains.js +0 -2
  626. package/dist/queries/slice.d.ts +0 -4
  627. package/dist/queries/slice.js +0 -2
  628. package/dist/queries/stale-abstractions.d.ts +0 -72
  629. package/dist/queries/stale-abstractions.js +0 -2
  630. package/dist/queries/system-map.d.ts +0 -449
  631. package/dist/queries/system-map.js +0 -2
  632. package/dist/queries/trace.js +0 -2
  633. package/dist/queries/twin-ab.d.ts +0 -66
  634. package/dist/queries/twin-ab.js +0 -2
  635. package/dist/queries/value-flow.d.ts +0 -43
  636. package/dist/queries/value-flow.js +0 -2
  637. package/dist/queries/wrapper-candidates.d.ts +0 -34
  638. package/dist/queries/wrapper-candidates.js +0 -2
  639. package/dist/refs-PSU4JZZW.js +0 -2
  640. package/dist/refs-pagination-JG6CJMRC.js +0 -2
  641. package/dist/slice-HYRATV64.js +0 -2
  642. package/dist/source-snippet-_wrcgmZc.d.ts +0 -15
  643. package/dist/stats-OOJ74B32.js +0 -2
  644. package/dist/surface-VTGDYWF5.js +0 -2
  645. package/dist/symbol-resolution-WD5EU5JE.js +0 -2
  646. package/dist/system-LRQNFOR2.js +0 -2
  647. package/dist/trace-F4B6OLL4.js +0 -2
  648. package/dist/value-flow-VRPZY72V.js +0 -2
  649. package/skills/concrete-plan/SKILL.md +0 -8
  650. package/skills/concrete-plan/agents/openai.yaml +0 -4
@@ -0,0 +1,2 @@
1
+ import{b as o}from"./chunk-76CZ77DF.js";import"./chunk-STMVAHJP.js";import"./chunk-NJJMVD65.js";import"./chunk-BIQEF5NE.js";import"./chunk-YTAP5Y2G.js";import"./chunk-NDUNO5JQ.js";import"./chunk-X6RMKHJQ.js";import"./chunk-JEVRKFRL.js";import"./chunk-GZKFETP5.js";import"./chunk-BL6XJKTA.js";import"./chunk-O4UZSPPI.js";import"./chunk-B3PYOSCX.js";import"./chunk-HRRFKWPZ.js";import"./chunk-HGFDYOVB.js";import"./chunk-QZ7KQZRN.js";import"./chunk-TKD34PHN.js";import"./chunk-2HLAFUCY.js";import"./chunk-U5RIG3JP.js";import"./chunk-62BDNPMI.js";var[r,c]=process.argv.slice(2);if(!r||!c)console.error("repository-cache-worker: expected <project-root> <cli-version>"),process.exitCode=1;else try{o(r,c)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1}
2
+ //# sourceMappingURL=repository-cache-worker.js.map
package/dist/runtime.d.ts CHANGED
@@ -210,6 +210,8 @@ declare class Watcher {
210
210
  private reindexInFlight;
211
211
  private lastReindexEnd;
212
212
  /** Generation identity the watcher last saw; a different published identity means someone else refreshed. */
213
+ /** Source events invalidate freshness observations even when the published generation is unchanged. */
214
+ private publicationObservationInvalidated;
213
215
  private lastObservedGeneration;
214
216
  private readonly publishedGeneration;
215
217
  private readonly indexFreshness;
@@ -267,15 +269,12 @@ declare class Watcher {
267
269
  private clearReconcileTimer;
268
270
  private readPublishedGeneration;
269
271
  /**
270
- * A manual `reindex` or `setup` publishes a generation the watcher did not
271
- * produce. When one appears while work is pending (dirty, cooldown, budget
272
- * pause, or a debounce wait) and the published index matches the working
273
- * tree, the pending refresh is already satisfied: drop it and report the
274
- * suppression instead of holding "changes pending" until the budget window
275
- * or cooldown expires and then re-running a refresh that would only be
276
- * suppressed as fresh anyway. Returns true when pending work was cleared.
272
+ * Clear pending work when an accepted publication already matches the source,
273
+ * including a publication from another producer or a source edit that restores
274
+ * indexed bytes. Definitive observations are reused only until the next input event.
277
275
  */
278
- private reconcileExternalPublication;
276
+ private reconcilePublishedIndex;
277
+ private hasFreshPublishedIndex;
279
278
  private pollGitState;
280
279
  private readGitState;
281
280
  private readFilesystemGitState;
@@ -300,6 +299,7 @@ interface InstallSkillsResult {
300
299
  declare function installSkills(opts?: {
301
300
  quiet?: boolean;
302
301
  homeDir?: string;
302
+ all?: boolean;
303
303
  }): InstallSkillsResult;
304
304
 
305
305
  /**
package/dist/runtime.js CHANGED
@@ -1,5 +1,4 @@
1
- import{C as lt,D as pt,M as ht,O as ue,b as at,c as ct,i as On,j as En,k as wn,q as dt,z as ut}from"./chunk-WNTFFKAX.js";import{c as qe,u as ce,x as st}from"./chunk-5ENOG4VP.js";import{c as Ue,e as q,g as Ke,h as Ye}from"./chunk-TRNAEQ6P.js";import"./chunk-DHEQMPLW.js";import"./chunk-JWTGMPIT.js";import{$ as Xe,C as $e,D as Ge,Da as it,Fa as ot,I as Je,Ia as K,J as v,L as Be,T as He,X as Qe,_ as ze,aa as de,ba as Ze,f as Le,fa as et,g as ae,i as B,ia as tt,ja as nt,k as Fe,ma as rt,n as p,p as C,q as k,r as D,ra as H,s as We,t as g,v as L,x as U}from"./chunk-N5B2NILC.js";import{existsSync as or}from"fs";import{randomUUID as sr}from"crypto";import{isAbsolute as Ki,join as At,relative as Yi,resolve as Qi}from"path";var E=1,T=2,Pn="./node_modules/scip-query/docs/schemas/project-config.schema.json";function le(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(a){return{kind:"malformed",reason:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}if(!p(t))return{kind:"malformed",reason:"project config must be a JSON object"};let n=t.schemaVersion;if(n!==void 0&&!Number.isInteger(n))return{kind:"malformed",reason:"schemaVersion must be an integer"};let r=n===void 0?E:n;if(r!==E&&r!==T)return{kind:"unsupported",schemaVersion:r,direction:r<E?"older":"future"};let i=t.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=Y(t),s=r!==T||typeof t.$schema!="string";return r===E?{kind:"legacy",sourceVersion:E,config:o,needsMigration:s}:{kind:"supported",sourceVersion:T,config:o,needsMigration:s}}function Y(e){let t=e,{$schema:n,schemaVersion:r,...i}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:Pn,schemaVersion:T,...i}}function pe(e){return`${JSON.stringify(Y(e),null,2)}
2
- `}import{createHash as kn}from"crypto";var f=1,I=2,Q=1,W=1,F="sha256",me=1;function Ct(e,t,n){if(!g(e)||!D(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:Q,canonicalizationVersion:W,hashAlgorithm:F,projection:{name:e,version:t},digest:kn(F).update(Tn(e,t,n)).digest("hex")}}function Tn(e,t,n){return`{"canonicalizationVersion":${W},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function ge(e){if(!p(e))return{kind:"malformed",reason:"observation receipt must be an object"};let t=e.schemaVersion;if(!Number.isInteger(t))return{kind:"malformed",reason:"observation receipt schemaVersion must be an integer"};if(t===f)return Vn(e)?{kind:"legacy",schemaVersion:f,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===I)return Dn(e)?{kind:"supported",schemaVersion:I,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<f?"older":"future"}}function z(e){let t=ge(e);return t.kind==="legacy"||t.kind==="supported"}function ye(e,t){return{collaborationDomain:w(b(e,n=>n.facts.collaborationDomain),b(t,n=>n.facts.collaborationDomain)),repositoryLineage:w(b(e,n=>n.facts.repositoryLineage),b(t,n=>n.facts.repositoryLineage)),workspaceInstance:w(b(e,n=>n.facts.workspaceInstance),b(t,n=>n.facts.workspaceInstance)),wholeContent:w(b(e,n=>n.facts.wholeContent),b(t,n=>n.facts.wholeContent)),relevantInputs:_n(e,t),indexInput:w(b(e,n=>n.facts.index?.inputs),b(t,n=>n.facts.index?.inputs)),indexGeneration:An(e,t),observationStability:jn(e,t)}}function X(e,t,n=ye(e,t)){let r=[["collaborationDomain",n.collaborationDomain],["wholeContent",n.wholeContent],["observationStability",n.observationStability]],i=[];for(let[s,a]of r)a.state!=="established"&&i.push(`${s}:${a.state}`);for(let[s,a]of[["left",e],["right",t]]){let c=Mn(a);c!=="not-applicable"&&c!=="established"&&i.push(`${s}IndexAlignment:${c}`)}let o=r.some(([,s])=>s.state==="disproven")||i.some(s=>s.endsWith(":disproven"));return{policyVersion:me,authority:i.length===0?"completion":o?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:i}}function bt(e){return e.schemaVersion===f?e.index?.generationIdentity:e.facts.index?.generation.digest}function vt(e){return e.schemaVersion===f?void 0:e.facts.workspaceInstance?.digest}function Rt(e){if(e.schemaVersion===f)return e.index?.alignment??"not-established";let t=e.stabilityProofs.filter(n=>n.source!=="process");return t.some(n=>n.kind==="invalidated")?"invalidated":t.length>0&&t.every(n=>n.kind==="immutable"||n.kind==="fixed-snapshot")?"fixed":t.some(n=>n.kind==="bracketed")?"bracketed":"not-established"}function _n(e,t){let n=ft(e),r=ft(t);return[...new Set([...n.keys(),...r.keys()])].sort().map(o=>{let s=n.get(o),a=r.get(o),c=s?.subject??a?.subject??o,d=s?.identity.projection.name??a?.identity.projection.name??o;return{subject:c,projection:d,judgment:w(s?.identity,a?.identity)}})}function ft(e){return e.schemaVersion!==I?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function An(e,t){return e.schemaVersion===f&&t.schemaVersion===f?Nn(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===f||t.schemaVersion===f?R("unknown",["legacy-fact-not-comparable"],gt(e),gt(t)):w(e.facts.index?.generation,t.facts.index?.generation)}function Nn(e,t){let n=e?[{kind:"legacy-index-generation",value:e}]:[],r=t?[{kind:"legacy-index-generation",value:t}]:[];return e===void 0||t===void 0?St(n,r):R(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,r)}function w(e,t){let n=e?[{kind:"identity",identity:e}]:[],r=t?[{kind:"identity",identity:t}]:[];return!e||!t?St(n,r):Ce(e,t)?R(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,r):R("unknown",["identity-projections-not-comparable"],n,r)}function jn(e,t){if(e.schemaVersion===f||t.schemaVersion===f)return R("unknown",["legacy-fact-not-comparable"],[],[]);let n=yt(e),r=yt(t),i=mt(e),o=mt(t);return i==="invalidated"||o==="invalidated"?R("disproven",[...i==="invalidated"?["left-observation-invalidated"]:[],...o==="invalidated"?["right-observation-invalidated"]:[]],n,r):i!=="fixed"||o!=="fixed"?R("unknown",[...i==="no-repository-source"?["left-observation-has-no-repository-source"]:i!=="fixed"?["left-observation-not-fixed"]:[],...o==="no-repository-source"?["right-observation-has-no-repository-source"]:o!=="fixed"?["right-observation-not-fixed"]:[]],n,r):R("established",["all-observed-sources-fixed"],n,r)}function mt(e){let t=e.observedSources.filter(r=>r.kind!=="process");if(t.length===0)return"no-repository-source";let n=new Map(e.stabilityProofs.map(r=>[r.source,r.kind]));return t.some(r=>n.get(r.kind)==="invalidated")?"invalidated":t.every(r=>{let i=n.get(r.kind);return i==="immutable"||i==="fixed-snapshot"})?"fixed":"unknown"}function Mn(e){if(e.schemaVersion!==I)return e.index?"unknown":"not-applicable";if(!e.observedSources.some(r=>r.kind==="index-generation"))return"not-applicable";let t=e.facts.index?.inputs;if(!t)return"unknown";let n=(e.facts.relevantInputs??[]).find(r=>Ce(r.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function b(e,t){return e.schemaVersion===I?t(e):void 0}function gt(e){return e.schemaVersion===f&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===I&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function yt(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function St(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return R("unknown",[n],e,t)}function R(e,t,n,r){return{state:e,reasons:t,facts:{left:n,right:r}}}function Ce(e,t){return e.schemaVersion===t.schemaVersion&&e.canonicalizationVersion===t.canonicalizationVersion&&e.hashAlgorithm===t.hashAlgorithm&&e.projection.name===t.projection.name&&e.projection.version===t.projection.version}function Vn(e){if(!p(e))return!1;let t=e.index,n=e.worktree;return It(e.observedAt)&&g(e.projectIdentity)&&Bn(e.authorityKind)&&(t===void 0||p(t)&&g(t.generationIdentity)&&(t.source==="immutable"||t.source==="legacy")&&(t.alignment==="not-certified"||t.alignment==="leased"))&&(n===void 0||p(n)&&g(n.identity)&&typeof n.clean=="boolean"&&(n.headCommit===void 0||g(n.headCommit))&&(n.treeOid===void 0||g(n.treeOid)))&&Jn(e.authorityKind,t,n)}function Dn(e){if(!p(e))return!1;let t=e.facts,n=e.observedSources,r=e.stabilityProofs;if(!It(e.observedAt)||!p(t)||!Array.isArray(n)||n.length===0||!n.every(Fn)||!fe(n,c=>c.kind)||!Array.isArray(r)||!r.every(Wn)||!fe(r,c=>c.source)||r.some(c=>!n.some(d=>d.kind===c.source))||!r.every(c=>Gn(c,t))||["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(c=>t[c]!==void 0&&!x(t[c])))return!1;let o=t.relevantInputs;if(o!==void 0&&(!Array.isArray(o)||!o.every(Ln)||!fe(o,c=>`${c.subject}\0${c.identity.projection.name}`)))return!1;let s=t.index;if(s!==void 0&&(!p(s)||!x(s.generation)||s.inputs!==void 0&&!x(s.inputs)||s.source!=="immutable"&&s.source!=="legacy"))return!1;let a=e.diagnostics;return(a===void 0||p(a)&&(a.clean===void 0||typeof a.clean=="boolean")&&(a.headCommit===void 0||g(a.headCommit))&&(a.treeOid===void 0||g(a.treeOid)))&&$n(t,n)}function x(e){return!p(e)||!p(e.projection)?!1:e.schemaVersion===Q&&e.canonicalizationVersion===W&&e.hashAlgorithm===F&&g(e.projection.name)&&D(e.projection.version)&&We(e.digest)}function Ln(e){return p(e)&&g(e.subject)&&x(e.identity)}function Fn(e){return p(e)&&xt(e.kind)&&(e.identity===void 0||x(e.identity))}function Wn(e){return p(e)&&xt(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function $n(e,t){let n=e.index,r=t.find(c=>c.kind==="index-generation");if(r){if(!p(n)||!x(n.generation)||r.identity&&!he(r.identity,n.generation))return!1}else if(n!==void 0)return!1;let i=e.workspaceInstance,o=t.find(c=>c.kind==="live-workspace");if(o?.identity&&(!x(i)||!he(o.identity,i)))return!1;let s=e.wholeContent,a=t.find(c=>c.kind==="repository-snapshot");return!(a?.identity&&(!x(s)||!he(a.identity,s)))}function Gn(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&p(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function he(e,t){return Ce(e,t)&&e.digest===t.digest}function Jn(e,t,n){return e==="index-worktree"?t!==void 0&&n!==void 0:e==="index-only"?t!==void 0&&n===void 0:e==="worktree-only"?t===void 0&&n!==void 0:e==="process-local"&&t===void 0&&n===void 0}function Bn(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function xt(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function It(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function fe(e,t){return new Set(e.map(t)).size===e.length}import{createHash as Ot}from"crypto";import{closeSync as Un,fstatSync as Et,lstatSync as qn,openSync as Hn,readlinkSync as Kn,realpathSync as Yn,rmSync as Qn}from"fs";import{dirname as kt,resolve as zn}from"path";var Xn=2e3,Zn=10,er=3,ee=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${Pt(r)}, but found ${Pt(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest};function Tt(e,t,n={}){let r=tr(e),i=nr(r,n.lockTimeoutMs??Xn,n.monotonicNow??q);try{let o=Math.max(0,Math.floor(n.maxRetries??er));for(let s=0;;s+=1){let a=Z(r),c=t(a,s);if(c.kind==="unchanged")return{changed:!1,attempts:s+1,previous:a,current:a};n.onBeforeCommit?.({attempt:s,snapshot:a,mutation:c});let d=Z(r);if(!ir(a.revision,d.revision)){if(s<o)continue;throw new ee(r,a.revision,d.revision)}try{rr(r,c,a.revision)}catch(l){if(l.code==="EEXIST"){let u=Z(r);if(s<o)continue;throw new ee(r,a.revision,u.revision)}throw l}return{changed:!0,attempts:s+1,previous:a,current:Z(r)}}}finally{i.release()}}function tr(e){let t;try{if(!qn(e).isSymbolicLink())return e;t=Kn(e)}catch{return e}try{return Yn(e)}catch{return zn(kt(e),t)}}function Z(e){for(let t=0;t<4;t+=1){let n;try{n=Hn(e,"r");let r=wt(Et(n)),i=Be(n,{maxBytes:Ge,inputKind:"revisioned text file"}),o=wt(Et(n));if(!_t(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:Ot("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:Ot("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&Un(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function nr(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=qe(r,{kind:"revisioned-file-mutation",detail:{target:e}});if(o.kind==="acquired")return o.lock;if(n()>=i)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Zn)}}function rr(e,t,n){if(t.kind==="delete"){if(!n.exists)return;Qn(e),He(kt(e));return}let r=t.mode??n.identity?.mode;n.exists?Ke(e,t.text,{durability:"durable",mode:r}):Ye(e,t.text,{durability:"durable",mode:r})}function ir(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&_t(e.identity,t.identity))}function wt(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function _t(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function Pt(e){return e.exists?e.hash.slice(0,12):"<absent>"}var $=".scipquery.json",Nt=2e3,jt=5e3,be=jt,Mt=15*6e4,ve={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},ar={enabled:!1,autoStart:!1,allowExpensiveRebuild:!1,debounceMs:Nt,cooldownMs:be,gitPollMs:2e3,idleTimeoutMs:Mt,autoRefresh:!0,ignore:[],resourceBudget:ve};var to=new Set(L);function te(e){let t=At(e,$);if(!or(t))return{};let n;try{n=Je(t,{maxBytes:$e,inputKind:"scip-query project config"})}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${$} at ${t}: ${i}`,{cause:r})}return Dt(le(n),t,"read").config}function Vt(e){return{...ar,...e.watch,cooldownMs:Math.max(jt,e.watch?.cooldownMs??be),resourceBudget:{...ve,...e.watch?.resourceBudget}}}function cr(e,t){return dr(e,t).configPath}function dr(e,t){let n=At(e,$),r=sr(),i={collaborationDomainId:r,languages:t,watch:{enabled:!0,debounceMs:Nt,cooldownMs:be,gitPollMs:2e3,idleTimeoutMs:Mt,autoRefresh:!0,resourceBudget:{...ve}}},o=Tt(n,s=>{if(!s.revision.exists)return{kind:"write",text:pe(i)};let a=ur(s,i);return a.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:pe({...a.config,collaborationDomainId:r})}});return{configPath:n,changed:o.changed}}function ur(e,t){if(!e.revision.exists)return{config:Y(t),needsMigration:!0};let n=Dt(le(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function Dt(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${$} at ${t}: ${e.reason}`:`Cannot update ${t}: the latest project config is ${e.reason}.`;throw new Error(`${i} The file was left untouched.`)}let r=n==="read"?`invalid ${$} at ${t}`:`Cannot update ${t}: the latest project config is invalid`;throw new Error(`${r} (unsupported ${e.direction} schemaVersion ${e.schemaVersion}; this scip-query reads legacy v${E} and current v${T}). Upgrade scip-query before retrying; the file was left untouched.`)}import{existsSync as we,lstatSync as Cr,statSync as Yt,watch as br}from"fs";import{EventEmitter as vr}from"events";import{basename as Rr,dirname as Qt,isAbsolute as Pe,join as y,relative as zt,resolve as Xt}from"path";import{watch as Sr}from"chokidar";import xr from"ignore";function Re(e){let t=JSON.stringify(e);return Buffer.byteLength(t)<=65536?t:void 0}import{existsSync as Lt,lstatSync as lr}from"fs";import{resolve as pr}from"path";function Ft(e,t,n,r={}){let i=new Date().toISOString();if(!Lt(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Lt(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let o=U(v(n.metaPath,"reindex metadata"));if(o.kind==="unsupported")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Reindex metadata version ${o.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(o.kind==="malformed")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not decode reindex metadata: ${o.reason}`,remedy:"Run: scip-query reindex"};let s=o.metadata,a=t.languages??dt(e),c=s.fingerprint,d=n.cacheDir&&r.gitContext&&ue(r.gitContext,n.cacheDir,c)?c:void 0,l=n.cacheDir&&r.gitContext&&d&&fr(d,a,t)&&mr(e,d,t)?r.gitObservation?.context===r.gitContext?r.gitContext:ze(r.gitContext):void 0,u=r.gitObservation&&r.gitObservation.context===r.gitContext?r.gitObservation.projectFileInventorySequence:void 0,h=l?.clean&&Xe(e,void 0,{cachedInventoryAfterSequence:u})?l:void 0,m=n.cacheDir&&h&&d&&ue(h,n.cacheDir,d)?d:hr(e,a,t),O=[...s.indexedLanguages??[]].sort(),V=o.capabilities.publishableGeneration&&Fe(B(s.fingerprint),m)&&JSON.stringify(O)===JSON.stringify(m.languages),P=ht(n.dbPath,n.metaPath),Me=P.state==="invalid"||P.state==="drifted",se=V?pt(n.dbPath,m,O):void 0,Ve=se?.state==="incomplete",De=V&&!Me&&!Ve;return{state:De?"fresh":"stale",checkedAt:i,metaPath:n.metaPath,updatedAt:s.updatedAt,lastRefresh:s.lastRefresh,reason:Me?`SQLite generation requires repair: ${P.reason}`:Ve?`SQLite generation is missing ${se.missingDocumentCount} indexed source document(s): ${se.missingPaths.join(", ")}`:V?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:De?void 0:"Run: scip-query reindex"}}catch(o){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${o instanceof Error?o.message:String(o)}`,remedy:"Run: scip-query reindex"}}}function hr(e,t,n){return ot(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}function fr(e,t,n){let r=gr(t,n);return e.version===r.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function mr(e,t,n){if(!(t.languages.includes("typescript")||!!t.clojureConfigPath))return!0;let i=it(e);if(t.clojureConfigPath){let o=Le(t.clojureConfigPath);if(!i.includes(o))return!1;try{if(!lr(pr(e,o)).isFile())return!1}catch{return!1}}return!t.languages.includes("typescript")||nt(e,n.indexer?.typescript?.projectMode,n.indexer?.typescript?.projects??[],i)}function gr(e,t){return K(e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}var Zt=5e3,Oe=class{projectRoot;config;watchConfig;outputDb;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;budgetInspector;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;budgetTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;pendingChanges=new Map;pendingChangesComplete=!0;pendingChangesIncompleteReason;reindexInFlight=!1;lastReindexEnd=0;lastObservedGeneration=null;publishedGeneration;indexFreshness;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;reconcileTimer=null;lastGitState=null;preferFilesystemGitState=!0;watchGitLayout=null;localCacheWatchPath;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Vt(t.config),this.outputDb=t.outputDb??y(rt(this.projectRoot,t.config),"index.db"),this.preferFilesystemGitState=t.gitReader===void 0,this.localCacheWatchPath=qr(this.projectRoot,Qt(this.outputDb)),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onReindexError=t.onReindexError??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.clock=t.clock??wr,en.set(this,Hr(t.stopTimeoutMs??Zt,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??on(),this.subscriptionFactory=t.subscriptionFactory??Pr,this.budgetInspector=t.budgetInspector??lt,this.publishedGeneration=t.publishedGeneration??ce,this.indexFreshness=t.indexFreshness??Ur,this.lastObservedGeneration=this.readPublishedGeneration(),tn.set(this,{projectRoot:t.projectRoot,config:t.config,gitReader:t.gitReader??Qe,languages:sn(t.languages??t.config.languages),typeScriptInputPaths:null,stagedIndexEntries:null}),this.gitignoreFilter=st(t.projectRoot),this.extraIgnore=xr(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore),xe(this)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,re(this).errors=[],this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let t=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.clearGitPollTimer(),this.clearReconcileTimer();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let r=[...re(this).closures],i=Or(this),o=this.clock.now()+i;return this.stopPromise=this.finishStop(t,r,n,o,i).catch(s=>{throw this.stopInProgress=!1,s}),this.stopPromise}requestRefresh(t,n={}){if(!this.stopped){if(this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`),!n.immediate||this.reindexInFlight||this.status.state==="cooldown"||this.status.state==="budget-paused"){this.scheduleReindex(t);return}this.pendingTrigger=Se(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(r,i)=>this.isIgnoredWatchPath(r,i?.isDirectory()??!1),usePolling:t,ignorePermissionErrors:!0,...t?{interval:5e3,binaryInterval:1e4}:{}});n.on("all",(r,i)=>{!this.stopped&&r!=="addDir"&&r!=="unlinkDir"&&this.handleFileChange(r,i)}),n.on("error",r=>this.handleSourceWatcherError(n,r,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,r){if(this.markPendingChangesIncomplete("source-watcher-error"),r||this.sourcePollingFallbackStarted||!Wr(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==t),Er(re(this),t,i=>this.onError(i));try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(t,n){let r=this.relativeWatchPath(t);if(!r)return!1;if(Jt(r,this.localCacheWatchPath))return!0;let i=n?`${r}/`:r;return this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(t,n){let r=this.relativeWatchPath(n);if(!r||r===".."||r.startsWith("../")||Jt(r,this.localCacheWatchPath)||this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)||r.endsWith("index.db")||r.endsWith("index.scip")||r.endsWith("index.db.tmp")||Rr(r).startsWith(ut))return;r===".scipquery.json"&&qt(this,this.projectRoot);let i=Ht(this,t,r);i!==null&&(i||this.markPendingChangesIncomplete(`unsupported-source-event:${t}`),this.scheduleReindex({kind:"watch-source",detail:r},i?[{path:r,kind:i}]:void 0,i!==void 0))}relativeWatchPath(t){let n=Pe(t)?t:y(this.projectRoot,t);return zt(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t,n,r=!1){this.pendingTrigger=Se(this.pendingTrigger,t),r||this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`);for(let o of n??[])this.recordPendingChange(o);if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});let o=this.activeOperation;o&&_.get(this)!==o&&(_.set(this,o),o.cancel().then(s=>{s.state==="degraded"&&!this.stopped&&this.onError(new Error(s.reason))},s=>{this.stopped||this.onError(s instanceof Error?s:new Error(String(s)))}));return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}if(this.status.state==="budget-paused"){this.dirty=!0,this.setStatus({...this.status,dirty:!0});return}this.clearDebounceTimer();let i=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:i}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped||this.reconcileExternalPublication())return;let t=this.inspectBudget(),n=this.watchConfig.allowExpensiveRebuild&&t.state!=="paused";if(t.state==="paused"&&t.reason!=="rebuild-count"){this.dirty=!0;let c=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:c,dirty:!0,reason:t.detail,rebuilt:t.rebuilt,estimatedWriteBytes:t.estimatedWriteBytes}),this.clearBudgetTimer(),this.budgetTimer=this.clock.setTimeout(()=>{this.budgetTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},Math.min(2147483647,Math.max(1,c-this.wallNow())));return}let r=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&r<this.watchConfig.cooldownMs){let c=this.watchConfig.cooldownMs-r;this.dirty=!0;let d=this.wallNow()+c;this.setStatus({state:"cooldown",until:d,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},c);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let i=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let o=this.consumePendingChangeJournal(),s=this.wallNow();this.setStatus({state:"indexing",startedAt:s});let a=this.reindexRunner.start(this.reindexRequest(i,n,o));this.activeOperation=a,a.completion.then(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),ne.set(this,0),this.stopped)return;if(_.get(this)===a){if(this.restorePendingChangeJournal(o),this.dirty){let l=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:l,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"});return}xe(this),this.lastObservedGeneration=this.readPublishedGeneration();let d=!1;try{d=this.onReindexComplete(c,i,{pendingChanges:this.dirty})===!0}catch(l){this.onError(l instanceof Error?l:new Error(String(l)))}if(this.dirty&&!this.stopped){if(d){let u=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),this.onRefreshSuppressed(u),this.setStatus({state:"idle"});return}let l=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:l,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let d=c instanceof Error?c:new Error(String(c));this.restorePendingChangeJournal(o);let l=rn(d),u=0;if(l?(u=(ne.get(this)??0)+1,ne.set(this,u),this.dirty=!0,this.pendingTrigger=Se(this.pendingTrigger,i)):ne.set(this,0),!l&&_.get(this)!==a&&(this.onReindexError(d,i),this.onError(d)),this.dirty){let h=l?Vr(this.watchConfig.cooldownMs,u):this.watchConfig.cooldownMs,m=this.wallNow()+h;this.setStatus({state:"cooldown",until:m,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},h);return}this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===a&&(this.activeOperation=null),_.get(this)===a&&_.delete(this)})}async finishStop(t,n,r,i,o){let s=[],a=t.map(async h=>{try{await h.close()}catch(m){s.push(`watch subscription close failed: ${String(m)}`)}});a.push(...n),r&&a.push((async()=>{try{let h=await r.cancel();h.state==="degraded"&&s.push(h.reason)}catch(h){s.push(`reindex cancellation failed: ${h instanceof Error?h.message:String(h)}`)}})());let c=a.length,d=a.map(h=>h.finally(()=>{c-=1})),l=await Ir(d,i,this.clock),u=re(this);return s.push(...u.errors),u.errors=[],l?this.stopInProgress=!1:(s.push(`watch shutdown exceeded the ${o}ms deadline with ${c} operation(s) still pending`),Promise.all(d).then(()=>{this.stopInProgress=!1})),s.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:s.join("; ")}),{state:"degraded",reasons:s}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}inspectBudget(){try{return this.budgetInspector(this.outputDb,this.watchConfig.resourceBudget,new Date(this.wallNow()))}catch(t){return{state:"paused",reason:"activity-evidence",until:this.wallNow()+this.watchConfig.resourceBudget.windowMs,rebuilt:0,estimatedWriteBytes:0,detail:`reindex activity evidence could not be read: ${t instanceof Error?t.message:String(t)}`}}}reindexRequest(t,n=!0,r){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:t,changeJournal:r,allowExpensiveRebuild:n}}setStatus(t){this.status=t,t.state==="cooldown"||t.state==="budget-paused"?this.armReconcileTimer(t.until):this.clearReconcileTimer(),this.onStatus(t)}recordPendingChange(t){if(this.pendingChanges.size>=1024&&!this.pendingChanges.has(t.path)){this.pendingChanges.clear(),this.markPendingChangesIncomplete("change-entry-limit");return}let n=this.pendingChanges.get(t.path),r=Lr(n,t.kind);r===null?this.pendingChanges.delete(t.path):this.pendingChanges.set(t.path,r)}markPendingChangesIncomplete(t){this.pendingChangesComplete=!1,this.pendingChangesIncompleteReason??=t}consumePendingChangeJournal(){let t=ce(this.outputDb),n=[...this.pendingChanges.entries()].map(([s,a])=>({path:s,kind:a})).sort((s,a)=>s.path.localeCompare(a.path)),r=this.pendingChangesComplete,i=this.pendingChangesIncompleteReason;t||(r=!1,i??="accepted-generation-unavailable");let o={version:1,baseGeneration:t,complete:r,...i?{incompleteReason:i}:{},entries:n};return Re(o)||(o={version:1,baseGeneration:t,complete:!1,incompleteReason:"change-journal-byte-limit",entries:[]}),this.resetPendingChanges(),o}restorePendingChangeJournal(t){let n=[...this.pendingChanges.entries()].map(([o,s])=>({path:o,kind:s})),r=this.pendingChangesComplete,i=this.pendingChangesIncompleteReason;this.resetPendingChanges(),t.complete||this.markPendingChangesIncomplete(t.incompleteReason??"failed-reindex");for(let o of t.entries)this.recordPendingChange(o);r||this.markPendingChangesIncomplete(i??"failed-reindex");for(let o of n)this.recordPendingChange(o)}resetPendingChanges(){this.pendingChanges.clear(),this.pendingChangesComplete=!0,this.pendingChangesIncompleteReason=void 0}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}clearBudgetTimer(){this.budgetTimer&&(this.clock.clearTimeout(this.budgetTimer),this.budgetTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(S(this).stagedIndexEntries=Kt(this.projectRoot,S(this).gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}armReconcileTimer(t){this.clearReconcileTimer();let n=t-this.wallNow();if(n<=0||!(this.watchConfig.gitPollMs>0))return;let r=Math.min(this.watchConfig.gitPollMs,n);this.reconcileTimer=this.clock.setTimeout(()=>{this.reconcileTimer=null,!(this.stopped||this.reconcileExternalPublication())&&(this.status.state==="cooldown"||this.status.state==="budget-paused")&&this.armReconcileTimer(this.status.until)},r),this.reconcileTimer.unref?.()}clearReconcileTimer(){this.reconcileTimer&&(this.clock.clearTimeout(this.reconcileTimer),this.reconcileTimer=null)}readPublishedGeneration(){try{return this.publishedGeneration(this.outputDb)}catch{return null}}reconcileExternalPublication(){if(this.stopped||this.reindexInFlight||!(this.dirty||this.status.state==="budget-paused"||this.status.state==="cooldown"||this.status.state==="waiting"))return!1;let n=this.readPublishedGeneration();if(n===null||n===this.lastObservedGeneration)return!1;this.lastObservedGeneration=n;let r;try{r=this.indexFreshness(this.projectRoot,this.config,this.outputDb)}catch{return!1}if(r!=="fresh")return!1;let i=this.pendingTrigger??{kind:"unknown"};return this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),xe(this),this.onRefreshSuppressed({...i,detail:`a generation published outside the watcher is fresh${i.detail?` (${i.detail})`:""}`}),this.setStatus({state:"idle"}),!0}pollGitState(){if(this.reindexInFlight||this.stopped)return;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;if(!r&&!i)return;let o=S(this),s=o.stagedIndexEntries,a=Kt(this.projectRoot,o.gitReader);o.stagedIndexEntries=a;let c=zr(this.projectRoot,o.gitReader,t,n,s,a,r,i),d=null;if(c!==null&&(c.includes(".scipquery.json")&&qt(this,this.projectRoot),d=c.filter(u=>Ht(this,"add",u)!==null),d.length===0))return;let l=d?.map(u=>({path:u,kind:we(y(this.projectRoot,u))?"change":"delete"}));r&&i?this.scheduleReindex({kind:"watch-git-state",detail:Ie("HEAD and index changed",d)},l,l!==void 0):r?this.scheduleReindex({kind:"watch-git-head",detail:Ie("HEAD changed",d)},l,l!==void 0):i&&this.scheduleReindex({kind:"watch-git-index",detail:Ie(n.indexPath??"index changed",d)},l,l!==void 0)}readGitState(){if(this.preferFilesystemGitState){let t=this.readFilesystemGitState();if(t)return t}return this.readGitStateFromGit()}readFilesystemGitState(){let t=this.watchGitLayout??$r(this.projectRoot);if(!t)return null;this.watchGitLayout=t;let n=Gr(t.gitDir);return n?Ut(n,t.indexPath):null}readGitStateFromGit(){let t=S(this).gitReader,n=de(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let r=Ze(this.projectRoot,n);return Ut(de(this.projectRoot,["rev-parse","--verify","HEAD"],t),r)}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function Ir(e,t,n){if(e.length===0)return!0;let r=Promise.all(e).then(()=>!0),i=Math.max(0,t-n.now()),o=null,s=new Promise(c=>{o=n.setTimeout(()=>c(!1),i)}),a=await Promise.race([r,s]);return a&&o&&n.clearTimeout(o),a}var $t=new WeakMap,en=new WeakMap,tn=new WeakMap,_=new WeakMap,ne=new WeakMap;function re(e){let t=$t.get(e);if(t)return t;let n={closures:new Set,errors:[]};return $t.set(e,n),n}function Or(e){return en.get(e)??Zt}function S(e){let t=tn.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function Er(e,t,n){let r=Promise.resolve().then(()=>t.close()).catch(i=>{let o=`watch subscription close failed during polling fallback: ${String(i)}`;e.errors.push(o),n(new Error(o))});e.closures.add(r),r.then(()=>e.closures.delete(r))}function nn(e,t=Ue){let{projectRoot:n,config:r,languages:i,pnpmWorkspaces:o,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:c,indexerConcurrency:d,trigger:l}=e,u=te(n),h=Object.keys(u).length>0?u:r,m=H(n,h),O=h.indexer?.typescript,V=h.indexer?.clojure,P=t(process.pid);if(!P)throw new Error(`Could not establish watcher process identity for reindex worker ownership (pid ${process.pid}).`);return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:n,SCIP_REINDEX_OUTPUT_SCIP:m.indexPath,SCIP_REINDEX_OUTPUT_DB:m.dbPath,SCIP_REINDEX_LANGUAGES:(h.languages??i)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(h.indexerConcurrency??d??""),SCIP_REINDEX_PNPM_WORKSPACES:O?.pnpmWorkspaces??o?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:O?.projectMode??s,projects:O?.projects??a??[],maxHeapMb:O?.maxHeapMb}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:V?.configPath??c??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_CHANGE_JOURNAL:e.changeJournal?Re(e.changeJournal)??"":"",SCIP_REINDEX_ALLOW_EXPENSIVE:e.allowExpensiveRebuild===!1?"0":"1",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(P)}}}var wr={now:q,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Pr=(e,t)=>kr(process.platform,t.usePolling)?new Ee(e):Sr(e,t);function kr(e,t){return e==="darwin"&&t!==!0}var G=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="RecursiveSourceWatchError"}},Ee=class{events=new vr;watcher;constructor(t){this.watcher=br(t,{recursive:!0},(n,r)=>{if(r===null){this.events.emit("error",new G("Recursive source watcher omitted the changed path."));return}let i=y(t,r.toString());this.events.emit("all",Tr(n,i),i)}),this.watcher.on("error",n=>{this.events.emit("error",new G(`Recursive source watcher failed: ${n.message}`,n))})}on=(t,n)=>(this.events.on(t,n),this);close(){this.watcher.close()}};function Tr(e,t){return e==="change"?"change":we(t)?Yt(t).isDirectory()?"addDir":"add":"unlink"}var _r=15*6e4,Ar=1e3,Nr=64*1024;function jr(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function Gt(e,t){let n=e instanceof Error?e.message:String(e),r=t.stderrTail.trim()||t.stdoutTail.trim();return r?`${n}
3
- ${r}`:n}function Mr(e,t){return Object.assign(new Error(e,t===void 0?void 0:{cause:t}),{retryable:!0})}function rn(e){return e instanceof Error&&"retryable"in e&&e.retryable===!0}function Vr(e,t){let n=e*2**Math.min(5,Math.max(0,t-1));return Math.max(e,Math.min(3e4,n))}function on(e={}){let t=e.timeoutMs??_r,n=e.terminationGraceMs??Ar,r=e.maxOutputBytes??Nr,i=e.resolveLaunch??nn;return{start(o){let s=i(o),a=new AbortController,c=jr(),d=!1,l=ct({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:r,maxStderrBytes:r,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(u=>{if(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0){let h=Gt(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c);throw u.status===75?Mr(h):new Error(h)}return u.durationMs}).catch(u=>{throw rn(u)?u:(u instanceof at&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(Gt(u,c),{cause:u}))}).finally(()=>{d=!0});return{completion:l,async cancel(){d||a.abort();try{await l}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Se(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}function Dr(e){if(e==="add")return"add";if(e==="change")return"change";if(e==="unlink")return"delete"}function Lr(e,t){return e?e==="add"?t==="delete"?null:"add":e==="delete"&&t==="add"?"change":t:t}function Fr(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function Wr(e){return e instanceof G||Fr(e)}var ke=/^[0-9a-f]{40,64}$/i;function Jt(e,t){return e===".git"||e.startsWith(".git/")||e==="node_modules"||e.startsWith("node_modules/")||e.endsWith("/node_modules")||e.includes("/node_modules/")?!0:t!==void 0&&(e===t||e.startsWith(`${t}/`))}function $r(e){let t=y(e,".git");try{let n=Cr(t),r;if(n.isDirectory())r=t;else if(n.isFile()){let i=/^gitdir:\s*(.+)\s*$/m.exec(v(t,"Git directory marker"));if(!i?.[1])return null;let o=i[1].trim();r=Pe(o)?o:Xt(e,o)}else return null;return we(r)?{gitDir:r,indexPath:y(r,"index")}:null}catch{return null}}function Gr(e){let t;try{t=v(y(e,"HEAD"),"Git HEAD").trim()}catch{return}if(ke.test(t))return t.toLowerCase();let n=/^ref:\s*(.+)$/.exec(t)?.[1]?.trim();if(!n)return;let r=Jr(e);return Bt(e,n)??Bt(r,n)??Br(r,n)}function Jr(e){try{let t=v(y(e,"commondir"),"Git common-directory marker").trim();return t?Pe(t)?t:Xt(e,t):e}catch{return e}}function Bt(e,t){try{let n=v(y(e,t),"Git reference").trim();return ke.test(n)?n.toLowerCase():void 0}catch{return}}function Br(e,t){try{for(let n of v(y(e,"packed-refs"),"Git packed references").split(`
4
- `)){if(n.startsWith("#")||n.startsWith("^"))continue;let r=n.indexOf(" ");if(r===-1)continue;let i=n.slice(0,r);if(n.slice(r+1).trim()===t&&ke.test(i))return i.toLowerCase()}}catch{return}}function Ur(e,t,n){let r=Qt(n);return Ft(e,t,{dbPath:n,metaPath:y(r,"meta.json"),cacheDir:r}).state}function Ut(e,t){let n={head:e,indexPath:t};try{let r=Yt(t);n.indexMtimeMs=r.mtimeMs,n.indexSize=r.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}function qr(e,t){let n=zt(e,t).replaceAll("\\","/");if(!(!n||n===".."||n.startsWith("../")))return n}function Hr(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function sn(e){return e&&e.length>0?[...e]:L}function qt(e,t){try{let n=S(e);n.config=te(t),n.languages=sn(n.config.languages)}catch{S(e).languages=L}}function Ht(e,t,n){let r=S(e);if(ae(n,r.languages)==="other")return null;let o=Dr(t);if(n===".scipquery.json"||et(n))return r.typeScriptInputPaths=null,o;if(!Kr(n,r.languages))return o;let s=r.typeScriptInputPaths;if(!s)return o;let a=s.has(n);if(o!=="add")return a?o:null;if(a)return"change";let c=an(e);return c?c.has(n)?"add":null:o}function xe(e){let t=S(e);if(!t.languages.includes("typescript")){t.typeScriptInputPaths=null;return}let n=Yr(t.projectRoot,t.config,t.languages);t.typeScriptInputPaths=n??an(e)}function an(e){let t=S(e);if(!t.languages.includes("typescript"))return t.typeScriptInputPaths=null,null;try{let n=t.config.indexer?.typescript,r=tt(t.projectRoot,n?.projectMode,n?.projects);return t.typeScriptInputPaths=r,r}catch{return t.typeScriptInputPaths=null,null}}function Kr(e,t){if(!t.includes("typescript"))return!1;let n=ae(e,["typescript","javascript"]);return n==="source"||n==="ambient"}function Yr(e,t,n){try{let r=U(v(H(e,t).metaPath,"reindex metadata"));if(r.kind!=="supported"&&r.kind!=="legacy")return null;let i=B(r.metadata.fingerprint);return!i||!Qr(i,n,t)?null:new Set(i.files.map(o=>o.path))}catch{return null}}function Qr(e,t,n){let r=K(t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath});return e.version===r.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function zr(e,t,n,r,i,o,s,a){let c=new Set;if(s){if(!n.head||!r.head)return null;let d=t.runResult(e,["diff","--name-only","-z","--no-renames","--relative",n.head,r.head,"--"]);if(d.kind!=="success")return null;for(let l of Xr(d.output))c.add(l)}if(a){if(i===null||o===null)return null;for(let d of ei(i,o))c.add(d)}return[...c].sort()}function Kt(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?Zr(n.output):null}function Xr(e){return e.split("\0").filter(t=>t.length>0)}function Zr(e){let t=e.split("\0");if(t.at(-1)===""&&t.pop(),t.length%2!==0)return null;let n=new Map;for(let r=0;r<t.length;r+=2){let i=t[r],o=t[r+1];if(!i.startsWith(":")||!o)return null;n.set(o,i)}return n}function ei(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(r=>e.get(r)!==t.get(r))}function Ie(e,t){return t===null?`${e}; changed paths unavailable`:t.length===0?e:t.length===1?t[0]:`${t.length} compiler inputs changed`}import{existsSync as Te,mkdirSync as ti,symlinkSync as ni,readlinkSync as cn,unlinkSync as dn,readdirSync as ri}from"fs";import{join as A,dirname as _e,resolve as N,relative as ii,isAbsolute as oi}from"path";import{homedir as si,platform as ai}from"os";import{fileURLToPath as ci}from"url";var di=ai()==="win32";var un=["scip-query","scip-plan","scip-setup","scip-integrity-audit","scip-explore","concrete-plan"];function ui(e={}){let t=e.quiet?()=>{}:console.log,n=ci(import.meta.url),r=N(_e(n),"..","skills"),i=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??si(),o=[A(i,".claude","skills"),A(i,".codex","skills"),A(i,".agents","skills")],s={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let a of o){let c=_e(a);if(!Te(c))continue;ti(a,{recursive:!0});let d=hi(a);li(a,r,d,s,t);for(let l of un){let u=A(r,l),h=A(a,l);if(!Te(u)){s.skipped.push(`${d}/${l}`);continue}if(Te(h)){try{let m=cn(h);if(N(m)===N(u)){s.alreadyLinked.push(`${d}/${l}`),t(` ok: ${l} \u2192 ${d} (already linked)`);continue}}catch{s.skipped.push(`${d}/${l}`),t(` skip: ${l} \u2192 ${d} (exists, not a symlink)`);continue}dn(h)}ni(u,h,di?"junction":"dir"),s.installed.push(`${d}/${l}`),t(` done: ${l} \u2192 ${d}`)}}return s}function li(e,t,n,r,i){let o=new Set(un);for(let s of ri(e)){if(o.has(s))continue;let a=A(e,s),c;try{c=N(_e(a),cn(a))}catch{continue}pi(c,t)&&(dn(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function pi(e,t){let n=ii(N(t),N(e));return n===""||!n.startsWith("..")&&!oi(n)}function hi(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}var ln=["repository-observation","repository-preview","mutation","composite","environment-observation","tool-information"];function fi(e,t=[]){return{defaultRole:e,...t.length>0?{rules:t}:{}}}function mi(e,t){for(let n of e.rules??[]){if(n.when.kind==="option-present"){let i=t.options[n.when.name];if(i!==void 0&&i!==!1)return n.role;continue}if((n.when.kind==="argument"?t.args[n.when.index]:t.options[n.when.name])===n.when.equals)return n.role}return e.defaultRole}function gi(e){return[...new Set([e.defaultRole,...(e.rules??[]).map(t=>t.role)])]}function ie(e){return ln.includes(e)}function yi(e){return e==="repository-observation"||e==="repository-preview"||e==="composite"}var Ae=1,Ne=1,oe=["compiler-graph","semantic-analysis","repository-source","change-history","runtime-measurement","heuristic","mixed","unknown"],pn=["complete","partial","unknown"],hn=["validated","failed","not-evaluated","not-applicable"],fn=["observe","advise","require-adjudication","block","not-established"],mn={policyId:"scip-query:unresolved-repository-policy",policyVersion:Ne,permission:"not-established",reasons:["No repository action policy was supplied for this claim."]};function Ci(e){return{schemaVersion:Ae,origin:e.contract.origin,coverage:gn(e.coverage),producerValidation:e.contract.producerValidation,stateAuthority:X(e.receipt,e.receipt),repositoryPolicy:e.repositoryPolicy??mn,...e.contract.families?{families:e.contract.families}:{}}}function gn(e){return e?e.complete===!0?{state:"complete",returned:e.returned,totalKnown:!0,total:e.total??e.returned,omitted:0}:e.totalKnown?{state:"partial",returned:e.returned,totalKnown:!0,...e.total===void 0?{}:{total:e.total},...e.omitted===void 0?{}:{omitted:e.omitted}}:{state:"unknown",returned:e.returned,totalKnown:!1}:{state:"unknown",returned:0,totalKnown:!1}}function bi(e,t){let n=[];return J(n,"origin",t.origins,e.origin),J(n,"coverage",t.coverage,e.coverage.state),J(n,"producer-validation",t.producerValidation,e.producerValidation.status),J(n,"state-authority",t.stateAuthority,e.stateAuthority.authority),J(n,"action-permission",t.actionPermission,e.repositoryPolicy.permission),{satisfied:n.every(r=>r.satisfied),predicates:n}}function J(e,t,n,r){n&&e.push({predicate:t,satisfied:n.includes(r),required:n,actual:r})}function je(e){return!p(e)||e.schemaVersion!==Ae||!j(e.origin,oe)||!vi(e.coverage)||!Ri(e.producerValidation)||!Si(e.stateAuthority)||!xi(e.repositoryPolicy)?!1:e.families===void 0||Ii(e.families)}function vi(e){return!p(e)||!j(e.state,pn)||!k(e.returned)||typeof e.totalKnown!="boolean"||e.total!==void 0&&!k(e.total)||e.omitted!==void 0&&!k(e.omitted)?!1:e.state==="complete"?e.totalKnown===!0&&e.total===e.returned&&e.omitted===0:e.state==="partial"?e.totalKnown===!0&&k(e.total)&&k(e.omitted)&&e.total===Number(e.returned)+Number(e.omitted):e.totalKnown===!1}function Ri(e){if(!p(e)||!j(e.status,hn))return!1;let t=e.certification;return e.status==="validated"||e.status==="failed"?p(t)&&C(t.id)&&Number.isSafeInteger(t.version)&&Number(t.version)>0&&C(t.corpus):t===void 0}function Si(e){return p(e)&&Number.isSafeInteger(e.policyVersion)&&(e.authority==="completion"||e.authority==="advisory"||e.authority==="none")&&Array.isArray(e.requiredRelationships)&&e.requiredRelationships.every(C)&&Array.isArray(e.reasons)&&e.reasons.every(C)}function xi(e){return p(e)&&C(e.policyId)&&e.policyVersion===Ne&&j(e.permission,fn)&&Array.isArray(e.reasons)&&e.reasons.every(C)}function Ii(e){return Array.isArray(e)&&e.every(t=>p(t)&&C(t.id)&&C(t.selector)&&Oi(t.origin))}function Oi(e){return p(e)?e.kind==="fixed"?j(e.origin,oe)&&e.origin!=="mixed":e.kind!=="result-field"||!C(e.field)||!p(e.values)?!1:Object.values(e.values).every(t=>j(t,oe)&&t!=="mixed"):!1}function j(e,t){return typeof e=="string"&&t.includes(e)}var bn="scip-query-result",vn=0,M=1,Ei=1,Rn=1,Sn=1;function xn(e){if(!p(e))return{kind:"malformed",reason:"CLI JSON output must be an object."};let t=Object.hasOwn(e,"kind"),n=Object.hasOwn(e,"schemaVersion");if(!t&&!n){let s=yn(e);return s?{kind:"malformed",reason:`Legacy CLI JSON envelope: ${s}`}:{kind:"legacy",schemaVersion:vn,envelope:e}}if(!t||!n)return{kind:"malformed",reason:"CLI JSON envelope must contain both kind and schemaVersion."};if(e.kind!==bn)return{kind:"malformed",reason:`Unsupported CLI JSON envelope kind: ${Ti(e.kind)}.`};let r=e.schemaVersion;if(!Number.isSafeInteger(r)||Number(r)<1)return{kind:"malformed",reason:"CLI JSON envelope schemaVersion must be a positive safe integer."};if(r!==M)return{kind:"unsupported",schemaVersion:Number(r),direction:Number(r)<M?"older":"future",...Cn(e.producer)?{producer:e.producer}:{}};let i=yn(e);if(i)return{kind:"malformed",reason:`CLI JSON envelope v1: ${i}`};if(!Cn(e.producer))return{kind:"malformed",reason:"CLI JSON envelope v1: producer must identify scip-query and its non-empty version."};if(!D(e.resultSchemaVersion))return{kind:"malformed",reason:"CLI JSON envelope v1: resultSchemaVersion must be a positive safe integer."};if(e.resultProjection!==void 0&&e.resultProjection!=="agent")return{kind:"malformed",reason:'CLI JSON envelope v1: resultProjection must be "agent" when present.'};let o=In(e.command);return o.includes(e.resultSchemaVersion)?e.evidenceContext!==void 0&&!ki(e.evidenceContext)?{kind:"malformed",reason:"CLI JSON envelope v1: evidenceContext must contain a supported receipt and analysis manifest."}:e.operationRole!==void 0&&!ie(e.operationRole)?{kind:"malformed",reason:"CLI JSON envelope v1: operationRole must be a supported command operation role."}:p(e.evidenceContext)&&e.operationRole!==void 0&&e.evidenceContext.operationRole!==void 0&&e.operationRole!==e.evidenceContext.operationRole?{kind:"malformed",reason:"CLI JSON envelope v1: top-level and evidence-context operation roles must agree."}:{kind:"supported",schemaVersion:M,envelope:e}:{kind:"unsupported-result",schemaVersion:M,command:e.command,resultSchemaVersion:e.resultSchemaVersion,supportedResultSchemaVersions:o}}function wi(e){let t=xn(e);if(t.kind==="legacy"||t.kind==="supported")return t;if(t.kind==="unsupported"){let n=t.producer?` from ${t.producer.name}@${t.producer.version}`:"";throw new Error(`Unsupported scip-query CLI JSON schemaVersion ${t.schemaVersion}${n}; this consumer supports the legacy unversioned envelope and schemaVersion ${M}.`)}throw t.kind==="unsupported-result"?new Error(`Unsupported resultSchemaVersion ${t.resultSchemaVersion} for scip-query command ${JSON.stringify(t.command)}; this consumer supports ${t.supportedResultSchemaVersions.join(", ")}.`):new Error(`Malformed scip-query CLI JSON envelope: ${t.reason}`)}function In(e){return Pi[e]??[Ei]}var Pi={};function yn(e){return typeof e.command!="string"||e.command.length===0?"command must be a non-empty string.":Array.isArray(e.args)?p(e.options)?Object.hasOwn(e,"result")?null:"result is required.":"options must be an object.":"args must be an array."}function Cn(e){return p(e)&&e.name==="scip-query"&&typeof e.version=="string"&&e.version.length>0}function ki(e){if(!p(e)||e.schemaVersion!==Rn||e.operationRole!==void 0&&!ie(e.operationRole)||!z(e.receipt))return!1;let t=e.analysisManifest;return p(t)&&t.schemaVersion===Sn&&(t.evidence===void 0||t.evidence==="graph-fact"||t.evidence==="heuristic"||t.evidence==="mixed")&&(t.claimQualification===void 0||je(t.claimQualification))}function Ti(e){return typeof e=="string"?JSON.stringify(e):String(e)}export{fn as CLAIM_ACTION_PERMISSIONS,Ne as CLAIM_ACTION_POLICY_VERSION,pn as CLAIM_COVERAGE_STATES,oe as CLAIM_ORIGINS,Ae as CLAIM_QUALIFICATION_SCHEMA_VERSION,Sn as CLI_ANALYSIS_MANIFEST_SCHEMA_VERSION,Rn as CLI_EVIDENCE_CONTEXT_SCHEMA_VERSION,bn as CLI_JSON_ENVELOPE_KIND,ln as COMMAND_OPERATION_ROLES,M as CURRENT_CLI_JSON_ENVELOPE_SCHEMA_VERSION,mn as DEFAULT_REPOSITORY_POLICY_ACTION,vn as LEGACY_CLI_JSON_ENVELOPE_SCHEMA_VERSION,f as LEGACY_OBSERVATION_RECEIPT_SCHEMA_VERSION,W as OBSERVATION_IDENTITY_CANONICALIZATION_VERSION,F as OBSERVATION_IDENTITY_HASH_ALGORITHM,Q as OBSERVATION_IDENTITY_SCHEMA_VERSION,I as OBSERVATION_RECEIPT_SCHEMA_VERSION,me as OBSERVATION_STATE_AUTHORITY_POLICY_VERSION,hn as PRODUCER_VALIDATION_STATUSES,Oe as Watcher,fi as commandOperation,gi as commandOperationRoles,ye as compareObservationReceipts,Ct as createObservationIdentity,on as createReindexRunner,xn as decodeCliJsonEnvelope,ge as decodeObservationReceipt,gn as deriveClaimCoverage,Ci as deriveClaimQualification,X as deriveObservationStateAuthority,bi as evaluateClaimQualification,En as getScipVersion,cr as initProjectConfig,ui as installSkills,je as isClaimQualificationV1,ie as isCommandOperationRole,z as isObservationReceipt,On as isScipInstalled,te as loadProjectConfig,bt as observationReceiptGenerationIdentity,Rt as observationReceiptStabilityLabel,vt as observationReceiptWorkspaceIdentity,yi as operationObservesRepository,wn as printScipInstallInstructions,wi as requireCompatibleCliJsonEnvelope,mi as resolveCommandOperationRole,H as resolveIndexStoragePaths,nn as resolveReindexWorkerLaunch,In as supportedCliResultSchemaVersions};
1
+ import{E as We,K as Fe,N as Ve,O as Ge,S as $e,U as Y,p as De,q as Le,w as an,x as cn,y as dn}from"./chunk-K4CN7GXK.js";import{a as Me}from"./chunk-J2TMAIN5.js";import{d as ve,v as K}from"./chunk-PKN354TH.js";import{a as qe,b as Ke,c as He,d as Ye,e as Qe,f as Xe,g as ze,h as Ze,i as M,j as et,k as D,l as tt,m as nt,n as rt}from"./chunk-FC2EVQRM.js";import{b as Je,c as Ue,d as Q,e as Be,f as X}from"./chunk-2IWUT6CJ.js";import{c as Se,e as _,g as be,h as Ie}from"./chunk-DA7RPPDF.js";import"./chunk-DHEQMPLW.js";import"./chunk-GVWX5T43.js";import{a as h,c as f,d as R,e as fe,i as q,j as P,m as k}from"./chunk-T6DK3ZP7.js";import{E as xe,J as Pe,M as Ee,N as we,O as H,P as Oe,T as Te,W as ke,X as _e,ba as N,f as he,g as B,ga as A,i as T,ja as Ne,k as ge,o as me,p as Ce,ta as Ae,u as ye,v as m,va as je,w as Re,ya as j}from"./chunk-5TNQJUR2.js";import{existsSync as Pn}from"fs";import{randomUUID as En}from"crypto";import{isAbsolute as Di,join as lt,relative as Li,resolve as Wi}from"path";import{createHash as it}from"crypto";import{closeSync as un,fstatSync as ot,lstatSync as ln,openSync as pn,readlinkSync as hn,realpathSync as gn,rmSync as fn}from"fs";import{dirname as ct,resolve as mn}from"path";var Cn=2e3,yn=10,Rn=3,W=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${at(r)}, but found ${at(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest};function dt(e,t,n={}){let r=Sn(e),i=vn(r,n.lockTimeoutMs??Cn,n.monotonicNow??_);try{let o=Math.max(0,Math.floor(n.maxRetries??Rn));for(let s=0;;s+=1){let a=L(r),c=t(a,s);if(c.kind==="unchanged")return{changed:!1,attempts:s+1,previous:a,current:a};n.onBeforeCommit?.({attempt:s,snapshot:a,mutation:c});let u=L(r);if(!bn(a.revision,u.revision)){if(s<o)continue;throw new W(r,a.revision,u.revision)}if(In(r,c,a.revision,s,o))return{changed:!0,attempts:s+1,previous:a,current:L(r)}}}finally{i.release()}}function Sn(e){let t;try{if(!ln(e).isSymbolicLink())return e;t=hn(e)}catch{return e}try{return gn(e)}catch{return mn(ct(e),t)}}function L(e){for(let t=0;t<4;t+=1){let n;try{n=pn(e,"r");let r=st(ot(n)),i=Re(n,{maxBytes:Ce,inputKind:"revisioned text file"}),o=st(ot(n));if(!ut(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:it("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:it("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&un(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function vn(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=ve(r,{kind:"revisioned-file-mutation",detail:{target:e}});if(o.kind==="acquired")return o.lock;if(n()>=i)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,yn)}}function xn(e,t,n){if(t.kind==="delete"){if(!n.exists)return;fn(e),xe(ct(e));return}let r=t.mode??n.identity?.mode;n.exists?be(e,t.text,{durability:"durable",mode:r}):Ie(e,t.text,{durability:"durable",mode:r})}function bn(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&ut(e.identity,t.identity))}function st(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function ut(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function at(e){return e.exists?e.hash.slice(0,12):"<absent>"}function In(e,t,n,r,i){try{xn(e,t,n)}catch(o){if(o.code==="EEXIST"){let s=L(e);if(r<i)return!1;throw new W(e,n,s.revision)}throw o}return!0}var E=".scipquery.json",pt=2e3,ht=5e3,z=ht,gt=15*6e4,Z={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},wn={enabled:!1,autoStart:!1,allowExpensiveRebuild:!1,debounceMs:pt,cooldownMs:z,gitPollMs:2e3,idleTimeoutMs:gt,autoRefresh:!0,ignore:[],resourceBudget:Z};var Ji=new Set(P);function F(e){let t=lt(e,E);if(!Pn(t))return{};let n;try{n=ye(t,{maxBytes:me,inputKind:"scip-query project config"})}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${E} at ${t}: ${i}`,{cause:r})}return mt(Q(n),t,"read").config}function ft(e){return{...wn,...e.watch,cooldownMs:Math.max(ht,e.watch?.cooldownMs??z),resourceBudget:{...Z,...e.watch?.resourceBudget}}}function On(e,t){return Tn(e,t).configPath}function Tn(e,t){let n=lt(e,E),r=En(),i={collaborationDomainId:r,languages:t,watch:{enabled:!0,debounceMs:pt,cooldownMs:z,gitPollMs:2e3,idleTimeoutMs:gt,autoRefresh:!0,resourceBudget:{...Z}}},o=dt(n,s=>{if(!s.revision.exists)return{kind:"write",text:X(i)};let a=kn(s,i);return a.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:X({...a.config,collaborationDomainId:r})}});return{configPath:n,changed:o.changed}}function kn(e,t){if(!e.revision.exists)return{config:Be(t),needsMigration:!0};let n=mt(Q(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function mt(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${E} at ${t}: ${e.reason}`:`Cannot update ${t}: the latest project config is ${e.reason}.`;throw new Error(`${i} The file was left untouched.`)}let r=n==="read"?`invalid ${E} at ${t}`:`Cannot update ${t}: the latest project config is invalid`;throw new Error(`${r} (unsupported ${e.direction} schemaVersion ${e.schemaVersion}; this scip-query reads legacy v${Je} and current v${Ue}). Upgrade scip-query before retrying; the file was left untouched.`)}import{fileURLToPath as Bn}from"url";import{existsSync as oe,lstatSync as qn,statSync as Et,watch as Kn}from"fs";import{EventEmitter as Hn}from"events";import{basename as Yn,dirname as wt,isAbsolute as se,join as g,relative as Ot,resolve as Tt}from"path";import{watch as Qn}from"chokidar";import Xn from"ignore";function ee(e){let t=JSON.stringify(e);return Buffer.byteLength(t)<=65536?t:void 0}import{existsSync as Ct,lstatSync as _n}from"fs";import{dirname as Nn,resolve as An}from"path";function yt(e,t,n,r={}){let i=new Date().toISOString();if(!Ct(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Ct(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let o=k(m(n.metaPath,"reindex metadata"));return o.kind==="unsupported"?{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Reindex metadata version ${o.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"}:o.kind==="malformed"?{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not decode reindex metadata: ${o.reason}`,remedy:"Run: scip-query reindex"}:jn(e,t,n,r,o,i)}catch(o){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${o instanceof Error?o.message:String(o)}`,remedy:"Run: scip-query reindex"}}}function jn(e,t,n,r,i,o){let s=i.metadata,a=t.languages??We(e),c=Mn(e,t,n,r,a,s.fingerprint),u=[...s.indexedLanguages??[]].sort(),l=i.capabilities.publishableGeneration&&ge(T(s.fingerprint),c)&&JSON.stringify(u)===JSON.stringify(c.languages),{accepted:d,reason:p}=Wn(n,c,u,l);return{state:d?"fresh":"stale",checkedAt:o,metaPath:n.metaPath,updatedAt:s.updatedAt,lastRefresh:s.lastRefresh,reason:p,remedy:d?void 0:"Run: scip-query reindex"}}function Mn(e,t,n,r,i,o){return Dn(e,t,n,r,i,o)??Vn(e,i,t,n.cacheDir??Nn(n.dbPath))}function Dn(e,t,n,r,i,o){if(!n.cacheDir||!r.gitContext||!Y(r.gitContext,n.cacheDir,o))return;let s=Ln(e,t,i,r.gitContext,r.gitObservation,o);if(!(!s||!Y(s,n.cacheDir,o)))return o}function Ln(e,t,n,r,i,o){if(!Gn(o,n,t)||!$n(e,o,t))return;let s=i?.context===r?r:Ee(r),a=i&&i.context===r?i.projectFileInventorySequence:void 0;return s?.clean&&we(e,void 0,{cachedInventoryAfterSequence:a})?s:void 0}function Wn(e,t,n,r){let i=$e(e.dbPath,e.metaPath),o=i.state==="invalid"||i.state==="drifted",s=r?Ge(e.dbPath,t,n):void 0,a=s?.state==="incomplete";return{accepted:r&&!o&&!a,reason:Fn(i,s,r)}}function Fn(e,t,n){return e.state==="invalid"||e.state==="drifted"?`SQLite generation requires repair: ${e.reason}`:t?.state==="incomplete"?`SQLite generation is missing ${t.missingDocumentCount} indexed source document(s): ${t.missingPaths.join(", ")}`:n?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files."}function Vn(e,t,n,r=N(e,n)){return Ne(e,r,()=>je(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath}))}function Gn(e,t,n){let r=Jn(t,n);return e.version===r.version&&e.typescriptSymbolIdentityVersion===r.typescriptSymbolIdentityVersion&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function $n(e,t,n){if(!(t.languages.includes("typescript")||!!t.clojureConfigPath))return!0;let i=Ae(e);if(t.clojureConfigPath){let o=he(t.clojureConfigPath);if(!i.includes(o))return!1;try{if(!_n(An(e,o)).isFile())return!1}catch{return!1}}return!t.languages.includes("typescript")||_e(e,n.indexer?.typescript?.projectMode,n.indexer?.typescript?.projects??[],i)}function Jn(e,t){return j(e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}var kt=5e3,re=class{projectRoot;config;watchConfig;outputDb;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;budgetInspector;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;budgetTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;pendingChanges=new Map;pendingChangesComplete=!0;pendingChangesIncompleteReason;reindexInFlight=!1;lastReindexEnd=0;publicationObservationInvalidated=!1;lastObservedGeneration=null;publishedGeneration;indexFreshness;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;reconcileTimer=null;lastGitState=null;preferFilesystemGitState=!0;watchGitLayout=null;localCacheWatchPath;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=ft(t.config),this.outputDb=t.outputDb??g(N(this.projectRoot,t.config),"index.db"),this.preferFilesystemGitState=t.gitReader===void 0,this.localCacheWatchPath=Ir(this.projectRoot,wt(this.outputDb)),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;let n=nr(t);this.onStatus=n.onStatus,this.onReindexComplete=n.onReindexComplete,this.onReindexError=n.onReindexError,this.onRefreshSuppressed=n.onRefreshSuppressed,this.onError=n.onError,this.clock=n.clock,_t.set(this,Pr(t.stopTimeoutMs??kt,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??Mt(),this.subscriptionFactory=t.subscriptionFactory??sr,this.budgetInspector=t.budgetInspector??Ve,this.publishedGeneration=t.publishedGeneration??K,this.indexFreshness=t.indexFreshness??br,this.lastObservedGeneration=this.readPublishedGeneration(),tr(this,t),this.gitignoreFilter=Me(t.projectRoot),this.extraIgnore=Xn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore),ne(this)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,G(this).errors=[],this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let t=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.clearGitPollTimer(),this.clearReconcileTimer();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let r=[...G(this).closures],i=Zn(this),o=this.clock.now()+i;return this.stopPromise=this.finishStop(t,r,n,o,i).catch(s=>{throw this.stopInProgress=!1,s}),this.stopPromise}requestRefresh(t,n={}){if(!this.stopped){if(this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`),!n.immediate||this.reindexInFlight||this.status.state==="cooldown"||this.status.state==="budget-paused"){this.scheduleReindex(t);return}this.pendingTrigger=te(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(r,i)=>this.isIgnoredWatchPath(r,i?.isDirectory()??!1),usePolling:t,ignorePermissionErrors:!0,...t?{interval:5e3,binaryInterval:1e4}:{}});n.on("all",(r,i)=>{!this.stopped&&r!=="addDir"&&r!=="unlinkDir"&&this.handleFileChange(r,i)}),n.on("error",r=>this.handleSourceWatcherError(n,r,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,r){if(this.markPendingChangesIncomplete("source-watcher-error"),r||this.sourcePollingFallbackStarted||!yr(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==t),er(G(this),t,i=>this.onError(i));try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(t,n){let r=this.relativeWatchPath(t);if(!r)return!1;if(xt(r,this.localCacheWatchPath))return!0;let i=n?`${r}/`:r;return this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(t,n){let r=this.relativeWatchPath(n);if(Mr(r)||xt(r,this.localCacheWatchPath)||this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)||Dr(r))return;r===".scipquery.json"&&Lt(this,this.projectRoot);let i=Wt(this,t,r);i!==null&&(i||this.markPendingChangesIncomplete(`unsupported-source-event:${t}`),this.scheduleReindex({kind:"watch-source",detail:r},i?[{path:r,kind:i}]:void 0,i!==void 0))}relativeWatchPath(t){let n=se(t)?t:g(this.projectRoot,t);return Ot(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t,n,r=!1){this.publicationObservationInvalidated=!0,this.pendingTrigger=te(this.pendingTrigger,t),r||this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`);for(let o of n??[])this.recordPendingChange(o);if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});let o=this.activeOperation;o&&S.get(this)!==o&&(S.set(this,o),o.cancel().then(s=>{s.state==="degraded"&&!this.stopped&&this.onError(new Error(s.reason))},s=>{this.stopped||this.onError(s instanceof Error?s:new Error(String(s)))}));return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}if(this.status.state==="budget-paused"){this.dirty=!0,this.setStatus({...this.status,dirty:!0});return}this.clearDebounceTimer();let i=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:i}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped||this.reconcilePublishedIndex())return;let t=this.inspectBudget(),n=this.watchConfig.allowExpensiveRebuild&&t.state!=="paused";if(t.state==="paused"&&t.reason!=="rebuild-count"){this.dirty=!0;let c=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:c,dirty:!0,reason:t.detail,rebuilt:t.rebuilt,estimatedWriteBytes:t.estimatedWriteBytes}),this.clearBudgetTimer(),this.budgetTimer=this.clock.setTimeout(()=>{this.budgetTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},Math.min(2147483647,Math.max(1,c-this.wallNow())));return}let r=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&r<this.watchConfig.cooldownMs){let c=this.watchConfig.cooldownMs-r;this.dirty=!0;let u=this.wallNow()+c;this.setStatus({state:"cooldown",until:u,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},c);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let i=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let o=this.consumePendingChangeJournal(),s=this.wallNow();this.setStatus({state:"indexing",startedAt:s});let a=this.reindexRunner.start(this.reindexRequest(i,n,o));this.activeOperation=a,a.completion.then(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),V.set(this,0),this.stopped)return;if(S.get(this)===a){if(this.restorePendingChangeJournal(o),this.dirty){let l=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:l,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"});return}ne(this),this.lastObservedGeneration=this.readPublishedGeneration();let u=!1;try{u=this.onReindexComplete(c,i,{pendingChanges:this.dirty})===!0}catch(l){this.onError(l instanceof Error?l:new Error(String(l)))}if(this.dirty&&!this.stopped){if(u){let d=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),this.onRefreshSuppressed(d),this.setStatus({state:"idle"});return}let l=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:l,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let u=c instanceof Error?c:new Error(String(c));this.restorePendingChangeJournal(o);let l=jt(u),d=0;if(l?(d=(V.get(this)??0)+1,V.set(this,d),this.dirty=!0,this.pendingTrigger=te(this.pendingTrigger,i)):V.set(this,0),!l&&S.get(this)!==a&&(this.onReindexError(u,i),this.onError(u)),this.dirty){let p=l?gr(this.watchConfig.cooldownMs,d):this.watchConfig.cooldownMs,y=this.wallNow()+p;this.setStatus({state:"cooldown",until:y,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},p);return}this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===a&&(this.activeOperation=null),S.get(this)===a&&S.delete(this)})}async finishStop(t,n,r,i,o){let s=[],a=t.map(async p=>{try{await p.close()}catch(y){s.push(`watch subscription close failed: ${String(y)}`)}});a.push(...n),r&&a.push((async()=>{try{let p=await r.cancel();p.state==="degraded"&&s.push(p.reason)}catch(p){s.push(`reindex cancellation failed: ${p instanceof Error?p.message:String(p)}`)}})());let c=a.length,u=a.map(p=>p.finally(()=>{c-=1})),l=await zn(u,i,this.clock),d=G(this);return s.push(...d.errors),d.errors=[],l?this.stopInProgress=!1:(s.push(`watch shutdown exceeded the ${o}ms deadline with ${c} operation(s) still pending`),Promise.all(u).then(()=>{this.stopInProgress=!1})),s.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:s.join("; ")}),{state:"degraded",reasons:s}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}inspectBudget(){try{return this.budgetInspector(this.outputDb,this.watchConfig.resourceBudget,new Date(this.wallNow()))}catch(t){return{state:"paused",reason:"activity-evidence",until:this.wallNow()+this.watchConfig.resourceBudget.windowMs,rebuilt:0,estimatedWriteBytes:0,detail:`reindex activity evidence could not be read: ${t instanceof Error?t.message:String(t)}`}}}reindexRequest(t,n=!0,r){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:t,changeJournal:r,allowExpensiveRebuild:n}}setStatus(t){this.status=t,t.state==="cooldown"||t.state==="budget-paused"?this.armReconcileTimer(t.until):this.clearReconcileTimer(),this.onStatus(t)}recordPendingChange(t){if(this.pendingChanges.size>=1024&&!this.pendingChanges.has(t.path)){this.pendingChanges.clear(),this.markPendingChangesIncomplete("change-entry-limit");return}let n=this.pendingChanges.get(t.path),r=mr(n,t.kind);r===null?this.pendingChanges.delete(t.path):this.pendingChanges.set(t.path,r)}markPendingChangesIncomplete(t){this.pendingChangesComplete=!1,this.pendingChangesIncompleteReason??=t}consumePendingChangeJournal(){let t=K(this.outputDb),n=[...this.pendingChanges.entries()].map(([s,a])=>({path:s,kind:a})).sort((s,a)=>s.path.localeCompare(a.path)),r=this.pendingChangesComplete,i=this.pendingChangesIncompleteReason;t||(r=!1,i??="accepted-generation-unavailable");let o={version:1,baseGeneration:t,complete:r,...i?{incompleteReason:i}:{},entries:n};return ee(o)||(o={version:1,baseGeneration:t,complete:!1,incompleteReason:"change-journal-byte-limit",entries:[]}),this.resetPendingChanges(),o}restorePendingChangeJournal(t){let n=[...this.pendingChanges.entries()].map(([o,s])=>({path:o,kind:s})),r=this.pendingChangesComplete,i=this.pendingChangesIncompleteReason;this.resetPendingChanges(),t.complete||this.markPendingChangesIncomplete(t.incompleteReason??"failed-reindex");for(let o of t.entries)this.recordPendingChange(o);r||this.markPendingChangesIncomplete(i??"failed-reindex");for(let o of n)this.recordPendingChange(o)}resetPendingChanges(){this.pendingChanges.clear(),this.pendingChangesComplete=!0,this.pendingChangesIncompleteReason=void 0}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}clearBudgetTimer(){this.budgetTimer&&(this.clock.clearTimeout(this.budgetTimer),this.budgetTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(C(this).stagedIndexEntries=Pt(this.projectRoot,C(this).gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}armReconcileTimer(t){this.clearReconcileTimer();let n=t-this.wallNow();if(n<=0||!(this.watchConfig.gitPollMs>0))return;let r=Math.min(this.watchConfig.gitPollMs,n);this.reconcileTimer=this.clock.setTimeout(()=>{this.reconcileTimer=null,!(this.stopped||this.reconcilePublishedIndex())&&(this.status.state==="cooldown"||this.status.state==="budget-paused")&&this.armReconcileTimer(this.status.until)},r),this.reconcileTimer.unref?.()}clearReconcileTimer(){this.reconcileTimer&&(this.clock.clearTimeout(this.reconcileTimer),this.reconcileTimer=null)}readPublishedGeneration(){try{return this.publishedGeneration(this.outputDb)}catch{return null}}reconcilePublishedIndex(){if(this.stopped||this.reindexInFlight||!(this.dirty||this.status.state==="budget-paused"||this.status.state==="cooldown"||this.status.state==="waiting")||!this.hasFreshPublishedIndex())return!1;let n=this.pendingTrigger??{kind:"unknown"};return this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),ne(this),this.onRefreshSuppressed({...n,detail:`the published index matches current source${n.detail?` (${n.detail})`:""}`}),this.setStatus({state:"idle"}),!0}hasFreshPublishedIndex(){let t=this.readPublishedGeneration();if(t===null||t===this.lastObservedGeneration&&!this.publicationObservationInvalidated)return!1;let n;try{n=this.indexFreshness(this.projectRoot,this.config,this.outputDb)}catch{return!1}return(n==="fresh"||n==="stale")&&(this.lastObservedGeneration=t,this.publicationObservationInvalidated=!1),n==="fresh"}pollGitState(){if(this.reindexInFlight||this.stopped)return;let t=this.lastGitState,n=this.readGitState();if(!n||this.stopped||(this.lastGitState=n,!t))return;let r=t.head!==n.head,i=Lr(t,n);if(!r&&!i)return;let o=C(this),s=o.stagedIndexEntries,a=Pt(this.projectRoot,o.gitReader);o.stagedIndexEntries=a;let c=Tr(this.projectRoot,o.gitReader,t,n,s,a,r,i),u=null;if(c!==null&&(u=Wr(this,this.projectRoot,c),u.length===0))return;let l=u?.map(p=>({path:p,kind:oe(g(this.projectRoot,p))?"change":"delete"})),d=Ar(r,i,n.indexPath);this.scheduleReindex({...d,detail:jr(d.detail,u)},l,l!==void 0)}readGitState(){if(this.preferFilesystemGitState){let t=this.readFilesystemGitState();if(t)return t}return this.readGitStateFromGit()}readFilesystemGitState(){let t=this.watchGitLayout??Rr(this.projectRoot);if(!t)return null;this.watchGitLayout=t;let n=Sr(t.gitDir);return n?It(n,t.indexPath):null}readGitStateFromGit(){let t=C(this).gitReader,n=H(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let r=Oe(this.projectRoot,n);return It(H(this.projectRoot,["rev-parse","--verify","HEAD"],t),r)}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function zn(e,t,n){if(e.length===0)return!0;let r=Promise.all(e).then(()=>!0),i=Math.max(0,t-n.now()),o=null,s=new Promise(c=>{o=n.setTimeout(()=>c(!1),i)}),a=await Promise.race([r,s]);return a&&o&&n.clearTimeout(o),a}var St=new WeakMap,_t=new WeakMap,Nt=new WeakMap,S=new WeakMap,V=new WeakMap;function G(e){let t=St.get(e);if(t)return t;let n={closures:new Set,errors:[]};return St.set(e,n),n}function Zn(e){return _t.get(e)??kt}function C(e){let t=Nt.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function er(e,t,n){let r=Promise.resolve().then(()=>t.close()).catch(i=>{let o=`watch subscription close failed during polling fallback: ${String(i)}`;e.errors.push(o),n(new Error(o))});e.closures.add(r),r.then(()=>e.closures.delete(r))}function tr(e,t){Nt.set(e,{projectRoot:t.projectRoot,config:t.config,gitReader:t.gitReader??Pe,languages:Dt(t.languages??t.config.languages),typeScriptInputPaths:null,stagedIndexEntries:null})}function nr(e){return{onStatus:e.onStatus??(()=>{}),onReindexComplete:e.onReindexComplete??(()=>{}),onReindexError:e.onReindexError??(()=>{}),onRefreshSuppressed:e.onRefreshSuppressed??(()=>{}),onError:e.onError??(t=>console.error(t.message)),clock:e.clock??or}}function At(e,t=Se){let{projectRoot:n,config:r,languages:i,pnpmWorkspaces:o,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:c,indexerConcurrency:u,trigger:l}=e,d=F(n),p=Object.keys(d).length>0?d:r,y=A(n,p),on=p.indexer?.typescript,sn=p.indexer?.clojure,pe=t(process.pid);if(!pe)throw new Error(`Could not establish watcher process identity for reindex worker ownership (pid ${process.pid}).`);return{workerPath:Bn(new URL("./reindex-worker.js",import.meta.url)),env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:n,SCIP_REINDEX_OUTPUT_SCIP:y.indexPath,SCIP_REINDEX_OUTPUT_DB:y.dbPath,...rr(p,on,sn,{languages:i,indexerConcurrency:u,pnpmWorkspaces:o,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:c}),SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_CHANGE_JOURNAL:e.changeJournal?ee(e.changeJournal)??"":"",SCIP_REINDEX_ALLOW_EXPENSIVE:e.allowExpensiveRebuild===!1?"0":"1",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(pe)}}}function rr(e,t,n,r){let{languages:i,indexerConcurrency:o,pnpmWorkspaces:s,typescriptProjectMode:a,typescriptProjects:c,clojureConfigPath:u}=r;return{SCIP_REINDEX_LANGUAGES:(e.languages??i)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(e.indexerConcurrency??o??""),SCIP_REINDEX_PNPM_WORKSPACES:t?.pnpmWorkspaces??s?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:ir(t,a,c),SCIP_REINDEX_CLOJURE_CONFIG_PATH:n?.configPath??u??""}}function ir(e,t,n){return JSON.stringify({projectMode:e?.projectMode??t,projects:e?.projects??n??[],maxHeapMb:e?.maxHeapMb})}var or={now:_,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},sr=(e,t)=>ar(process.platform,t.usePolling)?new ie(e):Qn(e,t);function ar(e,t){return e==="darwin"&&t!==!0}var w=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="RecursiveSourceWatchError"}},ie=class{events=new Hn;watcher;constructor(t){this.watcher=Kn(t,{recursive:!0},(n,r)=>{if(r===null){this.events.emit("error",new w("Recursive source watcher omitted the changed path."));return}let i=g(t,r.toString());this.events.emit("all",cr(n,i),i)}),this.watcher.on("error",n=>{this.events.emit("error",new w(`Recursive source watcher failed: ${n.message}`,n))})}on=(t,n)=>(this.events.on(t,n),this);close(){this.watcher.close()}};function cr(e,t){return e==="change"?"change":oe(t)?Et(t).isDirectory()?"addDir":"add":"unlink"}var dr=15*6e4,ur=1e3,lr=64*1024;function pr(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function vt(e,t){let n=e instanceof Error?e.message:String(e),r=t.stderrTail.trim()||t.stdoutTail.trim();return r?`${n}
2
+ ${r}`:n}function hr(e,t){return Object.assign(new Error(e,t===void 0?void 0:{cause:t}),{retryable:!0})}function jt(e){return e instanceof Error&&"retryable"in e&&e.retryable===!0}function gr(e,t){let n=e*2**Math.min(5,Math.max(0,t-1));return Math.max(e,Math.min(3e4,n))}function Mt(e={}){let t=e.timeoutMs??dr,n=e.terminationGraceMs??ur,r=e.maxOutputBytes??lr,i=e.resolveLaunch??At;return{start(o){let s=i(o),a=new AbortController,c=pr(),u=!1,l=Le({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:r,maxStderrBytes:r,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(d=>{if(c={stdoutTail:d.stdout,stderrTail:d.stderr,stdoutTruncated:d.stdoutTruncated,stderrTruncated:d.stderrTruncated},d.status!==0){let p=vt(new Error(`Reindex worker exited with ${d.signal?`signal ${d.signal}`:`code ${d.status}`}`),c);throw d.status===75?hr(p):new Error(p)}return d.durationMs}).catch(d=>{throw jt(d)?d:(d instanceof De&&(c={stdoutTail:d.stdout,stderrTail:d.stderr,stdoutTruncated:d.stdoutTruncated,stderrTruncated:d.stderrTruncated}),new Error(vt(d,c),{cause:d}))}).finally(()=>{u=!0});return{completion:l,async cancel(){u||a.abort();try{await l}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function te(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}function fr(e){if(e==="add")return"add";if(e==="change")return"change";if(e==="unlink")return"delete"}function mr(e,t){return e?e==="add"?t==="delete"?null:"add":e==="delete"&&t==="add"?"change":t:t}function Cr(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function yr(e){return e instanceof w||Cr(e)}var ae=/^[0-9a-f]{40,64}$/i;function xt(e,t){return e===".git"||e.startsWith(".git/")||e==="node_modules"||e.startsWith("node_modules/")||e.endsWith("/node_modules")||e.includes("/node_modules/")?!0:t!==void 0&&(e===t||e.startsWith(`${t}/`))}function Rr(e){let t=g(e,".git");try{let n=qn(t),r;if(n.isDirectory())r=t;else if(n.isFile()){let i=/^gitdir:\s*(.+)\s*$/m.exec(m(t,"Git directory marker"));if(!i?.[1])return null;let o=i[1].trim();r=se(o)?o:Tt(e,o)}else return null;return oe(r)?{gitDir:r,indexPath:g(r,"index")}:null}catch{return null}}function Sr(e){let t;try{t=m(g(e,"HEAD"),"Git HEAD").trim()}catch{return}if(ae.test(t))return t.toLowerCase();let n=/^ref:\s*(.+)$/.exec(t)?.[1]?.trim();if(!n)return;let r=vr(e);return bt(e,n)??bt(r,n)??xr(r,n)}function vr(e){try{let t=m(g(e,"commondir"),"Git common-directory marker").trim();return t?se(t)?t:Tt(e,t):e}catch{return e}}function bt(e,t){try{let n=m(g(e,t),"Git reference").trim();return ae.test(n)?n.toLowerCase():void 0}catch{return}}function xr(e,t){try{for(let n of m(g(e,"packed-refs"),"Git packed references").split(`
3
+ `)){if(n.startsWith("#")||n.startsWith("^"))continue;let r=n.indexOf(" ");if(r===-1)continue;let i=n.slice(0,r);if(n.slice(r+1).trim()===t&&ae.test(i))return i.toLowerCase()}}catch{return}}function br(e,t,n){let r=wt(n);return yt(e,t,{dbPath:n,metaPath:g(r,"meta.json"),cacheDir:r}).state}function It(e,t){let n={head:e,indexPath:t};try{let r=Et(t);n.indexMtimeMs=r.mtimeMs,n.indexSize=r.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}function Ir(e,t){let n=Ot(e,t).replaceAll("\\","/");if(!(!n||n===".."||n.startsWith("../")))return n}function Pr(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function Dt(e){return e&&e.length>0?[...e]:P}function Lt(e,t){try{let n=C(e);n.config=F(t),n.languages=Dt(n.config.languages)}catch{C(e).languages=P}}function Wt(e,t,n){let r=C(e);if(B(n,r.languages)==="other")return null;let o=fr(t);return n===".scipquery.json"||Te(n)?(r.typeScriptInputPaths=null,o):Er(n,r.languages)?Fr(e,r.typeScriptInputPaths,n,o):o}function ne(e){let t=C(e);if(!t.languages.includes("typescript")){t.typeScriptInputPaths=null;return}let n=wr(t.projectRoot,t.config,t.languages);t.typeScriptInputPaths=n??Ft(e)}function Ft(e){let t=C(e);if(!t.languages.includes("typescript"))return t.typeScriptInputPaths=null,null;try{let n=t.config.indexer?.typescript,r=ke(t.projectRoot,n?.projectMode,n?.projects);return t.typeScriptInputPaths=r,r}catch{return t.typeScriptInputPaths=null,null}}function Er(e,t){if(!t.includes("typescript"))return!1;let n=B(e,["typescript","javascript"]);return n==="source"||n==="ambient"}function wr(e,t,n){try{let r=k(m(A(e,t).metaPath,"reindex metadata"));if(r.kind!=="supported"&&r.kind!=="legacy")return null;let i=T(r.metadata.fingerprint);return!i||!Or(i,n,t)?null:new Set(i.files.map(o=>o.path))}catch{return null}}function Or(e,t,n){let r=j(t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath});return e.version===r.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function Tr(e,t,n,r,i,o,s,a){let c=new Set;if(s){if(!n.head||!r.head)return null;let u=t.runResult(e,["diff","--name-only","-z","--no-renames","--relative",n.head,r.head,"--"]);if(u.kind!=="success")return null;for(let l of kr(u.output))c.add(l)}if(a){if(i===null||o===null)return null;for(let u of Nr(i,o))c.add(u)}return[...c].sort()}function Pt(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?_r(n.output):null}function kr(e){return e.split("\0").filter(t=>t.length>0)}function _r(e){let t=e.split("\0");if(t.at(-1)===""&&t.pop(),t.length%2!==0)return null;let n=new Map;for(let r=0;r<t.length;r+=2){let i=t[r],o=t[r+1];if(!i.startsWith(":")||!o)return null;n.set(o,i)}return n}function Nr(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(r=>e.get(r)!==t.get(r))}function Ar(e,t,n){return e&&t?{kind:"watch-git-state",detail:"HEAD and index changed"}:e?{kind:"watch-git-head",detail:"HEAD changed"}:{kind:"watch-git-index",detail:n??"index changed"}}function jr(e,t){return t===null?`${e}; changed paths unavailable`:t.length===0?e:t.length===1?t[0]:`${t.length} compiler inputs changed`}function Mr(e){return!e||e===".."||e.startsWith("../")}function Dr(e){return e.endsWith("index.db")||e.endsWith("index.scip")||e.endsWith("index.db.tmp")||Yn(e).startsWith(Fe)}function Lr(e,t){return e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize}function Wr(e,t,n){return n.includes(".scipquery.json")&&Lt(e,t),n.filter(r=>Wt(e,"add",r)!==null)}function Fr(e,t,n,r){if(!t)return r;let i=t.has(n);if(r!=="add")return i?r:null;if(i)return"change";let o=Ft(e);return o?o.has(n)?"add":null:r}import{existsSync as ce,mkdirSync as Vr,symlinkSync as Gr,readlinkSync as Vt,unlinkSync as Gt,readdirSync as $r}from"fs";import{join as v,dirname as $,resolve as x,relative as Jr,isAbsolute as Ur}from"path";import{homedir as Br,platform as qr}from"os";import{fileURLToPath as Kr}from"url";var Hr=qr()==="win32",$t=["scip-query","scip-explore","scip-plan","scip-architecture-review","scip-integrity-audit","scip-setup"],Yr=$t;var Jt=$t;function Qr(e={}){let t=e.quiet?()=>{}:console.log,n=Kr(import.meta.url),r=x($(n),"..","skills"),i=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??Br(),o=[v(i,".claude","skills"),v(i,".codex","skills"),v(i,".agents","skills")],s={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let a of o){let c=$(a);if(!ce(c))continue;Vr(a,{recursive:!0});let u=Zr(a);zr(a,r,u,s,t);for(let l of e.all?Jt:Yr)Xr(a,r,u,l,s,t)}return s}function Xr(e,t,n,r,i,o){let s=v(t,r),a=v(e,r);if(!ce(s)){i.skipped.push(`${n}/${r}`);return}let c=null;try{c=x($(a),Vt(a))}catch{if(ce(a)){i.skipped.push(`${n}/${r}`),o(` skip: ${r} \u2192 ${n} (exists, not a symlink)`);return}}if(c===x(s)){i.alreadyLinked.push(`${n}/${r}`),o(` ok: ${r} \u2192 ${n} (already linked)`);return}if(c&&!Ut(c,t)){i.skipped.push(`${n}/${r}`),o(` skip: ${r} \u2192 ${n} (symlink outside this scip-query package)`);return}c&&Gt(a),Gr(s,a,Hr?"junction":"dir"),i.installed.push(`${n}/${r}`),o(` done: ${r} \u2192 ${n}`)}function zr(e,t,n,r,i){let o=new Set(Jt);for(let s of $r(e)){if(o.has(s))continue;let a=v(e,s),c;try{c=x($(a),Vt(a))}catch{continue}Ut(c,t)&&(Gt(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function Ut(e,t){let n=Jr(x(t),x(e));return n===""||!n.startsWith("..")&&!Ur(n)}function Zr(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}var Bt=["repository-observation","repository-preview","mutation","composite","environment-observation","tool-information"];function ei(e,t=[]){return{defaultRole:e,...t.length>0?{rules:t}:{}}}function ti(e,t){for(let n of e.rules??[]){if(n.when.kind==="option-present"){let i=t.options[n.when.name];if(i!==void 0&&i!==!1)return n.role;continue}if((n.when.kind==="argument"?t.args[n.when.index]:t.options[n.when.name])===n.when.equals)return n.role}return e.defaultRole}function ni(e){return[...new Set([e.defaultRole,...(e.rules??[]).map(t=>t.role)])]}function J(e){return Bt.includes(e)}function ri(e){return e==="repository-observation"||e==="repository-preview"||e==="composite"}var de=1,ue=1,U=["compiler-graph","semantic-analysis","repository-source","change-history","runtime-measurement","heuristic","mixed","unknown"],qt=["complete","partial","unknown"],Kt=["validated","failed","not-evaluated","not-applicable"],Ht=["observe","advise","require-adjudication","block","not-established"],Yt={policyId:"scip-query:unresolved-repository-policy",policyVersion:ue,permission:"not-established",reasons:["No repository action policy was supplied for this claim."]};function ii(e){return{schemaVersion:de,origin:e.contract.origin,coverage:Qt(e.coverage),producerValidation:e.contract.producerValidation,stateAuthority:D(e.receipt,e.receipt),repositoryPolicy:e.repositoryPolicy??Yt,...e.contract.families?{families:e.contract.families}:{}}}function Qt(e){return e?e.complete===!0?{state:"complete",returned:e.returned,totalKnown:!0,total:e.total??e.returned,omitted:0}:e.totalKnown?{state:"partial",returned:e.returned,totalKnown:!0,...e.total===void 0?{}:{total:e.total},...e.omitted===void 0?{}:{omitted:e.omitted}}:{state:"unknown",returned:e.returned,totalKnown:!1}:{state:"unknown",returned:0,totalKnown:!1}}function oi(e,t){let n=[];return O(n,"origin",t.origins,e.origin),O(n,"coverage",t.coverage,e.coverage.state),O(n,"producer-validation",t.producerValidation,e.producerValidation.status),O(n,"state-authority",t.stateAuthority,e.stateAuthority.authority),O(n,"action-permission",t.actionPermission,e.repositoryPolicy.permission),{satisfied:n.every(r=>r.satisfied),predicates:n}}function O(e,t,n,r){n&&e.push({predicate:t,satisfied:n.includes(r),required:n,actual:r})}function le(e){return!h(e)||e.schemaVersion!==de||!b(e.origin,U)||!si(e.coverage)||!di(e.producerValidation)||!ui(e.stateAuthority)||!li(e.repositoryPolicy)?!1:e.families===void 0||pi(e.families)}function si(e){return!h(e)||!b(e.state,qt)?!1:ai(e)&&ci(e)}function ai(e){return!(!R(e.returned)||typeof e.totalKnown!="boolean"||e.total!==void 0&&!R(e.total)||e.omitted!==void 0&&!R(e.omitted))}function ci(e){return e.state==="complete"?e.totalKnown===!0&&e.total===e.returned&&e.omitted===0:e.state==="partial"?e.totalKnown===!0&&R(e.total)&&R(e.omitted)&&e.total===Number(e.returned)+Number(e.omitted):e.totalKnown===!1}function di(e){if(!h(e)||!b(e.status,Kt))return!1;let t=e.certification;return e.status==="validated"||e.status==="failed"?h(t)&&f(t.id)&&Number.isSafeInteger(t.version)&&Number(t.version)>0&&f(t.corpus):t===void 0}function ui(e){return h(e)&&Number.isSafeInteger(e.policyVersion)&&(e.authority==="completion"||e.authority==="advisory"||e.authority==="none")&&Array.isArray(e.requiredRelationships)&&e.requiredRelationships.every(f)&&Array.isArray(e.reasons)&&e.reasons.every(f)}function li(e){return h(e)&&f(e.policyId)&&e.policyVersion===ue&&b(e.permission,Ht)&&Array.isArray(e.reasons)&&e.reasons.every(f)}function pi(e){return Array.isArray(e)&&e.every(t=>h(t)&&f(t.id)&&f(t.selector)&&hi(t.origin))}function hi(e){return h(e)?e.kind==="fixed"?b(e.origin,U)&&e.origin!=="mixed":e.kind!=="result-field"||!f(e.field)||!h(e.values)?!1:Object.values(e.values).every(t=>b(t,U)&&t!=="mixed"):!1}function b(e,t){return typeof e=="string"&&t.includes(e)}var Xt="scip-query-result",zt=0,I=1,gi=1,Zt=1,en=1;function tn(e){if(!h(e))return{kind:"malformed",reason:"CLI JSON output must be an object."};let t=Object.hasOwn(e,"kind"),n=Object.hasOwn(e,"schemaVersion");return!t&&!n?mi(e):!t||!n?{kind:"malformed",reason:"CLI JSON envelope must contain both kind and schemaVersion."}:e.kind!==Xt?{kind:"malformed",reason:`Unsupported CLI JSON envelope kind: ${xi(e.kind)}.`}:fi(e)}function fi(e){let t=e.schemaVersion;return!Number.isSafeInteger(t)||Number(t)<1?{kind:"malformed",reason:"CLI JSON envelope schemaVersion must be a positive safe integer."}:t!==I?{kind:"unsupported",schemaVersion:Number(t),direction:Number(t)<I?"older":"future",...q(e.producer)?{producer:e.producer}:{}}:Ci(e)}function mi(e){let t=rn(e);return t?{kind:"malformed",reason:`Legacy CLI JSON envelope: ${t}`}:{kind:"legacy",schemaVersion:zt,envelope:e}}function Ci(e){let t=rn(e);if(t)return{kind:"malformed",reason:`CLI JSON envelope v1: ${t}`};if(!q(e.producer))return{kind:"malformed",reason:"CLI JSON envelope v1: producer must identify scip-query and its non-empty version."};if(!fe(e.resultSchemaVersion))return{kind:"malformed",reason:"CLI JSON envelope v1: resultSchemaVersion must be a positive safe integer."};if(e.resultProjection!==void 0&&e.resultProjection!=="agent")return{kind:"malformed",reason:'CLI JSON envelope v1: resultProjection must be "agent" when present.'};let n=nn(e.command);if(!n.includes(e.resultSchemaVersion))return{kind:"unsupported-result",schemaVersion:I,command:e.command,resultSchemaVersion:e.resultSchemaVersion,supportedResultSchemaVersions:n};let r=yi(e);return r||{kind:"supported",schemaVersion:I,envelope:e}}function yi(e){return e.evidenceContext!==void 0&&!vi(e.evidenceContext)?{kind:"malformed",reason:"CLI JSON envelope v1: evidenceContext must contain a supported receipt and analysis manifest."}:e.operationRole!==void 0&&!J(e.operationRole)?{kind:"malformed",reason:"CLI JSON envelope v1: operationRole must be a supported command operation role."}:h(e.evidenceContext)&&e.operationRole!==void 0&&e.evidenceContext.operationRole!==void 0&&e.operationRole!==e.evidenceContext.operationRole?{kind:"malformed",reason:"CLI JSON envelope v1: top-level and evidence-context operation roles must agree."}:null}function Ri(e){let t=tn(e);if(t.kind==="legacy"||t.kind==="supported")return t;if(t.kind==="unsupported"){let n=t.producer?` from ${t.producer.name}@${t.producer.version}`:"";throw new Error(`Unsupported scip-query CLI JSON schemaVersion ${t.schemaVersion}${n}; this consumer supports the legacy unversioned envelope and schemaVersion ${I}.`)}throw t.kind==="unsupported-result"?new Error(`Unsupported resultSchemaVersion ${t.resultSchemaVersion} for scip-query command ${JSON.stringify(t.command)}; this consumer supports ${t.supportedResultSchemaVersions.join(", ")}.`):new Error(`Malformed scip-query CLI JSON envelope: ${t.reason}`)}function nn(e){return Si[e]??[gi]}var Si={};function rn(e){return typeof e.command!="string"||e.command.length===0?"command must be a non-empty string.":Array.isArray(e.args)?h(e.options)?Object.hasOwn(e,"result")?null:"result is required.":"options must be an object.":"args must be an array."}function vi(e){return!h(e)||e.schemaVersion!==Zt||e.operationRole!==void 0&&!J(e.operationRole)||!M(e.receipt)?!1:bi(e.analysisManifest)}function xi(e){return typeof e=="string"?JSON.stringify(e):String(e)}function bi(e){return h(e)&&e.schemaVersion===en&&(e.evidence===void 0||e.evidence==="graph-fact"||e.evidence==="heuristic"||e.evidence==="mixed")&&(e.claimQualification===void 0||le(e.claimQualification))}export{Ht as CLAIM_ACTION_PERMISSIONS,ue as CLAIM_ACTION_POLICY_VERSION,qt as CLAIM_COVERAGE_STATES,U as CLAIM_ORIGINS,de as CLAIM_QUALIFICATION_SCHEMA_VERSION,en as CLI_ANALYSIS_MANIFEST_SCHEMA_VERSION,Zt as CLI_EVIDENCE_CONTEXT_SCHEMA_VERSION,Xt as CLI_JSON_ENVELOPE_KIND,Bt as COMMAND_OPERATION_ROLES,I as CURRENT_CLI_JSON_ENVELOPE_SCHEMA_VERSION,Yt as DEFAULT_REPOSITORY_POLICY_ACTION,zt as LEGACY_CLI_JSON_ENVELOPE_SCHEMA_VERSION,qe as LEGACY_OBSERVATION_RECEIPT_SCHEMA_VERSION,Ye as OBSERVATION_IDENTITY_CANONICALIZATION_VERSION,Qe as OBSERVATION_IDENTITY_HASH_ALGORITHM,He as OBSERVATION_IDENTITY_SCHEMA_VERSION,Ke as OBSERVATION_RECEIPT_SCHEMA_VERSION,Xe as OBSERVATION_STATE_AUTHORITY_POLICY_VERSION,Kt as PRODUCER_VALIDATION_STATUSES,re as Watcher,ei as commandOperation,ni as commandOperationRoles,et as compareObservationReceipts,ze as createObservationIdentity,Mt as createReindexRunner,tn as decodeCliJsonEnvelope,Ze as decodeObservationReceipt,Qt as deriveClaimCoverage,ii as deriveClaimQualification,D as deriveObservationStateAuthority,oi as evaluateClaimQualification,cn as getScipVersion,On as initProjectConfig,Qr as installSkills,le as isClaimQualificationV1,J as isCommandOperationRole,M as isObservationReceipt,an as isScipInstalled,F as loadProjectConfig,tt as observationReceiptGenerationIdentity,rt as observationReceiptStabilityLabel,nt as observationReceiptWorkspaceIdentity,ri as operationObservesRepository,dn as printScipInstallInstructions,Ri as requireCompatibleCliJsonEnvelope,ti as resolveCommandOperationRole,A as resolveIndexStoragePaths,At as resolveReindexWorkerLaunch,nn as supportedCliResultSchemaVersions};
5
4
  //# sourceMappingURL=runtime.js.map
@@ -1,2 +1,2 @@
1
- import{j as O}from"./chunk-OWOOWNJ5.js";import{e as E,f as A,g as C,h as V,m as F}from"./chunk-SSK6LDPC.js";import"./chunk-4WNW27SX.js";import"./chunk-F4FNK44D.js";import"./chunk-GAS2LJMP.js";import"./chunk-DRENNWRG.js";import"./chunk-2OOY75BW.js";import{b as h}from"./chunk-3AF4TUFK.js";import{b as q,c as N,h as _,i as T,m as g,n as k,o as P,p as B,r as U}from"./chunk-FGA2U4OR.js";import{a as x}from"./chunk-B3PYOSCX.js";import"./chunk-H5EXS3HM.js";import"./chunk-HGFDYOVB.js";import{c as L,d as b,e as v}from"./chunk-JFMEXGFE.js";import"./chunk-KYSDI3GE.js";import"./chunk-7F45LJKI.js";import n from"process";import{randomUUID as J}from"crypto";import{rmSync as W}from"fs";import{resolve as S}from"path";import{pathToFileURL as X}from"url";var G=10*6e4,j=10,z=250,Y=1e3;function $(e,t,o={}){let M=_(e),d=o.now??(o.nowMs===void 0?Date.now:()=>o.nowMs),f=d(),y=A(e),w=g(M,{ownerId:o.ownerId??re,nowMs:f,limits:o.limits,owner:ne,liveness:ie}),p=0;for(let i of w){let s=null,c,m="handler-error";try{let a=k(i,o.limits),u;try{u=JSON.parse(a)}catch{throw m="malformed-request",new Error("Durable Rust semantic helper received malformed request JSON.")}let r=C(u,{claimRequestId:i.requestId,sessionIdentity:y,nowMs:d()});if(!r.ok)throw m=r.code,c=r.responseIdentity,new Error(r.error);s=r.value,c={id:s.id,sessionIdentity:s.sessionIdentity,deadlineAtMs:s.deadlineAtMs};let l=K(s.request,o.monotonicNowMs??b());o.beforeRequest?.(l);let R=t.handle(l),I=d();if(s.deadlineAtMs<I)throw m="expired-request",new Error("Durable Rust semantic request expired while the helper was processing it.");P(M,i,{ok:!0,protocolVersion:E,id:s.id,sessionIdentity:s.sessionIdentity,deadlineAtMs:s.deadlineAtMs,...R},{nowMs:I,limits:o.limits})}catch(a){let u=d(),r=c??(s?{id:s.id,sessionIdentity:s.sessionIdentity,deadlineAtMs:s.deadlineAtMs}:void 0),l=a instanceof Error?a.message:String(a);B(M,i,{ok:!1,protocolVersion:E,id:r?.id??i.requestId,...r?{sessionIdentity:r.sessionIdentity,deadlineAtMs:r.deadlineAtMs}:{},errorCode:m,error:l},l,{nowMs:u,limits:o.limits})}p+=1}return p}function K(e,t){let o=t+Math.max(1,e.timeoutMs-1e3);return{...e,request:{...e.request,readinessDeadlineMs:o}}}async function Q(e,t){let o=_(e);T(o);let M=S(e,"server.lock"),d=te(M);if(!d)return;let f=new V(()=>F({semanticWorkerPath:t,shareEnvironment:!0})),y=!1,w=b(),p=Number.NEGATIVE_INFINITY,i,s=0,c=L(n.pid),m=A(e),a=()=>{y=!0};n.once("SIGINT",a),n.once("SIGTERM",a);let u=(r=!1,l=r?"durable":"visibility")=>{let R=Date.now(),I=b();if(!r&&I-p<Y)return;p=I;let D={protocolVersion:E,sessionIdentity:m,pid:n.pid,...c?{processIdentity:c}:{},heartbeatAtMs:R,...i===void 0?{}:{busyUntilMs:i},mailbox:U(o)};l==="durable"?N(S(e,"server.json"),D):q(S(e,"server.json"),D)};try{u(!0);let r=se();for(;!y&&b()-w<r;){let l=$(e,f,{beforeRequest(R){i=Date.now()+R.timeoutMs+5e3,u(!0,"visibility")}});l>0?(s=0,w=b(),i=void 0,u(!0,"visibility")):(s+=1,u()),await O(Z(l,s))}}finally{f.shutdown(),W(S(e,"server.json"),{force:!0}),d.release()}}function Z(e,t=1){return v(e,t,j,j,z,5)}var ee=e=>{let t=Number(e);return Number.isInteger(t)&&t>0?{pid:t}:null};function te(e){let t=h(e,{kind:"rust-durable-session-server",parseLegacy:ee});return t.kind==="acquired"?t.lock:null}function se(){let e=Number(n.env.SCIP_RUST_SEMANTIC_DURABLE_IDLE_MS);return Number.isInteger(e)&&e>=0?e:G}var oe=n.argv[1]?X(S(n.argv[1])).href:null;if(oe===import.meta.url){let e=n.argv[2],t=n.argv[3];!e||!t?(console.error("durable-rust-session: expected <session-dir> <semantic-worker-path>"),n.exitCode=1):await Q(e,t)}var re=`rust-semantic-${n.pid}-${J()}`,H=L(n.pid),ne={pid:n.pid,...H?{processIdentity:H}:{}},ie={isProcessAlive:x,readProcessIdentity:L};export{te as acquireDurableRustSessionServerLock,Z as durableSessionLoopDelayMs,$ as processDurableRustSessionRequests};
1
+ import{j as O}from"./chunk-64DZ5TXR.js";import{e as L,f as _,g as C,h as V,m as F}from"./chunk-TRBI4UKT.js";import"./chunk-WKPV2TDZ.js";import"./chunk-F4FNK44D.js";import"./chunk-ZLADLUE6.js";import"./chunk-6FFVZZL4.js";import{c as T}from"./chunk-BL6XJKTA.js";import{e as D,f as N,j as P,k,l as B,m as g,o as U}from"./chunk-3JIQS44J.js";import{c as A,d as x}from"./chunk-O4UZSPPI.js";import{a as h}from"./chunk-B3PYOSCX.js";import"./chunk-HRRFKWPZ.js";import"./chunk-YULZRALL.js";import"./chunk-HGFDYOVB.js";import{c as E,d as I,e as q}from"./chunk-QZ7KQZRN.js";import"./chunk-TKD34PHN.js";import"./chunk-2HLAFUCY.js";import"./chunk-U5RIG3JP.js";import"./chunk-62BDNPMI.js";import n from"process";import{randomUUID as J}from"crypto";import{rmSync as W}from"fs";import{resolve as w}from"path";import{pathToFileURL as X}from"url";var G=10*6e4,j=10,z=250,Y=1e3;function $(e,t,o={}){let i=D(e),d=o.now??(o.nowMs===void 0?Date.now:()=>o.nowMs),c=d(),b=_(e),R=P(i,{ownerId:o.ownerId??ne,nowMs:c,limits:o.limits,owner:re,liveness:ie}),l=0;for(let r of R){let s=null,p,M="handler-error";try{let f=k(r,o.limits),a;try{a=JSON.parse(f)}catch{throw M="malformed-request",new Error("Durable Rust semantic helper received malformed request JSON.")}let u=C(a,{claimRequestId:r.requestId,sessionIdentity:b,nowMs:d()});if(!u.ok)throw M=u.code,p=u.responseIdentity,new Error(u.error);s=u.value,p={id:s.id,sessionIdentity:s.sessionIdentity,deadlineAtMs:s.deadlineAtMs};let m=K(s.request,o.monotonicNowMs??I());o.beforeRequest?.(m);let S=t.handle(m),y=d();if(s.deadlineAtMs<y)throw M="expired-request",new Error("Durable Rust semantic request expired while the helper was processing it.");B(i,r,{ok:!0,protocolVersion:L,id:s.id,sessionIdentity:s.sessionIdentity,deadlineAtMs:s.deadlineAtMs,...S},{nowMs:y,limits:o.limits})}catch(f){let a=d();le(i,r,p,s,M,f,a,o.limits)}l+=1}return l}function K(e,t){let o=t+Math.max(1,e.timeoutMs-1e3);return{...e,request:{...e.request,readinessDeadlineMs:o}}}async function Q(e,t){let o=D(e);N(o);let i=w(e,"server.lock"),d=te(i);if(!d)return;let c=new V(()=>F({semanticWorkerPath:t,shareEnvironment:!0})),b=!1,R=I(),l=Number.NEGATIVE_INFINITY,r,s=0,p=E(n.pid),M=_(e),f=()=>{b=!0};n.once("SIGINT",f),n.once("SIGTERM",f);let a=(u=!1,m=u?"durable":"visibility")=>{let S=Date.now(),y=I();if(!u&&y-l<Y)return;l=y;let v={protocolVersion:L,sessionIdentity:M,pid:n.pid,...p?{processIdentity:p}:{},heartbeatAtMs:S,...r===void 0?{}:{busyUntilMs:r},mailbox:U(o)};m==="durable"?x(w(e,"server.json"),v):A(w(e,"server.json"),v)};try{a(!0);let u=oe();for(;!b&&I()-R<u;){let m=$(e,c,{beforeRequest(S){r=Date.now()+S.timeoutMs+5e3,a(!0,"visibility")}});m>0?(s=0,R=I(),r=void 0,a(!0,"visibility")):(s+=1,a()),await O(Z(m,s))}}finally{c.shutdown(),W(w(e,"server.json"),{force:!0}),d.release()}}function Z(e,t=1){return q(e,t,j,j,z,5)}var ee=e=>{let t=Number(e);return Number.isInteger(t)&&t>0?{pid:t}:null};function te(e){let t=T(e,{kind:"rust-durable-session-server",parseLegacy:ee});return t.kind==="acquired"?t.lock:null}function oe(){let e=Number(n.env.SCIP_RUST_SEMANTIC_DURABLE_IDLE_MS);return Number.isInteger(e)&&e>=0?e:G}var se=n.argv[1]?X(w(n.argv[1])).href:null;if(se===import.meta.url){let e=n.argv[2],t=n.argv[3];!e||!t?(console.error("durable-rust-session: expected <session-dir> <semantic-worker-path>"),n.exitCode=1):await Q(e,t)}var ne=`rust-semantic-${n.pid}-${J()}`,H=E(n.pid),re={pid:n.pid,...H?{processIdentity:H}:{}},ie={isProcessAlive:h,readProcessIdentity:E};function le(e,t,o,i,d,c,b,R){let l=o??(i?{id:i.id,sessionIdentity:i.sessionIdentity,deadlineAtMs:i.deadlineAtMs}:void 0),r=c instanceof Error?c.message:String(c);g(e,t,{ok:!1,protocolVersion:L,id:l?.id??t.requestId,...l?{sessionIdentity:l.sessionIdentity,deadlineAtMs:l.deadlineAtMs}:{},errorCode:d,error:r},r,{nowMs:b,limits:R})}export{te as acquireDurableRustSessionServerLock,Z as durableSessionLoopDelayMs,$ as processDurableRustSessionRequests};
2
2
  //# sourceMappingURL=rust-semantic-session-server.js.map
@@ -1,2 +1,2 @@
1
- import{b as H,c as U,d as K,e as W,f as le,i as ce,j as ue,k as de,l as fe,m as D,o as me,p as pe}from"./chunk-BDUVI7TO.js";import{a as P,b as ne}from"./chunk-ILMHV3KM.js";import{b as te,c as ie,d as C,e as N,f as G,h as E,i as B,j as S}from"./chunk-OWOOWNJ5.js";import{d as F,e as se,f as re,g as oe,h as ae}from"./chunk-GAS2LJMP.js";import"./chunk-2OOY75BW.js";import{a as j,f as d,g as M}from"./chunk-HGFDYOVB.js";import"./chunk-JFMEXGFE.js";import{$ as ee,_ as q}from"./chunk-KYSDI3GE.js";import"./chunk-7F45LJKI.js";import k from"process";import{existsSync as Te,writeFileSync as ve}from"fs";import{dirname as Ae,isAbsolute as Ie,resolve as Ce}from"path";import{performance as L}from"perf_hooks";import{parentPort as Ee}from"worker_threads";import{resolve as he}from"path";var ze=4,x=class{constructor(n=ze){this.capacity=n;if(!Number.isSafeInteger(n)||n<=0)throw new Error("Rust analyzer session capacity must be a positive safe integer.")}capacity;entries=new Map;get(n){let i=this.entries.get(n);if(i)return this.entries.delete(n),this.entries.set(n,i),i}async acquire(n,i,t){let s=this.get(n);if(s)return s;if(this.entries.size>=this.capacity){let o=this.entries.entries().next().value;if(!o)throw new Error("Rust analyzer session registry capacity accounting is inconsistent.");this.entries.delete(o[0]);try{await t(o[1])}catch(l){throw this.restoreOldest(o),l}}let r=await i();if(r.key!==n){try{await t(r)}catch(o){throw new AggregateError([o],`Rust analyzer session factory returned '${r.key}' for reserved key '${n}', and the mismatched session could not be reaped.`,{cause:o})}throw new Error(`Rust analyzer session factory returned '${r.key}' for reserved key '${n}'.`)}return this.entries.set(n,r),r}deleteIfSame(n){return this.entries.get(n.key)!==n?!1:this.entries.delete(n.key)}async shutdownAll(n){let i=[...this.entries.values()];this.entries.clear();let t=await Promise.allSettled(i.map(n)),s=[];for(let r=0;r<t.length;r+=1){let o=t[r];if(o.status==="fulfilled")continue;let l=i[r];s.push({session:l,reason:o.reason}),this.entries.set(l.key,l)}if(s.length>0)throw new AggregateError(s.map(r=>r.reason),`Failed to shut down ${s.length} retained rust-analyzer session(s).`)}get size(){return this.entries.size}restoreOldest(n){let i=[...this.entries.entries()];this.entries.clear(),this.entries.set(n[0],n[1]);for(let[t,s]of i)this.entries.set(t,s)}};function Re(e,n){let i=he(e);return[...new Set(n.map(t=>he(i,t)))].sort((t,s)=>t<s?-1:t>s?1:0)}function ye(e,n,i){return JSON.stringify({binary:e,sessionRoot:n,linkedProjects:i})}var Fe="SCIP_RUST_SEMANTIC_REFERENCE_TASK_PROFILE_MS",We="SCIP_RUST_SEMANTIC_CALLEE_TASK_PROFILE_MS",_=new x,ge=Promise.resolve(),Me;Ee?.on("message",e=>{ge=ge.then(()=>xe(e)).catch(()=>{})});async function xe(e){if(Me??=Ae(e.responsePath),e.kind==="shutdown"){await He(),g(e.responsePath,{ok:!0},e.sharedBuffer);return}if(e.kind==="import-definitions"){try{let n=await Le(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t={available:!1,reason:n instanceof Error?n.message:String(n),sourcePaths:e.request.positions.map(s=>[s.id,null])};g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}return}try{let n=await _e(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t=De(e.request,n instanceof Error?n.message:String(n));g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}}async function Le(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=await d("rust.semantic.worker.session",()=>Pe(e.projectRoot,e.rustAnalyzerBinary,[e.file],{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs}),()=>({kind:"import-definitions",files:1,positions:e.positions.length}));if(!i.capabilities.definitionProvider)return{available:!1,reason:"rust-analyzer initialized without textDocument/definition support.",sourcePaths:e.positions.map(o=>[o.id,null])};let t=0;await E(()=>d("rust.semantic.worker.open-source-documents",async()=>{t=await Ne(i,e.projectRoot,[e.file],{diagnosticsTimeoutMs:e.diagnosticsTimeoutMs,settleDelayMs:e.settleDelayMs,readinessDeadlineMs:e.readinessDeadlineMs})},()=>({files:1,openedDocuments:t,positions:e.positions.length})),()=>ke(_,i,e.readinessDeadlineMs));let s=0;return{available:!0,sourcePaths:await d("rust.semantic.worker.import-definitions",()=>P(e.positions,e.concurrency??8,async o=>{let l=await i.client.definition({textDocument:{uri:F(e.projectRoot,o.file)},position:{line:o.line,character:o.column}},n),u=Ge(e.projectRoot,l);return u&&(s+=1),[o.id,u]}),()=>({positions:e.positions.length,resolvedPositions:s,concurrency:e.concurrency??8}))}}async function _e(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=e.includeReferences!==!1,t=e.includeCallees===!0,s=e.includeSignatures===!0,r=H(e),o=U(e),l=K(e),u=W(e),c=await d("rust.semantic.worker.session",()=>Oe(e),()=>({kind:"semantic",definitions:u.length,referenceDefinitions:r.length,calleeDefinitions:o.length,signatureDefinitions:l.length,references:i,callees:t,signatures:s})),p=Be(c.capabilities,{references:i,callees:t,signatures:s});if(p)return De(e,p);let f=0;await E(()=>d("rust.semantic.worker.open-definition-documents",async()=>{f=await je(c,e)},()=>({definitions:u.length,openedDocuments:f})),()=>ke(_,c,e.readinessDeadlineMs));let m=0,b=0,y=j(),$=y?new Map:null,z=y?we(k.env[Fe]):null,J=()=>i?d("rust.semantic.worker.references",()=>P(r,e.concurrency??8,async a=>{let w=y?L.now():0,R=await me(c.client,re(e.projectRoot,a,!1),{requestTimeoutMs:e.requestTimeoutMs,retryTimeoutMs:e.referenceRetryTimeoutMs,deadlineMs:e.readinessDeadlineMs}),h=ae(oe(e.projectRoot,R.locations)),I=y?Math.round(L.now()-w):0;return Ue($,a.relativePath,{durationMs:I,references:h.length,hasReferences:h.length>0,slow:z!==null&&I>=z}),z!==null&&I>=z&&M({type:"span",name:"rust.semantic.worker.reference-task",durationMs:I,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,references:h.length,complete:R.complete}),h.length>0&&(b+=1),m+=h.length,{symbolId:a.symbolId,references:h,complete:R.complete}}),()=>({definitions:r.length,concurrency:e.concurrency??8,definitionsWithReferences:b,references:m})):Promise.resolve(r.map(a=>({symbolId:a.symbolId,references:[],complete:!0}))),V=0,Y=0,T=j(),Z=T?new Map:null,v=T?we(k.env[We]):null,Q=()=>t?d("rust.semantic.worker.callees",()=>P(o,e.concurrency??8,async a=>{let w=T?L.now():0,R=await pe(c.client,e.projectRoot,a,n),h=T?Math.round(L.now()-w):0;return Je(Z,a.relativePath,{durationMs:h,callees:R.length,hasCallees:R.length>0,slow:v!==null&&h>=v}),v!==null&&h>=v&&M({type:"span",name:"rust.semantic.worker.callee-task",durationMs:h,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,callees:R.length}),R.length>0&&(Y+=1),V+=R.length,{symbolId:a.symbolId,callees:R}}),()=>({definitions:o.length,concurrency:e.concurrency??8,definitionsWithCallees:Y,callees:V})):Promise.resolve([]),A,O;i&&t&&r.length>0&&o.length>0&&Ze()?[A,O]=await ne([J(),Q()]):(A=await J(),O=await Q()),Ke($),Ve(Z);let X=0,be=s?await d("rust.semantic.worker.signatures",()=>P(l,e.concurrency??8,async a=>{let w=await le(c.client,e.projectRoot,a,n);return w&&(X+=1),{symbolId:a.symbolId,signature:w}}),()=>({definitions:l.length,concurrency:e.concurrency??8,signaturesFound:X})):[];return{available:!0,references:A.filter(a=>a.complete).map(a=>[a.symbolId,a.references]),incompleteReferenceSymbolIds:A.filter(a=>!a.complete).map(a=>a.symbolId),...t?{callees:O.map(a=>[a.symbolId,a.callees])}:{},...s?{signatures:be.map(a=>[a.symbolId,a.signature])}:{}}}async function Oe(e){return Pe(e.projectRoot,e.rustAnalyzerBinary,W(e).map(n=>n.relativePath),{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs})}async function Pe(e,n,i,t){let s=Re(e,de(e,i.map(l=>({relativePath:l})))),r=ue(e,s),o=ye(n,r,s);return _.acquire(o,async()=>{let l=ce(s),u=new te(ie(n,r,k.env,Me),{requestTimeoutMs:t.requestTimeoutMs,configuration:l}),c=t.readinessDeadlineMs===void 0?null:{afterGeneration:u.serverStatusGeneration(),deadlineMs:t.readinessDeadlineMs},p=await E(()=>d("rust.semantic.worker.initialize",()=>u.initialize({processId:k.pid,rootUri:F(r,"."),capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1},callHierarchy:{dynamicRegistration:!1},hover:{dynamicRegistration:!1}}},initializationOptions:l},{timeoutMs:t.requestTimeoutMs,deadlineMs:t.readinessDeadlineMs}),()=>({linkedProjects:s.length,relativePaths:i.length})),()=>u.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}));return{key:o,client:u,capabilities:p.capabilities,openedPaths:new Set,initializationReadiness:c}},l=>l.client.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}))}async function je(e,n){let i=W(n).filter(c=>e.openedPaths.has(c.relativePath)?!1:Te(Ce(n.projectRoot,c.relativePath)));if(i.length===0)return await Se(e),0;let t=e.initializationReadiness,s=n.readinessDeadlineMs===void 0?null:{statusSnapshot:t?null:e.client.serverStatusSnapshot(),initializationGeneration:t?.afterGeneration,deadlineMs:n.readinessDeadlineMs},r=fe(e.client,n.projectRoot,i);for(let c of i)e.openedPaths.add(c.relativePath);let o=n.diagnosticsTimeoutMs??1e4,l=o;await d("rust.semantic.worker.diagnostics",()=>s?G(c=>(l=c,D(e.client,r,c)),o,s.deadlineMs):D(e.client,r,o),()=>({openedDocuments:r.length,timeoutMs:l}));let u=n.settleDelayMs??5e3;if(!s)await d("rust.semantic.worker.settle",()=>S(u),()=>({openedDocuments:r.length,settleDelayMs:u}));else{let c;await d("rust.semantic.worker.readiness",async()=>{let p=m=>d("rust.semantic.worker.settle",()=>S(m),()=>({openedDocuments:r.length,settleDelayMs:m})),f=s.initializationGeneration===void 0?await N(e.client,s.statusSnapshot,r.length,s.deadlineMs,u,Date.now,p):await C(e.client,s.initializationGeneration,r.length,s.deadlineMs,u,Date.now,p);s.initializationGeneration!==void 0&&(e.initializationReadiness=null),c=f?.health},()=>({phase:s.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:r.length,health:c}))}return r.length}async function Ne(e,n,i,t){let s=i.filter(f=>!e.openedPaths.has(f));if(s.length===0)return await Se(e),0;let r=e.initializationReadiness,o=t.readinessDeadlineMs===void 0?null:{statusSnapshot:r?null:e.client.serverStatusSnapshot(),initializationGeneration:r?.afterGeneration,deadlineMs:t.readinessDeadlineMs},l=[];for(let f of s)try{let m=F(n,f);e.client.didOpenTextDocument({uri:m,languageId:"rust",version:1,text:q(n,f,{inputKind:"indexed Rust source file"})}),e.openedPaths.add(f),l.push(m)}catch(m){if(!ee(m))throw m}let u=t.diagnosticsTimeoutMs??1e4,c=u;await d("rust.semantic.worker.diagnostics",()=>o?G(f=>(c=f,D(e.client,l,f)),u,o.deadlineMs):D(e.client,l,u),()=>({openedDocuments:l.length,timeoutMs:c}));let p=t.settleDelayMs??5e3;if(!o)await d("rust.semantic.worker.settle",()=>S(p),()=>({openedDocuments:l.length,settleDelayMs:p}));else{let f;await d("rust.semantic.worker.readiness",async()=>{let m=y=>d("rust.semantic.worker.settle",()=>S(y),()=>({openedDocuments:l.length,settleDelayMs:y})),b=o.initializationGeneration===void 0?await N(e.client,o.statusSnapshot,l.length,o.deadlineMs,p,Date.now,m):await C(e.client,o.initializationGeneration,l.length,o.deadlineMs,p,Date.now,m);o.initializationGeneration!==void 0&&(e.initializationReadiness=null),f=b?.health},()=>({phase:o.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:l.length,health:f}))}return l.length}async function Se(e){let n=e.initializationReadiness;if(!n)return;let i;await d("rust.semantic.worker.readiness",async()=>{i=(await C(e.client,n.afterGeneration,0,n.deadlineMs,0)).health,e.initializationReadiness=null},()=>({phase:"initialize",openedDocuments:0,health:i}))}function Ge(e,n){for(let i of n){let t=se(e,i.uri);if(!(!t||t===".."||t.startsWith("../")||Ie(t)))return t}return null}function Be(e,n){return n.references&&!e.referencesProvider?"rust-analyzer initialized without textDocument/references support.":n.callees&&!e.callHierarchyProvider?"rust-analyzer initialized without call hierarchy support.":n.signatures&&!e.hoverProvider?"rust-analyzer initialized without hover support.":null}function De(e,n){let i=H(e),t=U(e),s=K(e);return{available:!1,reason:n,references:i.map(r=>[r.symbolId,[]]),...e.includeCallees?{callees:t.map(r=>[r.symbolId,[]])}:{},...e.includeSignatures?{signatures:s.map(r=>[r.symbolId,null])}:{}}}async function He(){await _.shutdownAll(e=>e.client.shutdownAndReap())}async function ke(e,n,i){e.deleteIfSame(n),await n.client.shutdownAndReap({deadlineMs:i})}function Ue(e,n,i){if(!e)return;let t=$e(e,n);t.definitions+=1,i.hasReferences&&(t.definitionsWithReferences+=1),t.references+=i.references,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ke(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.references.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithReferences:t.definitionsWithReferences,references:t.references,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function $e(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithReferences:0,references:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function Je(e,n,i){if(!e)return;let t=Ye(e,n);t.definitions+=1,i.hasCallees&&(t.definitionsWithCallees+=1),t.callees+=i.callees,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ve(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.callees.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithCallees:t.definitionsWithCallees,callees:t.callees,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function Ye(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithCallees:0,callees:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function we(e){if(e===void 0||e==="")return null;let n=Number(e);return Number.isInteger(n)&&n>=0?n:null}function Ze(){let e=k.env.SCIP_RUST_SEMANTIC_PARALLEL_OPERATIONS;return e!=="0"&&e!=="false"}function g(e,n,i){ve(e,JSON.stringify(n));let t=new Int32Array(i);Atomics.store(t,0,1),Atomics.notify(t,0)}export{ke as discardRustAnalyzerSession};
1
+ import{b as H,c as U,d as K,e as W,f as le,i as ce,j as ue,k as de,l as fe,m as D,o as me,p as pe}from"./chunk-FL7NBMHP.js";import{a as P,b as ne}from"./chunk-ILMHV3KM.js";import{b as te,c as ie,d as C,e as N,f as G,h as E,i as B,j as S}from"./chunk-64DZ5TXR.js";import{d as F,e as se,f as re,g as oe,h as ae}from"./chunk-ZLADLUE6.js";import"./chunk-6FFVZZL4.js";import{a as j,f as d,g as M}from"./chunk-HGFDYOVB.js";import"./chunk-QZ7KQZRN.js";import{u as q,v as ee}from"./chunk-TKD34PHN.js";import"./chunk-2HLAFUCY.js";import"./chunk-U5RIG3JP.js";import"./chunk-62BDNPMI.js";import k from"process";import{existsSync as Te,writeFileSync as ve}from"fs";import{dirname as Ae,isAbsolute as Ie,resolve as Ce}from"path";import{performance as L}from"perf_hooks";import{parentPort as Ee}from"worker_threads";import{resolve as he}from"path";var ze=4,x=class{constructor(n=ze){this.capacity=n;if(!Number.isSafeInteger(n)||n<=0)throw new Error("Rust analyzer session capacity must be a positive safe integer.")}capacity;entries=new Map;get(n){let i=this.entries.get(n);if(i)return this.entries.delete(n),this.entries.set(n,i),i}async acquire(n,i,t){let s=this.get(n);if(s)return s;if(this.entries.size>=this.capacity){let o=this.entries.entries().next().value;if(!o)throw new Error("Rust analyzer session registry capacity accounting is inconsistent.");this.entries.delete(o[0]);try{await t(o[1])}catch(l){throw this.restoreOldest(o),l}}let r=await i();if(r.key!==n){try{await t(r)}catch(o){throw new AggregateError([o],`Rust analyzer session factory returned '${r.key}' for reserved key '${n}', and the mismatched session could not be reaped.`,{cause:o})}throw new Error(`Rust analyzer session factory returned '${r.key}' for reserved key '${n}'.`)}return this.entries.set(n,r),r}deleteIfSame(n){return this.entries.get(n.key)!==n?!1:this.entries.delete(n.key)}async shutdownAll(n){let i=[...this.entries.values()];this.entries.clear();let t=await Promise.allSettled(i.map(n)),s=[];for(let r=0;r<t.length;r+=1){let o=t[r];if(o.status==="fulfilled")continue;let l=i[r];s.push({session:l,reason:o.reason}),this.entries.set(l.key,l)}if(s.length>0)throw new AggregateError(s.map(r=>r.reason),`Failed to shut down ${s.length} retained rust-analyzer session(s).`)}get size(){return this.entries.size}restoreOldest(n){let i=[...this.entries.entries()];this.entries.clear(),this.entries.set(n[0],n[1]);for(let[t,s]of i)this.entries.set(t,s)}};function Re(e,n){let i=he(e);return[...new Set(n.map(t=>he(i,t)))].sort((t,s)=>t<s?-1:t>s?1:0)}function ye(e,n,i){return JSON.stringify({binary:e,sessionRoot:n,linkedProjects:i})}var Fe="SCIP_RUST_SEMANTIC_REFERENCE_TASK_PROFILE_MS",We="SCIP_RUST_SEMANTIC_CALLEE_TASK_PROFILE_MS",_=new x,ge=Promise.resolve(),Me;Ee?.on("message",e=>{ge=ge.then(()=>xe(e)).catch(()=>{})});async function xe(e){if(Me??=Ae(e.responsePath),e.kind==="shutdown"){await He(),g(e.responsePath,{ok:!0},e.sharedBuffer);return}if(e.kind==="import-definitions"){try{let n=await Le(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t={available:!1,reason:n instanceof Error?n.message:String(n),sourcePaths:e.request.positions.map(s=>[s.id,null])};g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}return}try{let n=await _e(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t=De(e.request,n instanceof Error?n.message:String(n));g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}}async function Le(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=await d("rust.semantic.worker.session",()=>Pe(e.projectRoot,e.rustAnalyzerBinary,[e.file],{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs}),()=>({kind:"import-definitions",files:1,positions:e.positions.length}));if(!i.capabilities.definitionProvider)return{available:!1,reason:"rust-analyzer initialized without textDocument/definition support.",sourcePaths:e.positions.map(o=>[o.id,null])};let t=0;await E(()=>d("rust.semantic.worker.open-source-documents",async()=>{t=await Ne(i,e.projectRoot,[e.file],{diagnosticsTimeoutMs:e.diagnosticsTimeoutMs,settleDelayMs:e.settleDelayMs,readinessDeadlineMs:e.readinessDeadlineMs})},()=>({files:1,openedDocuments:t,positions:e.positions.length})),()=>ke(_,i,e.readinessDeadlineMs));let s=0;return{available:!0,sourcePaths:await d("rust.semantic.worker.import-definitions",()=>P(e.positions,e.concurrency??8,async o=>{let l=await i.client.definition({textDocument:{uri:F(e.projectRoot,o.file)},position:{line:o.line,character:o.column}},n),u=Ge(e.projectRoot,l);return u&&(s+=1),[o.id,u]}),()=>({positions:e.positions.length,resolvedPositions:s,concurrency:e.concurrency??8}))}}async function _e(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=e.includeReferences!==!1,t=e.includeCallees===!0,s=e.includeSignatures===!0,r=H(e),o=U(e),l=K(e),u=W(e),c=await d("rust.semantic.worker.session",()=>Oe(e),()=>({kind:"semantic",definitions:u.length,referenceDefinitions:r.length,calleeDefinitions:o.length,signatureDefinitions:l.length,references:i,callees:t,signatures:s})),p=Be(c.capabilities,{references:i,callees:t,signatures:s});if(p)return De(e,p);let f=0;await E(()=>d("rust.semantic.worker.open-definition-documents",async()=>{f=await je(c,e)},()=>({definitions:u.length,openedDocuments:f})),()=>ke(_,c,e.readinessDeadlineMs));let m=0,b=0,y=j(),$=y?new Map:null,z=y?we(k.env[Fe]):null,J=()=>i?d("rust.semantic.worker.references",()=>P(r,e.concurrency??8,async a=>{let w=y?L.now():0,R=await me(c.client,re(e.projectRoot,a,!1),{requestTimeoutMs:e.requestTimeoutMs,retryTimeoutMs:e.referenceRetryTimeoutMs,deadlineMs:e.readinessDeadlineMs}),h=ae(oe(e.projectRoot,R.locations)),I=y?Math.round(L.now()-w):0;return Ue($,a.relativePath,{durationMs:I,references:h.length,hasReferences:h.length>0,slow:z!==null&&I>=z}),z!==null&&I>=z&&M({type:"span",name:"rust.semantic.worker.reference-task",durationMs:I,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,references:h.length,complete:R.complete}),h.length>0&&(b+=1),m+=h.length,{symbolId:a.symbolId,references:h,complete:R.complete}}),()=>({definitions:r.length,concurrency:e.concurrency??8,definitionsWithReferences:b,references:m})):Promise.resolve(r.map(a=>({symbolId:a.symbolId,references:[],complete:!0}))),V=0,Y=0,T=j(),Z=T?new Map:null,v=T?we(k.env[We]):null,Q=()=>t?d("rust.semantic.worker.callees",()=>P(o,e.concurrency??8,async a=>{let w=T?L.now():0,R=await pe(c.client,e.projectRoot,a,n),h=T?Math.round(L.now()-w):0;return Je(Z,a.relativePath,{durationMs:h,callees:R.length,hasCallees:R.length>0,slow:v!==null&&h>=v}),v!==null&&h>=v&&M({type:"span",name:"rust.semantic.worker.callee-task",durationMs:h,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,callees:R.length}),R.length>0&&(Y+=1),V+=R.length,{symbolId:a.symbolId,callees:R}}),()=>({definitions:o.length,concurrency:e.concurrency??8,definitionsWithCallees:Y,callees:V})):Promise.resolve([]),A,O;Qe(i,t,r.length,o.length)?[A,O]=await ne([J(),Q()]):(A=await J(),O=await Q()),Ke($),Ve(Z);let X=0,be=s?await d("rust.semantic.worker.signatures",()=>P(l,e.concurrency??8,async a=>{let w=await le(c.client,e.projectRoot,a,n);return w&&(X+=1),{symbolId:a.symbolId,signature:w}}),()=>({definitions:l.length,concurrency:e.concurrency??8,signaturesFound:X})):[];return{available:!0,references:A.filter(a=>a.complete).map(a=>[a.symbolId,a.references]),incompleteReferenceSymbolIds:A.filter(a=>!a.complete).map(a=>a.symbolId),...t?{callees:O.map(a=>[a.symbolId,a.callees])}:{},...s?{signatures:be.map(a=>[a.symbolId,a.signature])}:{}}}async function Oe(e){return Pe(e.projectRoot,e.rustAnalyzerBinary,W(e).map(n=>n.relativePath),{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs})}async function Pe(e,n,i,t){let s=Re(e,de(e,i.map(l=>({relativePath:l})))),r=ue(e,s),o=ye(n,r,s);return _.acquire(o,async()=>{let l=ce(s),u=new te(ie(n,r,k.env,Me),{requestTimeoutMs:t.requestTimeoutMs,configuration:l}),c=t.readinessDeadlineMs===void 0?null:{afterGeneration:u.serverStatusGeneration(),deadlineMs:t.readinessDeadlineMs},p=await E(()=>d("rust.semantic.worker.initialize",()=>u.initialize({processId:k.pid,rootUri:F(r,"."),capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1},callHierarchy:{dynamicRegistration:!1},hover:{dynamicRegistration:!1}}},initializationOptions:l},{timeoutMs:t.requestTimeoutMs,deadlineMs:t.readinessDeadlineMs}),()=>({linkedProjects:s.length,relativePaths:i.length})),()=>u.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}));return{key:o,client:u,capabilities:p.capabilities,openedPaths:new Set,initializationReadiness:c}},l=>l.client.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}))}async function je(e,n){let i=W(n).filter(c=>e.openedPaths.has(c.relativePath)?!1:Te(Ce(n.projectRoot,c.relativePath)));if(i.length===0)return await Se(e),0;let t=e.initializationReadiness,s=n.readinessDeadlineMs===void 0?null:{statusSnapshot:t?null:e.client.serverStatusSnapshot(),initializationGeneration:t?.afterGeneration,deadlineMs:n.readinessDeadlineMs},r=fe(e.client,n.projectRoot,i);for(let c of i)e.openedPaths.add(c.relativePath);let o=n.diagnosticsTimeoutMs??1e4,l=o;await d("rust.semantic.worker.diagnostics",()=>s?G(c=>(l=c,D(e.client,r,c)),o,s.deadlineMs):D(e.client,r,o),()=>({openedDocuments:r.length,timeoutMs:l}));let u=n.settleDelayMs??5e3;if(!s)await d("rust.semantic.worker.settle",()=>S(u),()=>({openedDocuments:r.length,settleDelayMs:u}));else{let c;await d("rust.semantic.worker.readiness",async()=>{let p=m=>d("rust.semantic.worker.settle",()=>S(m),()=>({openedDocuments:r.length,settleDelayMs:m})),f=s.initializationGeneration===void 0?await N(e.client,s.statusSnapshot,r.length,s.deadlineMs,u,Date.now,p):await C(e.client,s.initializationGeneration,r.length,s.deadlineMs,u,Date.now,p);s.initializationGeneration!==void 0&&(e.initializationReadiness=null),c=f?.health},()=>({phase:s.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:r.length,health:c}))}return r.length}async function Ne(e,n,i,t){let s=i.filter(f=>!e.openedPaths.has(f));if(s.length===0)return await Se(e),0;let r=e.initializationReadiness,o=t.readinessDeadlineMs===void 0?null:{statusSnapshot:r?null:e.client.serverStatusSnapshot(),initializationGeneration:r?.afterGeneration,deadlineMs:t.readinessDeadlineMs},l=[];for(let f of s)try{let m=F(n,f);e.client.didOpenTextDocument({uri:m,languageId:"rust",version:1,text:q(n,f,{inputKind:"indexed Rust source file"})}),e.openedPaths.add(f),l.push(m)}catch(m){if(!ee(m))throw m}let u=t.diagnosticsTimeoutMs??1e4,c=u;await d("rust.semantic.worker.diagnostics",()=>o?G(f=>(c=f,D(e.client,l,f)),u,o.deadlineMs):D(e.client,l,u),()=>({openedDocuments:l.length,timeoutMs:c}));let p=t.settleDelayMs??5e3;if(!o)await d("rust.semantic.worker.settle",()=>S(p),()=>({openedDocuments:l.length,settleDelayMs:p}));else{let f;await d("rust.semantic.worker.readiness",async()=>{let m=y=>d("rust.semantic.worker.settle",()=>S(y),()=>({openedDocuments:l.length,settleDelayMs:y})),b=o.initializationGeneration===void 0?await N(e.client,o.statusSnapshot,l.length,o.deadlineMs,p,Date.now,m):await C(e.client,o.initializationGeneration,l.length,o.deadlineMs,p,Date.now,m);o.initializationGeneration!==void 0&&(e.initializationReadiness=null),f=b?.health},()=>({phase:o.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:l.length,health:f}))}return l.length}async function Se(e){let n=e.initializationReadiness;if(!n)return;let i;await d("rust.semantic.worker.readiness",async()=>{i=(await C(e.client,n.afterGeneration,0,n.deadlineMs,0)).health,e.initializationReadiness=null},()=>({phase:"initialize",openedDocuments:0,health:i}))}function Ge(e,n){for(let i of n){let t=se(e,i.uri);if(!(!t||t===".."||t.startsWith("../")||Ie(t)))return t}return null}function Be(e,n){return n.references&&!e.referencesProvider?"rust-analyzer initialized without textDocument/references support.":n.callees&&!e.callHierarchyProvider?"rust-analyzer initialized without call hierarchy support.":n.signatures&&!e.hoverProvider?"rust-analyzer initialized without hover support.":null}function De(e,n){let i=H(e),t=U(e),s=K(e);return{available:!1,reason:n,references:i.map(r=>[r.symbolId,[]]),...e.includeCallees?{callees:t.map(r=>[r.symbolId,[]])}:{},...e.includeSignatures?{signatures:s.map(r=>[r.symbolId,null])}:{}}}async function He(){await _.shutdownAll(e=>e.client.shutdownAndReap())}async function ke(e,n,i){e.deleteIfSame(n),await n.client.shutdownAndReap({deadlineMs:i})}function Ue(e,n,i){if(!e)return;let t=$e(e,n);t.definitions+=1,i.hasReferences&&(t.definitionsWithReferences+=1),t.references+=i.references,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ke(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.references.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithReferences:t.definitionsWithReferences,references:t.references,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function $e(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithReferences:0,references:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function Je(e,n,i){if(!e)return;let t=Ye(e,n);t.definitions+=1,i.hasCallees&&(t.definitionsWithCallees+=1),t.callees+=i.callees,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ve(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.callees.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithCallees:t.definitionsWithCallees,callees:t.callees,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function Ye(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithCallees:0,callees:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function we(e){if(e===void 0||e==="")return null;let n=Number(e);return Number.isInteger(n)&&n>=0?n:null}function Ze(){let e=k.env.SCIP_RUST_SEMANTIC_PARALLEL_OPERATIONS;return e!=="0"&&e!=="false"}function g(e,n,i){ve(e,JSON.stringify(n));let t=new Int32Array(i);Atomics.store(t,0,1),Atomics.notify(t,0)}function Qe(e,n,i,t){return e&&n&&i>0&&t>0&&Ze()}export{ke as discardRustAnalyzerSession};
2
2
  //# sourceMappingURL=rust-semantic-session-worker.js.map
@@ -1,2 +1,2 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m,m as n,n as o,o as p,p as q}from"./chunk-BDUVI7TO.js";import{a}from"./chunk-ILMHV3KM.js";import"./chunk-OWOOWNJ5.js";import"./chunk-GAS2LJMP.js";import"./chunk-2OOY75BW.js";import"./chunk-JFMEXGFE.js";import"./chunk-KYSDI3GE.js";import"./chunk-7F45LJKI.js";export{q as calleesForDefinition,l as cargoManifestsForDefinitions,i as hoverToRustSignature,h as hoverWithRetry,m as openDefinitionDocuments,p as referencesWithCompletion,o as referencesWithRetry,b as runRustAnalyzerReferenceBatch,a as runWithConcurrency,j as rustAnalyzerInitializationOptions,k as rustAnalyzerSessionRoot,d as rustRequestCalleeDefinitions,c as rustRequestReferenceDefinitions,f as rustRequestSessionDefinitions,e as rustRequestSignatureDefinitions,g as signatureForDefinition,n as waitForOpenedDocuments};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m,m as n,n as o,o as p,p as q}from"./chunk-FL7NBMHP.js";import{a}from"./chunk-ILMHV3KM.js";import"./chunk-64DZ5TXR.js";import"./chunk-ZLADLUE6.js";import"./chunk-6FFVZZL4.js";import"./chunk-QZ7KQZRN.js";import"./chunk-TKD34PHN.js";import"./chunk-2HLAFUCY.js";import"./chunk-U5RIG3JP.js";import"./chunk-62BDNPMI.js";export{q as calleesForDefinition,l as cargoManifestsForDefinitions,i as hoverToRustSignature,h as hoverWithRetry,m as openDefinitionDocuments,p as referencesWithCompletion,o as referencesWithRetry,b as runRustAnalyzerReferenceBatch,a as runWithConcurrency,j as rustAnalyzerInitializationOptions,k as rustAnalyzerSessionRoot,d as rustRequestCalleeDefinitions,c as rustRequestReferenceDefinitions,f as rustRequestSessionDefinitions,e as rustRequestSignatureDefinitions,g as signatureForDefinition,n as waitForOpenedDocuments};
2
2
  //# sourceMappingURL=rust-semantic-worker.js.map
@@ -0,0 +1,6 @@
1
+ import{a as C,b as T,c as $,d as _,e as z,f as G,g as se,h as ce}from"./chunk-BOZ4EXBB.js";import"./chunk-TZCVNCAN.js";import"./chunk-BGBBVSH4.js";import"./chunk-7VPEEAAG.js";import"./chunk-S6CZA3MV.js";import"./chunk-PAVGPRHJ.js";import"./chunk-65245JCM.js";import"./chunk-NJJMVD65.js";import{a as D,c as I}from"./chunk-H73WY2RM.js";import{a as N,b as h,c as P}from"./chunk-ZHMRSZFD.js";import"./chunk-ZGTYGDMF.js";import"./chunk-WRQXLNYE.js";import"./chunk-DVFP6PZI.js";import"./chunk-QIWXRW72.js";import"./chunk-LOVIZBJ4.js";import"./chunk-QXEUDXBT.js";import"./chunk-O2C4UILI.js";import"./chunk-WXU3DGPU.js";import"./chunk-YUKYB54I.js";import"./chunk-TRBI4UKT.js";import"./chunk-WKPV2TDZ.js";import"./chunk-F4FNK44D.js";import"./chunk-ZLADLUE6.js";import"./chunk-6FFVZZL4.js";import"./chunk-KU3QRSTH.js";import"./chunk-DHEQMPLW.js";import"./chunk-4XQ4O6IM.js";import"./chunk-BZB4QPIP.js";import"./chunk-CN5EH7O3.js";import"./chunk-T3I6NHBH.js";import"./chunk-J5FJMODQ.js";import"./chunk-WOFQ5DTB.js";import"./chunk-PH52RA7D.js";import"./chunk-7Y5T6XDP.js";import"./chunk-X6RMKHJQ.js";import"./chunk-JEVRKFRL.js";import"./chunk-QOIXNWQR.js";import"./chunk-GZKFETP5.js";import"./chunk-3JIQS44J.js";import"./chunk-O4UZSPPI.js";import"./chunk-B3PYOSCX.js";import{a as k}from"./chunk-HRRFKWPZ.js";import"./chunk-YULZRALL.js";import"./chunk-HGFDYOVB.js";import"./chunk-QZ7KQZRN.js";import{r as A,w as E,x as L}from"./chunk-TKD34PHN.js";import"./chunk-2HLAFUCY.js";import"./chunk-U5RIG3JP.js";import"./chunk-62BDNPMI.js";import{execFileSync as Re}from"child_process";var w={maxFiles:1e4,maxFileBytes:1024*1024},O=128*1024*1024,ae=[{option:"includeGenerated",reason:"generated",matches:n=>/(^|\/)(__generated__|generated)(\/|$)/.test(n)},{option:"includeReferences",reason:"reference",matches:n=>/^(docs|agent_docs|\.agents|\.claude|\.codex)\/|(^|\/)(vendor|third_party|third-party)(\/|$)/.test(n)},{option:"includeTests",reason:"test",matches:n=>I(n)==="test"||/(^|\/)(fixtures|benchmarks)(\/|$)/.test(n)}];function V(n,t={}){if(!/\.[cm]?[jt]sx?$/.test(n))return"unsupported-language";if(/\.d\.[cm]?ts$/.test(n))return"declaration";if(D(n))return"managed-output";for(let e of ae)if(!t[e.option]&&e.matches(n))return e.reason}function H(n,t={}){le(t);let e=U(n);return ue("working-tree",e,t,r=>A(n,r,{maxBytes:t.maxFileBytes??w.maxFileBytes}).toString("utf8"))}function q(n,t,e={}){let r=U(n),o=r.filter(c=>!V(c,e)).sort(),s=[];(o.length!==t.eligibleFiles||o.slice(0,e.maxFiles??w.maxFiles).some(c=>!t.files.has(c)))&&s.push("Eligible source file set changed or was incomplete during analysis; rerun after edits settle."),J(r).join(`
2
+ `)!==J([...t.project.inventory]).join(`
3
+ `)&&s.push("Project configuration file set changed during analysis; rerun after edits settle.");for(let[c,i]of[...t.files,...t.project.inputs])try{A(n,c,{maxBytes:e.maxFileBytes??w.maxFileBytes}).toString("utf8")!==i&&s.push(`${c}: source changed during analysis; rerun after edits settle.`)}catch{s.push(`${c}: source unavailable during final freshness check.`)}return s}function ue(n,t,e,r){let o={},s=t.filter(p=>{let d=V(p,e);return d&&(o[d]=(o[d]??0)+1),!d}).sort(),c=new Map,i=[],u=s.slice(0,e.maxFiles??w.maxFiles);u.length<s.length&&i.push(`${s.length-u.length} eligible files omitted by max-files; increase --max-files to cover them.`);let a=0;for(let p of u)try{let d=r(p);if(a+=Buffer.byteLength(d),a>O){i.push(`Snapshot exceeds ${O} bytes; ${u.length-c.size} remaining files omitted.`);break}c.set(p,d)}catch(d){i.push(`${p}: ${d instanceof Error?d.message:String(d)}`)}let l=_(t,s,p=>{let d=r(p);if(a+=Buffer.byteLength(d),a>O)throw new Error("source and configuration snapshot exceeds total byte limit");return d});return{revision:n,files:c,fingerprint:h([...c,...l.inputs].sort(([p],[d])=>p.localeCompare(d)).map(([p,d])=>`${JSON.stringify(p)}:${h(d)}`).join(`
4
+ `)),eligibleFiles:s.length,excludedFiles:t.length-s.length,exclusions:o,project:l,problems:i}}function J(n){return n.filter(t=>/(^|\/)((ts|js)config[^/]*\.json|package\.json|\.scipquery\.json)$/.test(t)).sort()}function U(n){return L(n).filter(t=>{try{return E(n,t)}catch{return!0}})}function le(n){for(let t of["maxFiles","maxFileBytes"]){let e=n[t];if(e!==void 0&&(!Number.isSafeInteger(e)||e<1))throw new Error(`${t} must be a positive safe integer.`)}}function K(n){return n.rule==="dependency-cycle"||n.id.startsWith("architecture:group-cycle:")}function B(n,t){let e={"broken-dependency":0,architecture:1,"dependency-cycle":2,responsibility:3,duplication:4,crap:5,complexity:6};return e[n.rule]-e[t.rule]||t.score-n.score||n.id.localeCompare(t.id)}import{ts as g}from"@ts-morph/common";var de=new Set([g.SyntaxKind.ImportSpecifier,g.SyntaxKind.ImportClause,g.SyntaxKind.NamespaceImport]);function W(n,t){let{sourceFile:e,checker:r}=n,o=fe(e),{importedBindings:s,consumers:c}=pe(e,r,t),i=ye(e,r);return{functions:o.flatMap(a=>{let l=n.functions.find(S=>S.startOffset===a.getStart(e));if(!l)return[];let p=new Set,d=new Set,b=S=>{if(g.isIdentifier(S)){let x=r.getSymbolAtLocation(S),R=x&&s.get(x);R&&d.add(R);for(let F of x?.declarations??[])F.getSourceFile()!==e||F.pos>=a.pos&&F.end<=a.end||de.has(F.kind)||p.add(F.getStart(e))}g.forEachChild(S,b)};b(a);let y=me(a),f=y&&r.getSymbolAtLocation(y),m=(g.isVariableDeclaration(a.parent)?a.parent:a).getStart(e);return[{fn:l,declaration:m,exports:f?i.get(f)??[]:[],bindings:[...p].sort((S,x)=>S-x),dependencies:[...d].sort()}]}),consumers:c}}function pe(n,t,e){let r=new Map,o=[];for(let s of n.statements.filter(g.isImportDeclaration)){if(!g.isStringLiteralLike(s.moduleSpecifier))continue;let c=s.moduleSpecifier.text,i=n.getLineAndCharacterOfPosition(s.moduleSpecifier.getStart(n)).line+1,u=e.find(a=>a.specifier===c&&a.line===i&&a.syntax==="import"&&a.kind==="value");if(!(!u||u.role==="test"))for(let a of ge(s)){let l=t.getSymbolAtLocation(a.local);l&&r.set(l,u.target??`specifier:${u.specifier}`),u.target&&u.resolution==="internal"&&o.push({file:n.fileName,line:u.line,target:u.target,name:a.imported})}}return{importedBindings:r,consumers:o}}function fe(n){return n.statements.flatMap(t=>g.isFunctionDeclaration(t)&&t.body?[t]:g.isVariableStatement(t)?t.declarationList.declarations.flatMap(e=>e.initializer&&(g.isArrowFunction(e.initializer)||g.isFunctionExpression(e.initializer))?[e.initializer]:[]):[])}function me(n){return g.isVariableDeclaration(n.parent)?n.parent.name:n.name}function ge(n){let t=n.importClause;if(!t||t.isTypeOnly)return[];let e=t.name?[{local:t.name,imported:"default"}]:[],r=t.namedBindings;if(!r)return e;if(g.isNamespaceImport(r))return e.push({local:r.name,imported:"*"}),e;for(let o of r.elements)o.isTypeOnly||e.push({local:o.name,imported:(o.propertyName??o.name).text});return e}function ye(n,t){let e=t.getSymbolAtLocation(n),r=new Map;if(!e)return r;for(let o of t.getExportsOfModule(e)){let s=o.flags&g.SymbolFlags.Alias?t.getAliasedSymbol(o):o;r.set(s,[...r.get(s)??[],o.name])}return r}import be from"path";function Y(n){return{configured:n.configured,boundaries:n.boundaries,coverage:n.coverage,policyCoverage:n.policyCoverage,dependencyRoles:n.dependencyRoles,cycles:n.cycles.map(t=>({boundaries:t.boundaries,origin:t.origin,fileCycleMembers:t.fileCycleMembers,violatesPolicy:t.violatesPolicy}))}}function M(n,t){return I(n)==="test"||/(^|\/)(fixtures|benchmarks)(\/|$)/.test(n)||(t?.testPaths??[]).some(e=>T(e,n))}function j(n,t){let e=new Map(n.map(r=>[r,new Set]));for(let r of t)r.resolution==="internal"&&r.target&&e.has(r.target)&&e.get(r.file)?.add(r.target);return e}function v(n,t){return n.filter(e=>!M(e.file,t)&&(!e.target||!M(e.target,t)))}function he(n){return n.filter(t=>t.kind==="value"&&(t.syntax==="import"||t.syntax==="reexport"))}function X(n){let t={internal:0,external:0,builtin:0,excluded:0,missing:0,ambiguous:0,dynamic:0};for(let e of n)t[e.resolution]++;return{resolutions:t,typeOnly:n.filter(e=>e.kind==="type").length,test:n.filter(e=>e.role==="test").length,deferredOrCommonJs:n.filter(e=>e.syntax==="dynamic-import"||e.syntax==="require").length,unresolved:n.filter(e=>e.resolution==="missing"||e.resolution==="ambiguous"||e.resolution==="dynamic"),excluded:n.filter(e=>e.resolution==="excluded")}}function Q(n,t){let e=he(t),r=j(n,e);return C(r).components.filter(o=>o.length>1||r.get(o[0])?.has(o[0])).map(o=>{let s=new Set(o),c=e.filter(i=>i.resolution==="internal"&&s.has(i.file)&&i.target&&s.has(i.target));return{id:`dependency-cycle:${h([...o].sort().join("\0"))}`,rule:"dependency-cycle",evidence:"derived",summary:`${o.length} production files form a circular component of static value imports.`,score:o.length,sites:c.map(i=>({file:i.file,line:i.line})),details:c.map(i=>`${i.file}:${i.line} \u2192 ${i.target} (${i.syntax}, ${i.kind})`)}})}function Z(n,t,e){let r=v(t,e),o=G(j(n,r),n,e),s=new Map(n.map(i=>[i,$(e,i)])),c=o.forbiddenEdges.map(i=>{let u=r.filter(a=>a.resolution==="internal"&&a.target&&s.get(a.file)===i.from&&s.get(a.target)===i.to);return{id:`architecture:${i.from}:${i.to}`,rule:"architecture",evidence:"derived",summary:`${i.from} \u2192 ${i.to}: ${i.fileEdgeCount} production file dependencies violate the declared rule.`,sites:u.flatMap(a=>[{file:a.file,line:a.line},{file:a.target,line:1}]),score:i.fileEdgeCount,details:u.map(a=>`${a.file}:${a.line} \u2192 ${a.target} (${a.kind}, ${a.syntax})`)}});for(let i of o.cycles.filter(u=>u.violatesPolicy)){let u=r.filter(a=>a.resolution==="internal"&&a.target&&i.boundaries.includes(s.get(a.file)??"")&&i.boundaries.includes(s.get(a.target)??""));c.push({id:`architecture:group-cycle:${h(i.boundaries.join("\0"))}`,rule:"architecture",evidence:"derived",score:i.boundaries.length,summary:`${i.boundaries.length} declared groups violate requireAcyclic (${i.origin}); group identities are retained in architecture.cycles.`,sites:u.map(a=>({file:a.file,line:a.line})),details:[o.dependencyRoles.cycleMeaning,...u.map(a=>`${a.file}:${a.line} \u2192 ${a.target} (${a.kind}, ${a.syntax})`)]})}for(let i of o.boundaryLimits)c.push({id:`architecture:limit:${i.boundary}:${i.kind}`,rule:"architecture",evidence:"derived",score:i.observed,summary:`${i.boundary}: ${i.observed} ${i.kind} exceeds the declared limit ${i.limit}.`,sites:n.filter(u=>s.get(u)===i.boundary).map(u=>({file:u,line:1})),details:["A configured bound is a project rule, not proof that a group has multiple responsibilities."]});if(o.policyCoverage.requiresCompleteCoverage){for(let i of o.coverage.unmappedFiles)c.push({id:`architecture:unmapped:${i}`,rule:"architecture",evidence:"derived",score:1,summary:`${i} has no declared boundary and violates requireCompleteCoverage.`,sites:[{file:i,line:1}],details:[]});for(let i of o.coverage.ambiguousFiles)c.push({id:`architecture:ambiguous:${i.file}`,rule:"architecture",evidence:"derived",score:i.boundaries.length,summary:`${i.file} matches multiple declared boundaries and violates requireCompleteCoverage.`,sites:[{file:i.file,line:1}],details:i.boundaries})}return{rules:o,findings:c}}function ee(n){return n.filter(t=>t.resolution==="missing"||t.resolution==="ambiguous").map(t=>({id:`broken-dependency:${t.file}:${t.specifier}`,rule:"broken-dependency",evidence:"candidate",summary:`${JSON.stringify(t.specifier)} ${t.resolution==="ambiguous"?"has conflicting project resolutions":"does not resolve in the captured internal source"}.`,sites:[{file:t.file,line:t.line}],score:1,details:[`Configuration: ${t.configs.join(", ")||"default compiler resolution"}.`,"Check the import, project configuration, generated files and custom loaders before treating this as a broken build."]}))}function ne(n,t,e,r){let{groups:o,owners:s}=Se(n,r),{outgoing:c,incoming:i}=ve(t,s,r),u=[...e].filter(l=>l.status!=="resolved"&&!K(l)).sort(B),a=new Map(u.map((l,p)=>[l.id,p]));return xe(u,o,s),[...o.values()].map(l=>({...l,files:l.files.sort(),consumers:[...i.get(l.id)??[]].sort(),dependencies:[...c.get(l.id)??[]].sort()})).sort((l,p)=>(a.get(l.primaryFindingIds[0])??1/0)-(a.get(p.primaryFindingIds[0])??1/0)||l.id.localeCompare(p.id))}function Se(n,t){let e=new Map,r=new Map;for(let o of n){let s=$(t,o),c=s?`boundary:${s}`:`directory:${be.posix.dirname(o)}`;r.set(o,c),e.has(c)||e.set(c,{id:c,basis:s?"declared-boundary":"directory",files:[],consumers:[],dependencies:[],findingIds:[],primaryFindingIds:[],interpretation:"Grouping identifies declared membership or a shared directory. Review the observed contracts before changing ownership."}),e.get(c).files.push(o)}return{groups:e,owners:r}}function ve(n,t,e){let r=new Map,o=new Map;for(let s of v(n,e)){if(s.resolution!=="internal"||!s.target)continue;let c=t.get(s.file),i=t.get(s.target);if(!c||!i||c===i)continue;let u=r.get(c)??new Set;u.add(s.target),r.set(c,u);let a=o.get(i)??new Set;a.add(s.file),o.set(i,a)}return{outgoing:r,incoming:o}}function xe(n,t,e){for(let r of n){let o=r.sites.map(s=>e.get(s.file)).find(s=>s!==void 0);o&&t.get(o).primaryFindingIds.push(r.id);for(let s of new Set(r.sites.map(c=>e.get(c.file)).filter(c=>!!c))){let c=t.get(s);c.findingIds.length||(c.highestPriority=r.rule),c.findingIds.push(r.id)}}}function te(n){let t=n.flatMap(r=>r.consumers),e=[];for(let r of n){if(r.functions.length<4)continue;let o=r.functions[0].fn.file,s=Fe(r.functions).map(i=>{let u=i.filter(l=>l.exports.length&&l.fn.tokenCount>=60),a=new Set(u.flatMap(l=>l.exports));return{functions:u,dependencies:[...new Set(i.flatMap(l=>l.dependencies))],consumers:t.filter(l=>l.target===o&&(a.has(l.name)||l.name==="*"))}}).filter(i=>i.functions.length>=2&&i.dependencies.length&&i.consumers.length),c=s.filter(i=>s.every(u=>i===u||!u.consumers.some(a=>i.consumers.some(l=>l.file===a.file))));c.length<2||e.push({id:`responsibility:${o}`,rule:"responsibility",evidence:"candidate",score:c.length,summary:`${o} contains ${c.length} substantial exported function groups with separate observed dependencies and named consumers.`,sites:c.flatMap(i=>i.functions.map(({fn:u})=>({file:o,line:u.startLine,name:u.name}))),details:c.map((i,u)=>`Group ${u+1}: ${i.functions.map(a=>a.fn.name).join(", ")}; dependencies: ${i.dependencies.join(", ")}; named importers: ${i.consumers.map(a=>`${a.file}:${a.line} (${a.name})`).join(", ")}.`).concat(["No shared same-file binding or imported module connects these groups in the covered top-level functions. Nested closures contribute their binding references to their containing function.","A shared public contract can justify keeping these groups together. Classes, indirect re-exports, dynamic consumers, external users and runtime resource identity are not established by this provider. Read those contracts before proposing a split."])})}return e}function Fe(n){let t=new Map(n.map((r,o)=>[String(o),new Set])),e=new Map;return n.forEach((r,o)=>{let s=String(o);for(let c of[...[r.declaration,...r.bindings].map(i=>`binding:${i}`),...r.dependencies.map(i=>`import:${i}`)]){let i=e.get(c);i!==void 0?(t.get(s).add(i),t.get(i).add(s)):e.set(c,s)}}),C(t).components.map(r=>r.map(o=>n[Number(o)]))}function re(n,t,e,r){let o=d=>({status:"unavailable",reason:d});if(r.problem)return o(r.problem);let s=r.files[n.file];if(!s||s.sourceHash!==h(e))return o("Coverage missing or source hash does not match current bytes.");let{statementMap:c,s:i}=s.coverage??{};if(!k(c)||!k(i))return o("Malformed statement coverage.");let u=Me(c,i,e);if(!u)return o("Malformed statement coverage locations or counts.");let a=Ie(n,t,u);if(a.size===0)return o("No measured executable lines in this function.");let l=[...a.values()].filter(Boolean).length,p=l/a.size;return{status:"available",basis:"istanbul-statement-start-lines",coveredLines:l,measuredLines:a.size,fraction:p,crap:Number((n.cyclomatic**2*(1-p)**3+n.cyclomatic).toFixed(2))}}function Me(n,t,e){let r=[0];for(let s=0;s<e.length;s++)e[s]===`
5
+ `&&r.push(s+1);let o=[];for(let[s,c]of Object.entries(n)){let i=c?.start?.line,u=c?.start?.column,a=t[s];if(!Ce(i,u,a,r,e.length))return;o.push({line:i,offset:r[i-1]+u,count:a})}return o}function Ie(n,t,e){let r=t.filter(s=>s!==n&&s.startOffset>n.startOffset&&s.endOffset<=n.endOffset),o=new Map;for(let{line:s,offset:c,count:i}of e)c<n.startOffset||c>=n.endOffset||r.some(u=>c>=u.startOffset&&c<u.endOffset)||o.set(s,(o.get(s)??!1)||i>0);return o}function Ce(n,t,e,r,o){if(!Number.isInteger(n)||!Number.isInteger(t)||!Number.isInteger(e)||n<1||n>r.length||t<0||e<0)return!1;let s=r[n-1]+t,c=r[n]??o;return s<c}var pn=[`TS/JS implemented functions; metric rules ${N}. Cognitive counts structural nesting and logical sequences; recursion and interprocedural behavior are not measured.`,"Duplication compares whole function body tokens (at least 60 tokens), retaining literals and property names. Renamed local bindings are candidates; similarity does not prove interchangeable behavior or justify deletion.","Dependencies use compiler resolution over captured source and project configuration, including aliases, repository package exports, literal dynamic imports and unshadowed CommonJS calls. External packages, excluded targets and unresolved imports are distinguished. Production file cycles use static value imports; type/test/deferred relationships remain separate. Runtime handoffs and custom loaders are not inferred.","Ownership and mixed responsibilities require evidence about callers, state and business rules; this scan does not infer a correct owner or an architectural grade."];function ie(n,t={files:{},problem:"No source-matched coverage supplied."},e){e??=n.project.architecture;let r=[],o=[],s=[],c=[],i=[...n.problems];for(let[d,b]of n.files){let y=P(d,b);if(i.push(...y.errors),y.errors.length>0)continue;o.push(...y.exports),r.push(...y.functions.map(m=>({...m,coverage:re(m,y.functions,b,t)})));let f=z(y.sourceFile,n.files,n.project,y.checker);for(let m of f)m.role=M(d,e)?"test":"production";s.push(...f),M(d,e)||c.push(W(y,f))}let u=[...n.files.keys()],a=j(u,s),l=Z(u,s,e),p=[...$e(r),...we(r),...Q(u,v(s,e)),...l.findings,...ee(s),...te(c)];return{functions:r,exports:o,findings:p.sort(B),imports:s,graph:a,problems:i,architecture:l.rules}}function $e(n){let t=[];for(let e of n){let r={file:e.file,line:e.startLine,name:e.name};(e.cyclomatic>10||e.cognitive>15)&&t.push({id:`complexity:${e.file}:${e.name}`,rule:"complexity",evidence:"derived",summary:`${e.name}: cyclomatic ${e.cyclomatic}, cognitive ${e.cognitive}.`,sites:[r],score:Math.max(e.cyclomatic/10,e.cognitive/15),details:["Review branching and nesting while preserving decisions, effects, and error handling.",...e.contributions.filter(o=>o.cognitive>1).map(o=>`${e.file}:${o.line}:${o.column} ${o.kind}: +${o.cognitive} cognitive`)]}),e.coverage.status==="available"&&e.coverage.crap>=30&&t.push({id:`crap:${e.file}:${e.name}`,rule:"crap",evidence:"derived",score:e.coverage.crap,sites:[r],summary:`${e.name}: CRAP ${e.coverage.crap}, measured line coverage ${Math.round(e.coverage.fraction*100)}%.`,details:["CRAP = cyclomatic\xB2 \xD7 (1 \u2212 measured coverage)\xB3 + cyclomatic. Improve tests and simplify behavior where justified."]})}return t}function we(n){let t=new Map;for(let e of n){if(e.tokenCount<60)continue;let r=e.renamedBodyHash,o=t.get(r)??[];o.push(e),t.set(r,o)}return[...t.values()].filter(e=>e.length>1).map(e=>{let r=new Set(e.map(s=>s.bodyHash)).size===1,o=e.map(s=>({file:s.file,line:s.startLine,name:s.name}));return{id:`duplication:${e[0].renamedBodyHash}`,rule:"duplication",evidence:"candidate",summary:`${e.length} functions share ${r?"identical body tokens":"body tokens after local binding renaming"}.`,sites:o,score:e.length,details:[`${e[0].tokenCount} tokens per body; comments and whitespace excluded; literals retained.`,"Read both contracts and callers. If these implementations own the same rule, reuse one owner; otherwise retain the separate responsibilities."]}})}function Be(n,t,e={}){let r=H(n,e),o=ie(r),s=ne([...r.files.keys()],o.imports,o.findings,r.project.architecture),c=je(s,t),i=new Set(c.flatMap(f=>f.files)),u=X(o.imports),a=[...o.problems,...r.project.problems,...q(n,r,e)];t&&!c.length&&a.push(`Selector ${JSON.stringify(t)} matches no captured module; use system --source to inspect group IDs and exclusions.`),(u.resolutions.missing||u.resolutions.ambiguous)&&a.push("Internal imports are missing or ambiguous; inspect coverage.dependencies.unresolved.");let l=oe(o.exports),p=o.imports.filter(f=>i.has(f.file)||f.target&&i.has(f.target)),d=new Map(p.map((f,m)=>[f,m])),b=oe(p),y=ke(p);return{mode:"source-system",current:r.fingerprint,selector:t,totalModules:s.length,imports:p,modules:c.map(f=>({...f,exports:f.files.flatMap(m=>l.get(m)??[]),importIds:f.files.flatMap(m=>b.get(m)??[]).map(m=>d.get(m)),incomingImportIds:f.files.flatMap(m=>y.get(m)??[]).filter(m=>!f.files.includes(m.file)).map(m=>d.get(m))})),edges:Ae(s,v(p,r.project.architecture),d).filter(f=>c.some(m=>m.id===f.from||m.id===f.to)),findings:o.findings.filter(f=>f.sites.some(m=>i.has(m.file))),architecture:Y(o.architecture),coverage:{status:a.length?"incomplete":"accounted",capturedFiles:r.files.size,eligibleFiles:r.eligibleFiles,excludedFiles:r.excludedFiles,exclusions:r.exclusions,dependencies:u,problems:a,limits:["Current TS/JS source and captured project configuration; no index or executed behavior is implied. Parse, resource and configuration failures are reported in problems.","Import IDs index the imports table in this report; each observation is stored once. IDs are not portable between reports.","Groups include files without findings. Unambiguous configured boundaries take precedence over provisional directories; membership does not establish business responsibility. A path selects whole groups containing matching files.","Module edges and dependency/consumer summaries are observed internal production imports, including type, dynamic and CommonJS relationships; their syntax and roles remain explicit. They are not runtime execution paths. Only static value imports participate in production file-cycle findings.","Export declarations are parsed source locations, not a complete resolved public API. Wildcard re-exports are not expanded; CommonJS exports, class member interfaces, external consumers, runtime registration and invocation coverage are not established. Use indexed surface/evidence and exact source when those facts matter.","Nonliteral dynamic imports, custom loaders, runtime handoffs and shared external resources are not resolved. Coverage can be accounted for while these relationships remain unknown.","Tests, generated/reference copies, declarations, unsupported languages and managed output are excluded by default; exclusion counts and opt-in source roles are reported. No architecture grade or module depth score is computed."]}}}function je(n,t){if(!t||t===".")return n;let e=n.find(o=>o.id===t);if(e)return[e];let r=t.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/$/,"");return n.filter(o=>o.files.some(s=>s===r||s.startsWith(r+"/")))}function oe(n){let t=new Map;for(let e of n){let r=t.get(e.file)??[];r.push(e),t.set(e.file,r)}return t}function ke(n){let t=new Map;for(let e of n){if(e.resolution!=="internal"||!e.target)continue;let r=t.get(e.target)??[];r.push(e),t.set(e.target,r)}return t}function Ae(n,t,e){let r=new Map(n.flatMap(s=>s.files.map(c=>[c,s.id]))),o=new Map;for(let s of t){if(s.resolution!=="internal"||!s.target)continue;let c=r.get(s.file),i=r.get(s.target);if(!c||!i||c===i)continue;let u=JSON.stringify([c,i]),a=o.get(u)??{from:c,to:i,importIds:[]};a.importIds.push(e.get(s)),o.set(u,a)}return[...o.values()].sort((s,c)=>s.from.localeCompare(c.from)||s.to.localeCompare(c.to))}export{ce as dependenceSlice,se as entryPoints,Be as sourceSystemReport};
6
+ //# sourceMappingURL=service-queries-2WAJI7R6.js.map