scip-query 0.19.8 → 0.20.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 (366) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +158 -48
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/chunk-26QA6FAI.js +8 -0
  5. package/dist/{chunk-KJ2IIBZN.js → chunk-2HPVVXM5.js} +2 -2
  6. package/dist/chunk-2KAZEZ6M.js +2 -0
  7. package/dist/chunk-32LVLCLN.js +40 -0
  8. package/dist/{chunk-24GTWJ3N.js → chunk-3CLX5EOX.js} +2 -2
  9. package/dist/{chunk-QGGLL3UH.js → chunk-3G66UZBH.js} +2 -2
  10. package/dist/{chunk-AA4UWRNL.js → chunk-3ORVDL3H.js} +2 -2
  11. package/dist/chunk-4MAK2HOY.js +6 -0
  12. package/dist/{chunk-QIQ63BHW.js → chunk-4TURLRL5.js} +2 -2
  13. package/dist/chunk-4UQVNCQE.js +2 -0
  14. package/dist/chunk-55Q3WLZX.js +2 -0
  15. package/dist/{chunk-CTF2GDEX.js → chunk-5E4WNAVD.js} +2 -2
  16. package/dist/{chunk-ZCEJ63SP.js → chunk-5I5G2QOX.js} +2 -2
  17. package/dist/chunk-6LDJQXAH.js +2 -0
  18. package/dist/{chunk-3EDFLQ6A.js → chunk-6O5TICIZ.js} +2 -2
  19. package/dist/{chunk-ACAM6O5R.js → chunk-6SHPK5ZE.js} +2 -2
  20. package/dist/chunk-7BAVHKMJ.js +49 -0
  21. package/dist/chunk-7O5IKBTZ.js +16 -0
  22. package/dist/{chunk-WJL2L6MV.js → chunk-7PIO7NKH.js} +2 -2
  23. package/dist/chunk-7S5E7KWT.js +2 -0
  24. package/dist/{chunk-YLFORA5G.js → chunk-7SQQWSY3.js} +2 -2
  25. package/dist/chunk-7WPLAODU.js +5 -0
  26. package/dist/chunk-A73XVBCR.js +20 -0
  27. package/dist/chunk-AFHORGLH.js +42 -0
  28. package/dist/chunk-AIE7TFJW.js +9 -0
  29. package/dist/{chunk-TWMJ3Y3G.js → chunk-AZJQQKDD.js} +2 -2
  30. package/dist/{chunk-BDOIKGDI.js → chunk-B2PX5I6M.js} +2 -2
  31. package/dist/{chunk-DQBCO2UY.js → chunk-B7PBSLZN.js} +2 -2
  32. package/dist/chunk-BBW6JFHN.js +2 -0
  33. package/dist/{chunk-YTVWB7YJ.js → chunk-BDCC2NPY.js} +2 -2
  34. package/dist/{chunk-O23I56NA.js → chunk-BNXCIFVY.js} +2 -2
  35. package/dist/{chunk-MLFZP76A.js → chunk-BPAPWKP6.js} +2 -2
  36. package/dist/chunk-BS2NMXQZ.js +4 -0
  37. package/dist/chunk-C3KV2II6.js +2 -0
  38. package/dist/chunk-C43RDDP4.js +20 -0
  39. package/dist/{chunk-K2WO7XY7.js → chunk-CJST5ETY.js} +2 -2
  40. package/dist/chunk-DAFAHMNB.js +42 -0
  41. package/dist/{chunk-KKME5ZAI.js → chunk-DQGFVPUV.js} +2 -2
  42. package/dist/chunk-DQLPXMH6.js +8 -0
  43. package/dist/chunk-EKZTZXHZ.js +117 -0
  44. package/dist/{chunk-FJ5UDTQF.js → chunk-EN3O7VJA.js} +2 -2
  45. package/dist/{chunk-HZYDQPNY.js → chunk-EW2NTSFA.js} +2 -2
  46. package/dist/chunk-F3Z4OUDS.js +8 -0
  47. package/dist/chunk-FJH2NW7J.js +66 -0
  48. package/dist/{chunk-MSBDMFER.js → chunk-FKSELJQF.js} +2 -2
  49. package/dist/chunk-FTFP6O3L.js +11 -0
  50. package/dist/chunk-FYLK2DEJ.js +2 -0
  51. package/dist/{chunk-WUW7YUAH.js → chunk-GH74ASD6.js} +2 -2
  52. package/dist/{chunk-464PLI5O.js → chunk-GMXWZP2B.js} +2 -2
  53. package/dist/chunk-GOUBFH5O.js +3 -0
  54. package/dist/{chunk-FIJCV235.js → chunk-HLF2TX6R.js} +2 -2
  55. package/dist/{chunk-WWKWUPSU.js → chunk-HX4GQPZP.js} +2 -2
  56. package/dist/chunk-HX7M4BDI.js +30 -0
  57. package/dist/chunk-HZ72SESS.js +128 -0
  58. package/dist/{chunk-SERUIGV5.js → chunk-IB2N4FIY.js} +2 -2
  59. package/dist/chunk-ILMHV3KM.js +2 -0
  60. package/dist/chunk-IZYYAFN5.js +2 -0
  61. package/dist/{chunk-GNC4JVAN.js → chunk-JAYYFEQY.js} +2 -2
  62. package/dist/{chunk-QJIVBYEK.js → chunk-JDOEX4E6.js} +2 -2
  63. package/dist/chunk-JFGGXWQF.js +947 -0
  64. package/dist/chunk-JN4NMBEX.js +8 -0
  65. package/dist/{chunk-6M7RONVB.js → chunk-JVYA47YU.js} +2 -2
  66. package/dist/{chunk-7KYNAMMH.js → chunk-JW56N3KI.js} +2 -2
  67. package/dist/{chunk-OUBAF226.js → chunk-JZ2OXNWB.js} +2 -2
  68. package/dist/chunk-KMKTIO2G.js +8 -0
  69. package/dist/chunk-L5GJNV2T.js +8 -0
  70. package/dist/{chunk-MNSTUIDD.js → chunk-L7AW2QB5.js} +2 -2
  71. package/dist/chunk-L7JDSCDF.js +4 -0
  72. package/dist/chunk-LU47HG23.js +14 -0
  73. package/dist/chunk-LVY7NPF7.js +2 -0
  74. package/dist/chunk-LY4WC4AD.js +74 -0
  75. package/dist/{chunk-7FT5Y65S.js → chunk-MKCDWWGV.js} +2 -2
  76. package/dist/chunk-MNE7YG56.js +2 -0
  77. package/dist/{chunk-7QHY3H7P.js → chunk-MRXBEXSY.js} +2 -2
  78. package/dist/chunk-MV7OWDUX.js +2 -0
  79. package/dist/{chunk-ZJ5CBXK3.js → chunk-N5W4YZMK.js} +2 -2
  80. package/dist/chunk-NGEXCJJW.js +11 -0
  81. package/dist/{chunk-7SWJEWJF.js → chunk-NIW6JDC5.js} +2 -2
  82. package/dist/{chunk-O3O4XXO6.js → chunk-O64IZ6UX.js} +2 -2
  83. package/dist/{chunk-3ZSJ3PWF.js → chunk-PBUQFCNB.js} +2 -2
  84. package/dist/{chunk-7RAG65VK.js → chunk-POAVPHH7.js} +2 -2
  85. package/dist/{chunk-A3QXWFBK.js → chunk-PQCI4SQX.js} +2 -2
  86. package/dist/{chunk-4BV4QAZJ.js → chunk-PXY7F6Y4.js} +2 -2
  87. package/dist/chunk-RDO52JGY.js +2 -0
  88. package/dist/chunk-RJT3TUUZ.js +2 -0
  89. package/dist/{chunk-S4S2WOIX.js → chunk-RUJURYSV.js} +2 -2
  90. package/dist/{chunk-JAY7YWS3.js → chunk-RVLDN63O.js} +2 -2
  91. package/dist/chunk-RXOXSKY3.js +2 -0
  92. package/dist/chunk-S7OYBOCK.js +2 -0
  93. package/dist/chunk-SMNXQT5Z.js +3 -0
  94. package/dist/{chunk-NE3TZUCI.js → chunk-SRAFT254.js} +2 -2
  95. package/dist/{chunk-ELLMY7XJ.js → chunk-SXP2MBJH.js} +2 -2
  96. package/dist/chunk-T7YQSHPQ.js +3 -0
  97. package/dist/{chunk-WY45BHKQ.js → chunk-TFRAYKN6.js} +2 -2
  98. package/dist/{chunk-2SNGN6U4.js → chunk-UJCOIXDY.js} +2 -2
  99. package/dist/{chunk-MZZBAITE.js → chunk-UJPRPGCO.js} +2 -2
  100. package/dist/chunk-W4ETQAXM.js +2 -0
  101. package/dist/chunk-WCCFZ7V7.js +113 -0
  102. package/dist/chunk-WUPW3UN3.js +3 -0
  103. package/dist/{chunk-7LSVMFX7.js → chunk-WXZLAAWK.js} +2 -2
  104. package/dist/{chunk-5ML2BNRH.js → chunk-X54AGLVX.js} +2 -2
  105. package/dist/chunk-XKWKXZKW.js +20 -0
  106. package/dist/{chunk-5YLUDDAF.js → chunk-XSRF6Q77.js} +2 -2
  107. package/dist/chunk-Y2MVPNKY.js +5 -0
  108. package/dist/{chunk-JHF3E4YM.js → chunk-YKUU5AIC.js} +2 -2
  109. package/dist/{chunk-E3HYEQO7.js → chunk-YLCJLTPL.js} +2 -2
  110. package/dist/{chunk-7VCOXZH3.js → chunk-YTQVETEO.js} +2 -2
  111. package/dist/chunk-Z4N3MZYA.js +38 -0
  112. package/dist/chunk-ZHXX42OH.js +18 -0
  113. package/dist/chunk-ZJOOT3BG.js +2 -0
  114. package/dist/{chunk-P3UO3EH3.js → chunk-ZK26BAQL.js} +2 -2
  115. package/dist/{chunk-33KUO7CG.js → chunk-ZTETIQ35.js} +2 -2
  116. package/dist/cli.js +3 -8
  117. package/dist/command-descriptors-DSS46KXI.js +642 -0
  118. package/dist/{config-types-B6MEoRNy.d.ts → config-types-jVM3D7MA.d.ts} +68 -2
  119. package/dist/{db-DYLKr9Wn.d.ts → db-B5PM5yNk.d.ts} +20 -2
  120. package/dist/{diff-gate-types-C9BoYwYD.d.ts → diff-gate-types-B0QYpDv1.d.ts} +2 -1
  121. package/dist/direct-navigation-6YHV6IB5.js +3 -0
  122. package/dist/{health-DgxIDXJC.d.ts → health-Do5TKSJI.d.ts} +1 -1
  123. package/dist/index.d.ts +3 -3
  124. package/dist/index.js +1 -1
  125. package/dist/postinstall.js +1 -1
  126. package/dist/queries/affected.d.ts +2 -2
  127. package/dist/queries/affected.js +1 -1
  128. package/dist/queries/architecture.d.ts +2 -2
  129. package/dist/queries/architecture.js +1 -1
  130. package/dist/queries/bottlenecks.d.ts +2 -2
  131. package/dist/queries/bottlenecks.js +1 -1
  132. package/dist/queries/by-kind.d.ts +2 -2
  133. package/dist/queries/by-kind.js +1 -1
  134. package/dist/queries/call-graph.d.ts +2 -2
  135. package/dist/queries/call-graph.js +1 -1
  136. package/dist/queries/change-surface.d.ts +22 -3
  137. package/dist/queries/change-surface.js +1 -1
  138. package/dist/queries/cleanup-plan.d.ts +2 -2
  139. package/dist/queries/cleanup-plan.js +1 -1
  140. package/dist/queries/co-change.d.ts +2 -2
  141. package/dist/queries/co-change.js +1 -1
  142. package/dist/queries/code.d.ts +2 -2
  143. package/dist/queries/code.js +1 -1
  144. package/dist/queries/complexity-hotspots.d.ts +3 -3
  145. package/dist/queries/complexity-hotspots.js +1 -1
  146. package/dist/queries/complexity.d.ts +3 -3
  147. package/dist/queries/complexity.js +1 -1
  148. package/dist/queries/convergence.d.ts +2 -2
  149. package/dist/queries/convergence.js +1 -1
  150. package/dist/queries/coupling.d.ts +2 -2
  151. package/dist/queries/coupling.js +1 -1
  152. package/dist/queries/cycles.d.ts +2 -2
  153. package/dist/queries/cycles.js +1 -1
  154. package/dist/queries/dataflow.d.ts +2 -2
  155. package/dist/queries/dataflow.js +1 -1
  156. package/dist/queries/dead.d.ts +2 -2
  157. package/dist/queries/dead.js +1 -1
  158. package/dist/queries/decorative-checkers.d.ts +2 -2
  159. package/dist/queries/decorative-checkers.js +1 -1
  160. package/dist/queries/deep-chains.d.ts +2 -2
  161. package/dist/queries/deep-chains.js +1 -1
  162. package/dist/queries/deps.d.ts +2 -2
  163. package/dist/queries/deps.js +1 -1
  164. package/dist/queries/diff-gate.d.ts +40 -7
  165. package/dist/queries/diff-gate.js +1 -1
  166. package/dist/queries/diff-impact.d.ts +84 -6
  167. package/dist/queries/diff-impact.js +1 -1
  168. package/dist/queries/doc-drift.d.ts +3 -3
  169. package/dist/queries/doc-drift.js +1 -1
  170. package/dist/queries/drift.d.ts +2 -2
  171. package/dist/queries/drift.js +1 -1
  172. package/dist/queries/duplicate-bodies.d.ts +3 -3
  173. package/dist/queries/duplicate-bodies.js +1 -1
  174. package/dist/queries/extract-candidates.d.ts +2 -2
  175. package/dist/queries/extract-candidates.js +1 -1
  176. package/dist/queries/fan.d.ts +2 -2
  177. package/dist/queries/fan.js +1 -1
  178. package/dist/queries/files.d.ts +12 -3
  179. package/dist/queries/files.js +1 -1
  180. package/dist/queries/health.d.ts +3 -3
  181. package/dist/queries/health.js +1 -1
  182. package/dist/queries/hierarchy.d.ts +2 -2
  183. package/dist/queries/hierarchy.js +1 -1
  184. package/dist/queries/hotspots.d.ts +2 -2
  185. package/dist/queries/hotspots.js +1 -1
  186. package/dist/queries/imports.d.ts +2 -2
  187. package/dist/queries/imports.js +1 -1
  188. package/dist/queries/incomplete-migration.d.ts +8 -6
  189. package/dist/queries/incomplete-migration.js +1 -1
  190. package/dist/queries/index.d.ts +141 -10
  191. package/dist/queries/index.js +1 -1
  192. package/dist/queries/isolated.d.ts +2 -2
  193. package/dist/queries/isolated.js +1 -1
  194. package/dist/queries/locality-candidates.d.ts +2 -2
  195. package/dist/queries/locality-candidates.js +1 -1
  196. package/dist/queries/members.d.ts +2 -2
  197. package/dist/queries/members.js +1 -1
  198. package/dist/queries/methods.d.ts +34 -3
  199. package/dist/queries/methods.js +1 -1
  200. package/dist/queries/not-implemented.d.ts +2 -2
  201. package/dist/queries/not-implemented.js +1 -1
  202. package/dist/queries/outline.d.ts +2 -2
  203. package/dist/queries/outline.js +1 -1
  204. package/dist/queries/passthrough-candidates.d.ts +3 -3
  205. package/dist/queries/passthrough-candidates.js +1 -1
  206. package/dist/queries/plan-context.d.ts +3 -3
  207. package/dist/queries/plan-context.js +1 -1
  208. package/dist/queries/react-component-duplicates.d.ts +2 -2
  209. package/dist/queries/react-component-duplicates.js +1 -1
  210. package/dist/queries/react-hook-candidates.d.ts +2 -2
  211. package/dist/queries/react-hook-candidates.js +1 -1
  212. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  213. package/dist/queries/react-large-component-pressure.js +1 -1
  214. package/dist/queries/recent-duplicates.d.ts +2 -2
  215. package/dist/queries/recent-duplicates.js +1 -1
  216. package/dist/queries/redundant-reexports.d.ts +2 -2
  217. package/dist/queries/redundant-reexports.js +1 -1
  218. package/dist/queries/refs.d.ts +2 -2
  219. package/dist/queries/refs.js +1 -1
  220. package/dist/queries/self-audit.d.ts +2 -2
  221. package/dist/queries/self-audit.js +1 -1
  222. package/dist/queries/similar-chains.d.ts +2 -2
  223. package/dist/queries/similar-chains.js +1 -1
  224. package/dist/queries/similar-files.d.ts +2 -2
  225. package/dist/queries/similar-files.js +1 -1
  226. package/dist/queries/similar-signatures.d.ts +2 -2
  227. package/dist/queries/similar-signatures.js +1 -1
  228. package/dist/queries/similar.d.ts +2 -2
  229. package/dist/queries/similar.js +1 -1
  230. package/dist/queries/slice.d.ts +2 -2
  231. package/dist/queries/slice.js +1 -1
  232. package/dist/queries/stale-abstractions.d.ts +2 -2
  233. package/dist/queries/stale-abstractions.js +1 -1
  234. package/dist/queries/stats.d.ts +2 -2
  235. package/dist/queries/surface.d.ts +2 -2
  236. package/dist/queries/surface.js +1 -1
  237. package/dist/queries/symbols.d.ts +2 -2
  238. package/dist/queries/symbols.js +1 -1
  239. package/dist/queries/system.d.ts +2 -2
  240. package/dist/queries/system.js +1 -1
  241. package/dist/queries/test-quality.d.ts +2 -2
  242. package/dist/queries/test-quality.js +1 -1
  243. package/dist/queries/trace.d.ts +2 -2
  244. package/dist/queries/trace.js +1 -1
  245. package/dist/queries/twin-ab.d.ts +14 -3
  246. package/dist/queries/twin-ab.js +1 -1
  247. package/dist/queries/twin-drift.d.ts +2 -2
  248. package/dist/queries/twin-drift.js +1 -1
  249. package/dist/queries/unused-imports.d.ts +2 -2
  250. package/dist/queries/unused-imports.js +1 -1
  251. package/dist/queries/unused-params.d.ts +2 -2
  252. package/dist/queries/unused-params.js +1 -1
  253. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  254. package/dist/queries/vue-component-duplicates.js +1 -1
  255. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  256. package/dist/queries/vue-composable-candidates.js +1 -1
  257. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  258. package/dist/queries/vue-large-view-pressure.js +1 -1
  259. package/dist/queries/wrapper-candidates.d.ts +2 -2
  260. package/dist/queries/wrapper-candidates.js +1 -1
  261. package/dist/reindex-worker.js +21 -21
  262. package/dist/reindex.d.ts +3 -3
  263. package/dist/reindex.js +33 -33
  264. package/dist/runtime.d.ts +5 -3
  265. package/dist/runtime.js +3 -3
  266. package/dist/rust-semantic-session-server.js +1 -1
  267. package/dist/rust-semantic-session-worker.js +1 -1
  268. package/dist/rust-semantic-worker.js +1 -1
  269. package/dist/{scip-cli-Cc6c00-a.d.ts → scip-cli-BnEwZRLJ.d.ts} +1 -1
  270. package/dist/{symbol-types-BgWU6lhL.d.ts → symbol-types-BIQwfoAx.d.ts} +7 -1
  271. package/dist/typescript-mailbox-worker.js +2 -0
  272. package/dist/watch-server.js +2 -42
  273. package/docs/AGENT_GUIDE.md +13 -6
  274. package/docs/CLI_JSON_OUTPUT.md +110 -22
  275. package/docs/COMMAND_REFERENCE.md +88 -88
  276. package/docs/COMMITTED_RECORD_COMPATIBILITY.md +55 -18
  277. package/docs/DURABILITY.md +88 -38
  278. package/docs/INDEX_GENERATIONS.md +65 -19
  279. package/docs/MAILBOX_LIFECYCLE.md +28 -1
  280. package/docs/REINDEX_METADATA_COMPATIBILITY.md +18 -8
  281. package/docs/SECURITY_MODEL.md +31 -14
  282. package/docs/TELEMETRY_RETENTION.md +11 -4
  283. package/docs/WATCH_REFRESH_REQUESTS.md +34 -21
  284. package/docs/WINDOWS_SIDECAR_RELEASE.md +9 -4
  285. package/docs/analyzer-inventory.md +31 -22
  286. package/docs/analyzer-validation-ledger.md +8 -0
  287. package/docs/schemas/outcome-event-record.schema.json +57 -1
  288. package/docs/schemas/project-config.schema.json +82 -1
  289. package/docs/schemas/suppression-record.schema.json +84 -3
  290. package/package.json +5 -5
  291. package/skills/_shared/SKILL.md +2 -2
  292. package/skills/_shared/references/agent-contract-catalog.md +1 -1
  293. package/skills/_shared/references/detector-precision-and-diffgate.md +1 -1
  294. package/skills/scip-audit/SKILL.md +6 -6
  295. package/skills/scip-audit/references/claims.md +1 -1
  296. package/skills/scip-audit/references/cleanup.md +19 -20
  297. package/skills/scip-audit/references/directory.md +4 -4
  298. package/skills/scip-audit/references/frontend.md +10 -10
  299. package/skills/scip-audit/references/twin-drift.md +2 -2
  300. package/skills/scip-diagnose/references/debug.md +8 -8
  301. package/skills/scip-diagnose/references/root-cause.md +3 -3
  302. package/skills/scip-diagnose/references/triage.md +10 -10
  303. package/skills/scip-explore/SKILL.md +3 -3
  304. package/skills/scip-improve/SKILL.md +10 -10
  305. package/skills/scip-improve/references/cleanup-batches.md +3 -3
  306. package/skills/scip-improve/references/directory-moves.md +3 -3
  307. package/skills/scip-improve/references/doc-reconcile.md +1 -1
  308. package/skills/scip-improve/references/frontend-extraction.md +2 -2
  309. package/skills/scip-improve/references/twin-drift.md +3 -3
  310. package/skills/scip-plan/SKILL.md +2 -2
  311. package/skills/scip-plan/references/api-impact.md +5 -5
  312. package/skills/scip-plan/references/conductor.md +2 -2
  313. package/skills/scip-plan/references/hyper-optimization.md +1 -1
  314. package/skills/scip-query/SKILL.md +15 -5
  315. package/skills/scip-setup/references/bootstrap-workflow.md +7 -8
  316. package/skills/scip-setup/references/language-verification.md +2 -2
  317. package/skills/scip-setup/references/per-repo-triage.md +1 -1
  318. package/skills/scip-verify/SKILL.md +10 -10
  319. package/skills/scip-verify/references/calibrate-detectors.md +7 -7
  320. package/dist/chunk-2465DLHK.js +0 -3
  321. package/dist/chunk-2U3OLUNJ.js +0 -61
  322. package/dist/chunk-33XTHFKR.js +0 -2
  323. package/dist/chunk-43KC6EQZ.js +0 -2
  324. package/dist/chunk-47BU5Z4T.js +0 -8
  325. package/dist/chunk-4YTUWQ6M.js +0 -18
  326. package/dist/chunk-64MNV6AB.js +0 -8
  327. package/dist/chunk-67QRR5YC.js +0 -6
  328. package/dist/chunk-6GXYN7YA.js +0 -40
  329. package/dist/chunk-A2TNXAXO.js +0 -8
  330. package/dist/chunk-APMMR5Y2.js +0 -2
  331. package/dist/chunk-AZFUMCQB.js +0 -2
  332. package/dist/chunk-BNXICU42.js +0 -33
  333. package/dist/chunk-C5Q44Q5D.js +0 -3
  334. package/dist/chunk-DQGSM7RZ.js +0 -20
  335. package/dist/chunk-E2LAW7SL.js +0 -30
  336. package/dist/chunk-E4NFOAD4.js +0 -6
  337. package/dist/chunk-E5HNT4X2.js +0 -3
  338. package/dist/chunk-FD3HFKXR.js +0 -5
  339. package/dist/chunk-GHKEJTCE.js +0 -35
  340. package/dist/chunk-GLZTVKAB.js +0 -16
  341. package/dist/chunk-HIB452NU.js +0 -949
  342. package/dist/chunk-IF6FP6B2.js +0 -66
  343. package/dist/chunk-JORHF5AL.js +0 -108
  344. package/dist/chunk-KSGTULOS.js +0 -9
  345. package/dist/chunk-KXDJAG4N.js +0 -38
  346. package/dist/chunk-L4S2A7BV.js +0 -2
  347. package/dist/chunk-LP3ARJKF.js +0 -8
  348. package/dist/chunk-LSOR3LQG.js +0 -3
  349. package/dist/chunk-NTUMF2X3.js +0 -56
  350. package/dist/chunk-QOXBSI6G.js +0 -20
  351. package/dist/chunk-QXK6UUSM.js +0 -2
  352. package/dist/chunk-RA3AYNWP.js +0 -112
  353. package/dist/chunk-RJMDJR3A.js +0 -2
  354. package/dist/chunk-RLH5VUMG.js +0 -2
  355. package/dist/chunk-SMQWE25B.js +0 -3
  356. package/dist/chunk-TAVELHYR.js +0 -2
  357. package/dist/chunk-VAXNI5NE.js +0 -146
  358. package/dist/chunk-VVY2G5ET.js +0 -2
  359. package/dist/chunk-W3DBTGL4.js +0 -11
  360. package/dist/chunk-WANA4KAQ.js +0 -5
  361. package/dist/chunk-X4FR5BZF.js +0 -9
  362. package/dist/chunk-X6RKPDY7.js +0 -2
  363. package/dist/chunk-YCPASUCX.js +0 -2
  364. package/dist/chunk-ZL2OGDCD.js +0 -2
  365. package/dist/command-descriptors-ZW5J4ZEM.js +0 -631
  366. package/dist/direct-navigation-42YHQPOI.js +0 -3
@@ -1,43 +1,3 @@
1
- import{B as Mr,Ba as Vr,C as Tr,Ca as Ne,D as kr,Da as zr,E as ht,Ea as Jr,F as gt,Fa as Xr,G as Er,Ga as It,H as Dr,Ha as X,I as Fr,Ia as Qr,J as le,Ja as Le,K as Ar,L as _r,La as Zr,M as Nr,Ma as en,N as Lr,Na as tn,O as jr,P as we,Q as Pe,R as Or,T as Wr,U as yt,V as qr,Y as $r,a as ar,aa as Gr,c as Ie,da as Br,ea as Te,f as ot,g as lr,h as dr,i as K,k as st,l as fr,m as mr,n as hr,o as at,p as gr,q as ct,qa as Ur,r as br,s as vr,t as Rr,ta as St,u as Cr,w as ft,x as mt,y as wr,z as Pr,za as Hr}from"./chunk-VAXNI5NE.js";import{b as ce,f as J,g as Me}from"./chunk-IF6FP6B2.js";import{b as nr,c as ir,j as xr,m as ut,o as Ir}from"./chunk-C5Q44Q5D.js";import{A as Fe,B as Ae,C as xt,D as _e,a as or,b as ae,c as sr,g as ur,h as pr,i as F,j as A,k as lt,l as yr,m as dt,n as Sr,o as z,p as pt,q as Ce,s as bt,t as Yr,u as ke,v as vt,w as Kr,y as Ee,z as De}from"./chunk-X4FR5BZF.js";import{a as Re,c as cr,d as it,e as W}from"./chunk-HGFDYOVB.js";import{a as T}from"./chunk-APMMR5Y2.js";import{a as tr,g as rr,h as D}from"./chunk-46XGSFNI.js";import P from"process";import{rmSync as Ei}from"fs";import{resolve as na}from"path";import{pathToFileURL as ia}from"url";import{existsSync as Ai}from"fs";import{isAbsolute as xa,join as _i,relative as Ia,resolve as Ra}from"path";var $=1,Q=2,Fi="./node_modules/scip-query/docs/schemas/project-config.schema.json";function rn(r){let e=r;if(typeof r=="string")try{e=JSON.parse(r)}catch(a){return{kind:"malformed",reason:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}if(!or(e))return{kind:"malformed",reason:"project config must be a JSON object"};let t=e.schemaVersion;if(t!==void 0&&!Number.isInteger(t))return{kind:"malformed",reason:"schemaVersion must be an integer"};let n=t===void 0?$:t;if(n!==$&&n!==Q)return{kind:"unsupported",schemaVersion:n,direction:n<$?"older":"future"};let i=e.$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=nn(e),s=n!==Q||typeof e.$schema!="string";return n===$?{kind:"legacy",sourceVersion:$,config:o,needsMigration:s}:{kind:"supported",sourceVersion:Q,config:o,needsMigration:s}}function nn(r){let e=r,{$schema:t,schemaVersion:n,...i}=e;return{$schema:typeof t=="string"&&t.trim()!==""?t:Fi,schemaVersion:Q,...i}}var je=".scipquery.json",Ni=250,Li=0,ji=10*6e4,Oi={enabled:!1,debounceMs:Ni,cooldownMs:Li,gitPollMs:2e3,idleTimeoutMs:ji,autoRefresh:!0,ignore:[]};var Ma=new Set(ar);function Z(r){let e=_i(r,je);if(!Ai(e))return{};let t;try{t=rr(e,{maxBytes:tr,inputKind:"scip-query project config"})}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`unable to read ${je} at ${e}: ${i}`,{cause:n})}return Wi(rn(t),e,"read").config}function Oe(r){return{...Oi,...r.watch}}function Wi(r,e,t){if(r.kind==="legacy"||r.kind==="supported")return r;if(r.kind==="malformed"){let i=t==="read"?`invalid ${je} at ${e}: ${r.reason}`:`Cannot update ${e}: the latest project config is ${r.reason}.`;throw new Error(`${i} The file was left untouched.`)}let n=t==="read"?`invalid ${je} at ${e}`:`Cannot update ${e}: the latest project config is invalid`;throw new Error(`${n} (unsupported ${r.direction} schemaVersion ${r.schemaVersion}; this scip-query reads legacy v${$} and current v${Q}). Upgrade scip-query before retrying; the file was left untouched.`)}import{existsSync as on}from"fs";function Rt(r,e,t){let n=new Date().toISOString();if(!on(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!on(t.metaPath))return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=Ie(D(t.metaPath,"reindex metadata"));if(i.kind==="unsupported")return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Reindex metadata version ${i.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(i.kind==="malformed")return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not decode reindex metadata: ${i.reason}`,remedy:"Run: scip-query reindex"};let o=i.metadata,s=e.languages??$r(r),a=qi(r,s,e),c=[...o.indexedLanguages??[]].sort(),l=i.capabilities.publishableGeneration&&JSON.stringify(o.fingerprint)===JSON.stringify(a)&&JSON.stringify(c)===JSON.stringify(a.languages),d=Ur(t.dbPath,t.metaPath),u=d.state==="invalid"||d.state==="drifted",p=l&&!u;return{state:p?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:o.updatedAt,lastRefresh:o.lastRefresh,reason:u?`SQLite generation requires repair: ${d.reason}`:l?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:p?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function qi(r,e,t){return Ir(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{statSync as $i}from"fs";import{basename as Gi,isAbsolute as Bi,join as Ui,relative as Hi}from"path";import{watch as Vi}from"chokidar";import Yi from"ignore";var We=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=Oe(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onReindexError=e.onReindexError??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.clock=e.clock??zi,this.reindexRunner=e.reindexRunner??to(),this.subscriptionFactory=e.subscriptionFactory??Ji,this.gitignoreFilter=Me(e.projectRoot),this.extraIgnore=Yi(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let e=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer();let t=this.activeOperation;return t&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"}),this.stopPromise=this.finishStop(e,t).finally(()=>{this.stopInProgress=!1}),this.stopPromise}requestRefresh(e,t={}){if(!this.stopped){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=an(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(e=!1){let t=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(n,i)=>this.isIgnoredWatchPath(n,i?.isDirectory()??!1),usePolling:e,...e?{interval:500,binaryInterval:1e3}:{}});t.on("all",(n,i)=>{this.stopped||this.handleFileChange(i)}),t.on("error",n=>this.handleSourceWatcherError(t,n,e)),this.fsWatchers.push(t)}handleSourceWatcherError(e,t,n){if(n||this.sourcePollingFallbackStarted||!ro(t)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==e),e.close();try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(e,t){let n=this.relativeWatchPath(e);if(!n)return!1;let i=t?`${n}/`:n;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||Gi(t).startsWith(Gr)||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=Bi(e)?e:Ui(this.projectRoot,e);return Hi(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=an(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let t=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let o=this.watchConfig.cooldownMs-e;this.dirty=!0;let s=this.wallNow()+o;this.setStatus({state:"cooldown",until:s,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},o);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=this.wallNow();this.setStatus({state:"indexing",startedAt:n});let i=this.reindexRunner.start(this.reindexRequest(t));this.activeOperation=i,i.completion.then(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let s=!1;try{s=this.onReindexComplete(o,t)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(s){let c=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(c),this.setStatus({state:"idle"});return}let a=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let s=o instanceof Error?o:new Error(String(o));this.onReindexError(s,t),this.onError(s),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===i&&(this.activeOperation=null)})}async finishStop(e,t){let n=[],i=t?t.cancel():null,o=await Promise.allSettled(e.map(s=>Promise.resolve().then(()=>s.close())));for(let s of o)s.status==="rejected"&&n.push(`watch subscription close failed: ${String(s.reason)}`);if(i)try{let s=await i;s.state==="degraded"&&n.push(s.reason)}catch(s){n.push(`reindex cancellation failed: ${s instanceof Error?s.message:String(s)}`)}return n.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:n.join("; ")}),{state:"degraded",reasons:n}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}reindexRequest(e){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:e}}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let n=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;n&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):n?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=at(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=gr(this.projectRoot,e),n={head:at(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=$i(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Ki(r){let{projectRoot:e,config:t,languages:n,pnpmWorkspaces:i,typescriptProjectMode:o,typescriptProjects:s,clojureConfigPath:a,indexerConcurrency:c,trigger:l}=r,d=Z(e),u=Object.keys(d).length>0?d:t,p=K(e,u),y=u.indexer?.typescript,f=u.indexer?.clojure;return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:e,SCIP_REINDEX_OUTPUT_SCIP:p.indexPath,SCIP_REINDEX_OUTPUT_DB:p.dbPath,SCIP_REINDEX_LANGUAGES:(u.languages??n)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(u.indexerConcurrency??c??""),SCIP_REINDEX_PNPM_WORKSPACES:y?.pnpmWorkspaces??i?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:y?.projectMode??o,projects:y?.projects??s??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:f?.configPath??a??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1"}}}var zi={now:T,wallNow:()=>Date.now(),setTimeout:(r,e)=>setTimeout(r,e),clearTimeout:r=>clearTimeout(r),setInterval:(r,e)=>setInterval(r,e),clearInterval:r=>clearInterval(r)},Ji=(r,e)=>Vi(r,e),Xi=15*6e4,Qi=1e3,Zi=64*1024;function eo(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function sn(r,e){let t=r instanceof Error?r.message:String(r),n=e.stderrTail.trim()||e.stdoutTail.trim();return n?`${t}
2
- ${n}`:t}function to(r={}){let e=r.timeoutMs??Xi,t=r.terminationGraceMs??Qi,n=r.maxOutputBytes??Zi,i=r.resolveLaunch??Ki;return{start(o){let s=i(o),a=new AbortController,c=eo(),l=!1,d=en({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:e,terminationGraceMs:t,maxStdoutBytes:n,maxStderrBytes:n,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(u=>{if(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0)throw new Error(sn(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c));return u.durationMs}).catch(u=>{throw u instanceof Zr&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(sn(u,c),{cause:u})}).finally(()=>{l=!0});return{completion:d,async cancel(){l||a.abort();try{await d}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function an(r,e){return r?r.kind===e.kind?r.detail===e.detail?r:{kind:r.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${r.kind}, ${e.kind}`}:e}function ro(r){return r instanceof Error&&"code"in r&&r.code==="EMFILE"||String(r).includes("EMFILE: too many open files")}import{existsSync as fn,statSync as ao}from"fs";import{join as co}from"path";import{join as no}from"path";var ee=3,io=2,oo="typescript-semantic";function ln(r){let e=no(r,oo),t=Yr(e);return{...t,requestDir:t.legacyRequestDir}}function Ct(r){return Rr(r)}function dn(r){let e=JSON.parse(r),t=e.protocolVersion,n=t===io;if(!n&&t!==ee||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||!Number.isFinite(e.deadlineAtMs)||e.profileEnvironment!==void 0&&!sr(e.profileEnvironment)||!e.request||!so(e.request)||!n&&(e.mailboxVersion!==bt||typeof e.operationKey!="string"||!/^[a-f0-9]{64}$/.test(e.operationKey)||e.id!==Kr(e.operationKey)||typeof e.clientId!="string"||!e.clientId||typeof e.enqueuedAtMs!="number"||!Number.isFinite(e.enqueuedAtMs)||e.deadlineAtMs<e.enqueuedAtMs))throw new Error("TypeScript semantic service received an invalid mailbox request.");if(!n){let o=e,s=vt("typescript-semantic-v3",{generation:o.generation,profileEnvironment:o.profileEnvironment,request:o.request});if(o.operationKey!==s)throw new Error("TypeScript semantic service received a mismatched mailbox operation identity.");return o}let i=vt("typescript-semantic-v2",{id:e.id,generation:e.generation,request:e.request});return{protocolVersion:ee,mailboxVersion:bt,id:e.id,operationKey:i,clientId:"legacy-v2",enqueuedAtMs:e.deadlineAtMs,deadlineAtMs:e.deadlineAtMs,generation:e.generation,...e.profileEnvironment?{profileEnvironment:e.profileEnvironment}:{},request:e.request}}function so(r){if(!r||typeof r!="object"||!("kind"in r))return!1;let e=r;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return Er(e.files)!==null;case"references":return cn(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return cn(e.definitions);case"signature":return un(e.definition);default:return!1}}function cn(r){return Array.isArray(r)&&r.every(un)}function un(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}function lo(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var pn;function uo(r=lo(),e=void 0){if(e===void 0&&pn?.projectRoot===r)return pn;let t=Z(r),n=K(r,t),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:r,config:t,paths:n,dbPath:i,dbPathSource:"env",gitContext:e};if(fn(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=co(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:po(o,n.dbPath),gitContext:e}}function mn(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=uo(r);if(!fn(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:r,sharedEvidenceDbPath:St(r,t,a),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,architecture:t.architecture,coverageContracts:t.coverageContracts,docs:t.docs},l=Me(r);return new Cr(c,l)}function po(r,e){let t="unknown time";try{t=ao(r).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${r}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{randomUUID as ps}from"crypto";import{resolve as Bn}from"path";import{performance as S}from"perf_hooks";function qe(r){return{forFile(e,t){return hn(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,hn(r,i,t));return n}}}function hn(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=Dr(r,e)),t.lines&&(n.lines=Fr(r,e)),t.ast&&(n.ast=Ar(r,e)),t.imports&&(n.imports=jr(r,e)),t.reexports&&(n.reexports=Lr(r,e)),i){let o=_r(r,e),s=o.facts;t.facts&&(n.facts=s),o.unavailable&&(n.sourceFactsUnavailable=o.unavailable),t.identifiers&&s&&(n.identifiers=s.fileIdentifiers,n.identifierLineMap=s.identifierLineMap)}return n}var fo={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function $e(r){if(r.startsWith("local "))return{kind:"local",id:r.slice(6),raw:r};let e=r.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:r};let t=e[0],n=e[1],i=r.slice(t.length+1+n.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let c=mo(i);return{scheme:t,manager:n,packageName:o,version:s,descriptors:c,raw:r}}function te(r){let e=$e(r);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let n=e.descriptors[t];if(n?.suffix==="type")return n.name}return null}function mo(r){let e=[],t=0;for(;t<r.length;){if(r[t]==="["){let o=r.indexOf("]",t+1);if(o===-1){e.push({name:r.slice(t+1),suffix:"type-param"});break}e.push({name:r.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(r[t]==="("&&(e.length===0||t===0||gn(r[t-1]))){let o=r.indexOf(")",t+1);if(o!==-1&&r[o+1]!=="."){e.push({name:r.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let n;if(r[t]==="`"){let o=r.indexOf("`",t+1);if(o===-1){n=r.slice(t+1),e.push({name:n,suffix:"term"});break}n=r.slice(t+1,o),t=o+1}else{let o=t;for(;t<r.length&&!gn(r[t]);)t++;n=r.slice(o,t)}if(t>=r.length){n&&e.push({name:n,suffix:"term"});break}let i=r[t];if(i==="("){let o=r.indexOf(")",t+1);o!==-1&&r[o+1]==="."?(e.push({name:n,suffix:"method"}),t=o+2):o!==-1?(e.push({name:n,suffix:"method"}),t=o+1):(e.push({name:n,suffix:"term"}),t++)}else{let o=fo[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function gn(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function G(r){let e=$e(r);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function B(r){let e=$e(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function yn(r){let e=B(r);return e==="method"?!0:e!=="term"?!1:r.endsWith("().")?!0:r.startsWith("rust-analyzer ")&&r.includes("#")?!1:r.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(r):!0}function ho(r,e={}){if(te(r.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(r.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function Sn(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!ho(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||n.set(o.id,o);for(let o of r)n.set(o.id,o);let i=[...n.values()];return t.sort?i.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):i}var go=ce("file-definitions",{clearGroups:["definition-catalog"]}),Ec=ce("file-function-like-definitions",{clearGroups:["definition-catalog"]});function U(r,e,t={}){return t.includeClassMemberFallbacks?bn(r,e,void 0,{includeClassMemberFallbacks:!0}):go.get(r,e,()=>{let n=yo(r,e);if(n)return n;let i=bn(r,e),o=mt(r),s=qe(r).forFile(e,{text:!0}).text;return o&&s&&xn.write(r,e,ft(r,e,s),{projectFingerprint:o,definitions:i.map(a=>({...a}))}),i})}var xn=Pr({kind:"file-definitions",invalidation:Mr("file-definitions"),serialize:So,deserialize:bo});function yo(r,e){let t=mt(r);if(!t)return null;let n=qe(r).forFile(e,{text:!0}).text;if(!n)return null;let i=xn.read(r,e,ft(r,e,n));return i?vo(i,t,e):null}function So(r){return JSON.stringify(r)}function bo(r){try{let e=JSON.parse(r);return!gt(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function vo(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=xo(i,t);if(!o)return null;n.push(o)}return n}function xo(r,e){return!gt(r)||typeof r.symbolId!="number"||typeof r.symbol!="string"||typeof r.documentId!="number"||typeof r.startLine!="number"||typeof r.startChar!="number"&&r.startChar!==void 0||typeof r.endLine!="number"||typeof r.endChar!="number"&&r.endChar!==void 0||r.relativePath!==e||typeof r.leaf!="string"||typeof r.parentTypeName!="string"&&r.parentTypeName!==null||typeof r.isFunctionLike!="boolean"||typeof r.isTypeLike!="boolean"||typeof r.kind!="number"&&r.kind!==null||typeof r.documentation!="string"&&r.documentation!==null||typeof r.enclosingSymbol!="string"&&r.enclosingSymbol!==null?null:{symbolId:r.symbolId,symbol:r.symbol,documentId:r.documentId,startLine:r.startLine,startChar:r.startChar,endLine:r.endLine,endChar:r.endChar,relativePath:r.relativePath,leaf:r.leaf,parentTypeName:r.parentTypeName,isFunctionLike:r.isFunctionLike,isTypeLike:r.isTypeLike,kind:r.kind,documentation:r.documentation,enclosingSymbol:r.enclosingSymbol}}function bn(r,e,t,n={}){let i=Sn(Io(r,e),Ro(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(Co);return t&&(i=i.filter(t)),Po(r,e,i)}function Io(r,e){return r.all(`SELECT
3
- gs.id,
4
- gs.symbol,
5
- der.document_id,
6
- der.start_line,
7
- der.start_char,
8
- der.end_line,
9
- der.end_char,
10
- d.relative_path,
11
- gs.display_name,
12
- gs.kind,
13
- gs.documentation,
14
- gs.enclosing_symbol
15
- FROM global_symbols gs
16
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
17
- JOIN documents d ON der.document_id = d.id
18
- WHERE d.relative_path = ?
19
- ${r.symbolNoiseFor("gs")}
20
- ORDER BY der.start_line, der.end_line`,e)}function Ro(r,e){return r.all(`SELECT
21
- gs.id,
22
- gs.symbol,
23
- c.document_id,
24
- MIN(c.start_line) AS start_line,
25
- 0 AS start_char,
26
- MAX(c.end_line) AS end_line,
27
- 0 AS end_char,
28
- d.relative_path,
29
- gs.display_name,
30
- gs.kind,
31
- gs.documentation,
32
- gs.enclosing_symbol
33
- FROM global_symbols gs
34
- JOIN mentions m ON m.symbol_id = gs.id
35
- JOIN chunks c ON m.chunk_id = c.id
36
- JOIN documents d ON c.document_id = d.id
37
- WHERE d.relative_path = ?
38
- AND m.role = 1
39
- ${r.symbolNoiseFor("gs")}
40
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
41
- ORDER BY start_line, end_line`,e)}function Co(r){return{symbolId:r.id,symbol:r.symbol,documentId:r.document_id,startLine:r.start_line,startChar:r.start_char??0,endLine:r.end_line,endChar:r.end_char??0,relativePath:r.relative_path,leaf:G(r.symbol),parentTypeName:te(r.symbol),isFunctionLike:yn(r.symbol),isTypeLike:B(r.symbol)==="type",kind:r.kind??null,documentation:r.documentation??null,enclosingSymbol:r.enclosing_symbol??null}}function In(r,e={}){return wo(r,e.scope)}function wo(r,e){return J(r,{scope:e,includeIgnored:!1}).flatMap(t=>U(r,t)).filter(t=>!r.isIgnored(t.relativePath))}function Po(r,e,t){let n=qe(r).forFile(e,{text:!0}).text,i=Nr(r,e);return i?Fo(t,i,n):n?Mo(t,n):t}function Mo(r,e){let t=e.split(/\r?\n/),n=To(r,t),i=ko(r,n),o=Eo(i,t);return Do(r,o)}function To(r,e){let t=r.some(i=>Ge(i.symbol))?Wo(e):null,n=new Map;for(let i of r)n.set(i.symbolId,Oo(e,t,i));return n}function ko(r,e){return r.filter(t=>Ge(t.symbol)).map(t=>({definition:t,startLine:e.get(t.symbolId)??t.startLine})).sort((t,n)=>t.startLine-n.startLine||t.definition.startLine-n.definition.startLine||t.definition.symbol.localeCompare(n.definition.symbol))}function Eo(r,e){let t=new Map;for(let n=0;n<r.length;n+=1){let i=r[n],o=r[n+1],s=o?Math.max(i.startLine,o.startLine-1):e.length-1;t.set(i.definition.symbolId,{startLine:i.startLine,endLine:qo(e,i.definition,i.startLine,s)})}return t}function Do(r,e){return r.map(t=>{let n=e.get(t.symbolId);return n?{...t,startLine:n.startLine,endLine:n.endLine}:t})}function Fo(r,e,t=null){let n=new Map;for(let i of e){let o=n.get(i.name);o?o.push(i):n.set(i.name,[i])}return r.map(i=>{if(!jo(i)||!i.leaf)return vn(i,t);let o=n.get(i.leaf);if(!o||o.length===0)return vn(i,t);let s=t?Ao(i,o,t):null;if(s)return{...i,startLine:s.startLine,endLine:s.endLine};let a=o[0],c=Math.abs(a.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let d=o[l],u=Math.abs(d.startLine-i.startLine);u<c&&(a=d,c=u)}return{...i,startLine:a.startLine,endLine:a.endLine}})}function Ao(r,e,t){let n=_o(r.symbol);if(!n)return null;let i=t.split(/\r?\n/),o=new RegExp(`\\b${le(n)}\\b`);for(let s of e){let a=No(i,s.startLine);if(a&&o.test(a))return s}return null}function _o(r){return r.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function No(r,e){for(let t=e;t>=0;t-=1){let n=r[t]?.trim()??"";if(n){if(/^impl\b/.test(n))return Lo(r,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(n))return null}}return null}function Lo(r,e,t){let n=[];for(let i=e;i<=t;i+=1){let o=r[i]??"";if(n.push(o),o.includes("{"))break}return n.join(" ")}function jo(r){return Ge(r.symbol)?!0:B(r.symbol)==="term"&&te(r.symbol)===null}function vn(r,e){if(!e||!r.leaf||B(r.symbol)!=="term"||te(r.symbol)!==null)return r;let t=le(r.leaf),n=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${t}\\b`),o=e.split(/\r?\n/).findIndex(s=>n.test(s));return o>=0?{...r,startLine:o,endLine:o}:r}function Oo(r,e,t){if(!Ge(t.symbol))return t.startLine;let n=Math.max(0,Math.min(t.startLine,r.length-1));if(!e)return n;let i=e.get(t.leaf);if(!i||i.length===0)return n;let o=null;for(let s of i){let a=Math.abs(s-t.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??n}function Wo(r){let e=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,t=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,n=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\b([A-Za-z_$][\w$]*)\s*\(/g,o=new Map,s=(a,c)=>{let l=o.get(a);if(!l){o.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let a=0;a<r.length;a+=1){let c=r[a]??"";for(let d of c.matchAll(e))d[1]&&s(d[1],a);for(let d of c.matchAll(t))d[1]&&s(d[1],a);let l=c.match(n);l?.[1]&&s(l[1],a);for(let d of c.matchAll(i))d[1]&&s(d[1],a)}return o}function qo(r,e,t,n){let i=Math.max(t,Math.min(r.length-1,n)),o=Math.max(t,Math.min(i,e.endLine)),s=0,a=0,c=!1;for(let l=t;l<=i;l+=1){let d=$o(r[l]??"");for(let u of d)u==="{"?(s+=1,c=!0):u==="}"?s=Math.max(0,s-1):u==="("?a+=1:u===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function $o(r){let e="",t=null,n=!1;for(let i=0;i<r.length;i+=1){let o=r[i],s=r[i+1];if(!t&&o==="/"&&s==="/"){e+=" ".repeat(r.length-i);break}if(t){if(n){n=!1,e+=" ";continue}if(o==="\\"){n=!0,e+=" ";continue}o===t&&(t=null),e+=" ";continue}if(o==='"'||o==="'"||o==="`"){t=o,e+=" ";continue}e+=o}return e}function Ge(r){return r.includes("().")}function _(r,e,t){if(r.has(e))return r.get(e);let n=t();return r.set(e,n),n}import wn from"path";import{realpathSync as Rn}from"fs";function Go(r,e){return r.getReferences().map(t=>{let n=t.getNode();return Be(n,e)})}function Bo(r){let e=r;return typeof e.findReferences=="function"?e.findReferences():[]}function Pn(r,e,t,n){let i=[];for(let o of Bo(r))for(let s of Go(o,n))s.file===e.relativePath&&s.line>=e.startLine&&s.line<=e.endLine||i.push(s);for(let o of t)i.push(o);return re(i)}function Mn(r,e,t,n){let i=[],o=t?.getStart();for(let s of r.getReferences()){let a=s.getNode();ne(n,a.getSourceFile().getFilePath())===e&&(o!==void 0&&a.getStart()===o||i.push({location:Be(a,n),node:a}))}return i}function Be(r,e){let t=r.getSourceFile(),n=t.getLineAndColumnAtPos(r.getStart());return{file:ne(e,t.getFilePath())??t.getBaseName(),line:n.line-1,column:n.column-1}}function Tn(r,e,t){let n=r.getSourceFile(),i=Pt(n,r),o=r.getText(),s=new RegExp(`\\b${le(o)}\\b`,"g"),a=n.getFullText().split(`
42
- `),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let d=a[l]??"";s.lastIndex=0;let u;for(;(u=s.exec(d))!==null;)c.push({file:e,line:l,column:u.index})}return re(c.filter(l=>ne(t,wn.join(t,l.file))===e))}function wt(r){for(let e=r;e;e=e.getParent()){let t=e.getKindName();if(t.includes("Type")||t==="InterfaceDeclaration"||t==="TypeAliasDeclaration")return!0;if(t==="CallExpression"||t==="NewExpression"||t==="ExpressionStatement")return!1}return!1}function Pt(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function re(r){let e=new Set,t=[];for(let n of r){let i=`${n.file}:${n.line}:${n.column}`;e.has(i)||(e.add(i),t.push(n))}return t}function ne(r,e){let t=r||process.cwd(),n=Cn(t,e);if(n)return n;try{return Cn(Rn(t),Rn(e))}catch{return null}}function Cn(r,e){let t=wn.relative(r,e).replace(/\\/g,"/");return!t||t===".."||t.startsWith("../")?null:t}function kn(r,e,t,n){let i=Uo(e,n);return i.size===0?new Map:Ho(r,t,i)}function Uo(r,e){let t=new Map;for(let n of U(r,e)){let i=G(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function Ho(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let s of Vo(r,o)){let a=t.get(s);if(!a)continue;let c=Pt(e,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),u=i.get(l.symbolId);u!==void 0&&u<=d||(i.set(l.symbolId,d),n.set(l.symbolId,o))}}}),n}function Vo(r,e){let t=[],n=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();n(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();n(i)}return r.Node.isIdentifier(e)&&n(e.getText()),t}var Yo=ce("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function En(r,e,t,n){let i=kt(r,e),o=Mt(i.get(n)??[],t);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||G(c.symbol)||"").includes(n)||c.symbol.includes(n))&&s.push(c);return Mt(s,t)}function Tt(r,e,t,n){return Mt(kt(r,e).get(n)??[],t)}function Dn(r,e){let t=new Map;for(let[n,i]of kt(r,e)){let o=i[0];o&&t.set(n,o)}return t}function kt(r,e){return Yo.get(r,e,()=>{let t=new Map;for(let n of U(r,e)){let i=n.leaf||G(n.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...n,leaf:i})}for(let n of t.values())n.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function Mt(r,e){let t=null,n=Number.POSITIVE_INFINITY;for(let i of r){let o=Math.abs(i.startLine-e);(o<n||o===n&&t&&i.startLine<t.startLine)&&(t=i,n=o)}return t}import Ko from"path";import{realpathSync as zo}from"fs";function Fn(r,e){let t=new Map,n=null,i=null,o=()=>(i??=J(r,{extensions:we}),i),s=()=>(n??=W("typescript.source-file-index",()=>Jo(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),a=c=>Pe(c)?_(t,c,()=>{let l=An(r.config.projectRoot,c);if(!l)return null;for(let{project:d,sourceFiles:u}of s()){let p=u.get(l)??null;if(p||(p=d.addSourceFileAtPathIfExists(l)??null,p&&Et(u,p)),p)return{project:d,sourceFile:p}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function Jo(r,e,t){let n=e.map(({project:i})=>{let o=new Map;for(let s of i.getSourceFiles())Et(o,s);return{project:i,sourceFiles:o}});for(let i of t){let o=An(r,i);if(o)for(let s of n){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){Et(s.sourceFiles,a);break}}}return n}function Et(r,e){let t=Dt(e.getFilePath());r.set(t,e);try{r.set(Dt(zo(t)),e)}catch(n){if(!ut(n))throw n}}function An(r,e){try{return Dt(xr(r,e,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(t){if(!ut(t))throw t;return null}}function Dt(r){return Ko.resolve(r)}function Ft(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function _n(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as de}from"fs";import x from"path";var At=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function _t(r,e){let n=e?x.dirname(x.join(r,e)):r,i=x.resolve(r);for(;n.startsWith(i);){for(let s of At){let a=x.join(n,s);if(de(a))return a}let o=x.dirname(n);if(o===n)break;n=o}for(let o of At){let s=x.join(r,o);if(de(s))return s}return null}function Nn(r){let e=r.config.projectRoot,t=new Set(Xo(e,r.config.semantic?.typescript?.tsconfigs)),n=J(r,{includeIgnored:!1,extensions:we});for(let i of n){let o=_t(e,i);o&&t.add(x.resolve(o))}if(t.size===0){let i=_t(e);i&&t.add(x.resolve(i))}return[...t].filter(i=>!Ln(e,i)).sort((i,o)=>i.localeCompare(o))}function Xo(r,e=[]){let t=new Set;for(let n of e){let i=x.isAbsolute(n)?n:x.join(r,n);de(i)&&t.add(x.resolve(i))}for(let n of Qo(r))for(let i of At){let o=x.join(n,i);de(o)&&t.add(x.resolve(o))}if(t.size===0){let n=_t(r);n&&t.add(x.resolve(n))}return[...t].filter(n=>!Ln(r,n)).sort((n,i)=>n.localeCompare(i))}function Qo(r){let e=x.join(r,"package.json");if(!de(e))return[];let t;try{t=JSON.parse(D(e,"project package manifest"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>kr(r,i))}function Ln(r,e){let t=x.relative(r,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var Zo=32;function Gn(r,e,t,n={}){return W("typescript.provider.construct",()=>new Lt(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var Lt=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=Tr(e.config.projectRoot),this.sourceFiles=Fn(e,n)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(e=>e.tsconfigPath)}}importUsage(e){return _(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=ts();return W("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return _(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=Re(),o=[];for(let d of e){let u=this.referencesCache.get(d.symbolId);u?n.set(d.symbolId,u):o.push(d)}if(o.length===0)return n;let s=o,a=t.exact?[]:o.filter(d=>!On(d));if(a.length>=Zo){let d=this.referencesForDefinitionsBySymbolScan(a);for(let u of a){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}if(s=o.filter(u=>On(u)),s.length===0)return n}let c=new Map;for(let d of s){let u=c.get(d.relativePath);u?u.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,u]of c){let p=Wn();W("typescript.references-map.file",()=>{let y=this.definitionNodesForFile(d);for(let f of u){i&&(p.cacheMisses+=1);let h=y.get(f.symbolId)??null;i&&(h?p.nodeHits+=1:p.nodeMisses+=1);try{let m=this.referencesForDefinitionNode(f,h,i?p:void 0);this.referencesCache.set(f.symbolId,m),n.set(f.symbolId,m)}catch{p.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:u.length,...qn(p)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let u of l){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}}return n}referenceFragmentsForFiles(e){let t=In(this.db).filter(o=>Pe(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return qr(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=Re(),i=Wn(),o=new Map,s=new Set(e.map(c=>c.symbolId)),a=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return W("typescript.references-map.inverted-scan",()=>{let c=n?S.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let m of e){let g=l.get(m.symbolId)??[];if(g.length>0){let R=o.get(m.symbolId)??[];R.push(...g),o.set(m.symbolId,R)}n&&(i.packageReferenceCount+=g.length)}n&&(i.packageRefsMs+=S.now()-c);let d=new Map,u=new Map,p=this.hierarchyTargetsForDefinitions(e),y=new Set(e.map(m=>m.leaf).filter(Boolean)),f=n?S.now():0;for(let m of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(m))continue;let g=this.sourceFiles.sourceFile(m);g&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(g,m,s,a,p,y,d,u,o,n?i:void 0))}n&&(i.scanMs+=S.now()-f);let h=n?S.now():0;this.addHierarchyMemberReferences(e,o,n?i:void 0),n&&(i.hierarchyMs+=S.now()-h);for(let[m,g]of o){let R=re(g);o.set(m,R),n&&(i.referenceCount+=R.length)}},()=>({definitions:e.length,...qn(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,s,a,c,l,d){let u=this.compilerCheckerForSourceFile(e),p=e.compilerNode,y=is(e),f=h=>{if(this.tsMorph.ts.isIdentifier(h)){if(d&&(d.identifiers+=1),!s.has(h.text)&&!y.has(h.text)){this.tsMorph.ts.forEachChild(h,f);return}let m=this.compilerReferenceSymbol(u,h,d);if(m){let g;a.has(m)?g=a.get(m)??null:(g=this.referenceDefinitionFromCompilerSymbol(m),a.set(m,g)),d&&(g?d.targetHits+=1:d.targetMisses+=1);let R=_(c,m,()=>this.compilerSymbolKeys(m)),M=null,k=null,O=g&&n.has(g.symbolId)?i.get(g.symbolId):void 0;if(O&&(M=Nt(p,h),!jn(O,t,M))){let j=p.getLineAndCharacterOfPosition(h.getStart(p));k={file:t,line:j.line,column:j.character};let N=l.get(O.symbolId)??[];N.push(k),l.set(O.symbolId,N),d&&(d.requestedHits+=1)}for(let j of R)for(let N of o.get(j)?.values()??[]){if(M??=Nt(p,h),jn(N,t,M))continue;if(!k){let C=p.getLineAndCharacterOfPosition(h.getStart(p));k={file:t,line:C.line,column:C.character}}let I=l.get(N.symbolId)??[];I.push(k),l.set(N.symbolId,I),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(h,f)};f(p)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let n of e){let i=this.nodeForDefinition(n),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let d of this.compilerSymbolKeys(l)){let u=t.get(d)??new Map;u.set(n.symbolId,n),t.set(d,u)}}return t}hierarchyMemberSymbols(e,t,n){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let d of l){let u=d.getProperty(n.name);u&&s(d,u,this.hierarchyAncestorTypesForType(e,d))}}};return s(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,n){let i=new Map;for(let o of e){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),d=l.getSymbolAtLocation(a.name);if(!d)continue;let u=a.getSourceFile(),p=u.getLineAndCharacterOfPosition(a.name.getStart(u)),y={definition:o,location:{file:o.relativePath,line:p.line,column:p.character}},f=t.get(o.symbolId)??[];for(let m of this.hierarchyMemberSymbols(l,c,d))if(m!==d)for(let g of this.compilerSymbolLocations(m))f.push(g),n&&(n.hierarchyReferences+=1);t.set(o.symbolId,f);let h=this.hierarchyRootMemberSymbols(l,c,d);for(let m of h){let g=i.get(m)??new Map;g.set(o.symbolId,y),i.set(m,g)}n&&(n.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){n&&(n.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=t.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),n&&(n.hierarchyReferences+=1));t.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(e,t,n){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let d=!1;for(let u of l){let p=u.getProperty(n.name);p&&(d=!0,s(u,p,this.hierarchyAncestorTypesForType(e,u)))}if(!d)for(let u of this.compilerSymbolKeys(c))i.add(u)};return s(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let n=t.getSourceFile();return`${n.fileName}\0${t.getStart(n)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let n of e.declarations??[]){let i=n.getSourceFile(),o=ne(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=n.name,a=i.getLineAndCharacterOfPosition((s??n).getStart(i));t.push({file:o,line:a.line,column:a.character})}return t}baseTypes(e,t){try{return e.getBaseTypes(t)??[]}catch{return[]}}hierarchyAncestorTypes(e,t){let n=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)n.add(e.getTypeAtLocation(o));return[...n]}hierarchyAncestorTypesForType(e,t){let n=new Set(this.baseTypes(e,t));for(let i of t.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let s of o.types)n.add(e.getTypeAtLocation(s));return[...n]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,t,n){n&&(n.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return n&&(n.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return _(this.calleesCache,e.symbolId,()=>_(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,n=new Map;for(let i of e){let o=n.get(i.relativePath);o?o.push(i):n.set(i.relativePath,[i])}for(let[i,o]of n){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),t.set(l.symbolId,d)}}return t}referencesForDefinitionNode(e,t,n){let i=n?S.now():0,o=this.packageImportReferencesForDefinition(e);if(n&&(n.packageRefsMs+=S.now()-i,n.packageReferenceCount+=o.length),!t)return o;let s=n?S.now():0,a=Pn(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=S.now()-s,n.referenceCount+=a.length),a}signatureFor(e){return _(this.signatureCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);if(!t||!this.tsMorph.Node.isFunctionDeclaration(t)&&!this.tsMorph.Node.isMethodDeclaration(t)&&!this.tsMorph.Node.isArrowFunction(t)&&!this.tsMorph.Node.isFunctionExpression(t)&&!this.tsMorph.Node.isConstructorDeclaration(t))return null;let n=t.getType().getCallSignatures()[0];if(!n)return null;let i=n.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return $n(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${$n(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let s of t.getImportDeclarations()){n.declarations+=1;let a=ht(this.db,e,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of jt(s)){n.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?n.bindingSymbols+=1:n.missingBindingSymbols+=1);let u={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(u),c||!l.localName||!d)continue;let p=o.get(l.localName);p?p.push(u):o.set(l.localName,[u])}}return o.size>0&&t.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||rs(s))return;n.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(n.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:Be(s,this.db.config.projectRoot),node:s}),n.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?es(e,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(n.fallbackEntries+=1,this.valueImportUsageForEntry(e,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(e,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(e,t,n){let i=n.identifier?n.identifier.findReferences():[],o=[];for(let s of i)for(let a of Mn(s,e,n.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(e,t,n,o)}valueImportUsageFromLocations(e,t,n,i){let o=i.some(c=>!wt(c.node)),s=i.some(c=>wt(c.node)),a=n.isTypeOnly;return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let t=new Map,n=new Set;for(let o of e){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=Ft(this.workspacePackages,a.getModuleSpecifierValue());c&&n.add(c)}}if(n.size===0)return t;let i=this.packageExportsForNames(n);for(let o of e)this.addPackageImportReferencesForDocument(t,i,o);for(let[o,s]of t)t.set(o,re(s));return t}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,t=this.packageExports();for(let n of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,n);for(let[n,i]of e)e.set(n,re(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,n){if(this.db.isIgnored(n))return;let i=this.sourceFiles.sourceFileMatch(n);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,n,o)}addPackageImportReferencesForDeclaration(e,t,n,i){let o=Ft(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=t.get(o);if(s)for(let a of jt(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Tn(a.identifier,n,this.db.config.projectRoot);l.length>0&&cs(e,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let t=new Map;for(let n of this.workspacePackages){if(!e.has(n.name))continue;let i=new Map;for(let o of _n(n))this.collectPackageExports(n,o,i,new Set);i.size>0&&t.set(n.name,i)}return t}collectPackageExports(e,t,n,i){if(i.has(t))return;i.add(t);let o=this.sourceFiles.sourceFile(t);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?ht(this.db,t,a):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(e,c,n,i);continue}for(let d of l){let u=d.getNameNode().getText(),p=d.getAliasNode()?.getText()??u,y=this.indexedDefinitionByLeaf(c,u);if(!y)continue;let f=n.get(p);f||(f=new Set,n.set(p,f)),f.add(y.symbolId)}}}indexedDefinitionByLeaf(e,t){return _(this.indexedDefinitionLeafCache,e,()=>Dn(this.db,e)).get(t)??null}nodeForDefinition(e){return _(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return _(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?kn(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,n=!1){let i=e.name,o=t?S.now():0,s=e.declarations??[];t&&(t.declarationsMs+=S.now()-o,t.declarationChecks+=s.length);for(let a of s){let c=t?S.now():0,l=a.getSourceFile(),d=ne(this.db.config.projectRoot,l.fileName),u=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(t&&(t.declarationLocationMs+=S.now()-c),!d||this.db.isIgnored(d))continue;let p=t?S.now():0,y=this.compilerDeclarationName(a),f=n?Tt(this.db,d,u,i)??(y&&y!==i?Tt(this.db,d,u,y):null):En(this.db,d,u,i);if(t&&(t.indexedLookupMs+=S.now()-p),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(e){let t=e.name;return t&&this.tsMorph.ts.isIdentifier(t)?t.text:null}calleeMapForFile(e,t){let n=Re(),i=0,o=0,s=0,a=0,c=0,l=0,d=0,u=0,p=n?ss():void 0;return W("typescript.callee-map.file",()=>{let y=n?S.now():0,f=this.sourceFiles.sourceFile(e);if(n&&(c=Math.round(S.now()-y)),!f)return new Map;let h=n?S.now():0,m=U(this.db,e).sort((I,C)=>I.startLine-C.startLine||C.endLine-I.endLine);if(n&&(l=Math.round(S.now()-h)),i=m.length,m.length===0)return new Map;let g=new Map,R=n?S.now():0,M=this.compilerCheckerForSourceFile(f),k=f.compilerNode;n&&(d=Math.round(S.now()-R));let O=new Map,j=I=>{if(this.tsMorph.ts.isCallExpression(I)||this.tsMorph.ts.isNewExpression(I)){n&&(o+=1);let C=this.semanticCalleeForCallNode(M,k,m,I,O,t,p);C&&(n&&(s+=1),ns(g,C.callerId,C.target))}this.tsMorph.ts.forEachChild(I,j)},N=n?S.now():0;j(k),n&&(u=Math.round(S.now()-N));for(let[I,C]of g)g.set(I,ls(C));return a=g.size,g},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:u,...p?as(p):{}}))}semanticCalleeForCallNode(e,t,n,i,o,s,a){let c=a?S.now():0,l=os(n,Nt(t,i));if(a&&(a.callerLookupMs+=S.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let d=i.expression,u=this.compilerSymbolForExpression(e,d,a),p=null;if(u)if(a&&(a.targetSymbolHits+=1),o.has(u))a&&(a.compilerSymbolCacheHits+=1),p=o.get(u)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let y=a?S.now():0;p=this.definitionFromCompilerSymbol(u,a),a&&(a.targetLookupMs+=S.now()-y),o.set(u,p)}else a&&(a.targetMisses+=1);return p?{callerId:l.symbolId,target:{symbol:p.symbol,file:p.file,line:p.line}}:null}compilerSymbolForExpression(e,t,n){let i=n?S.now():0,o=e.getSymbolAtLocation(t);if(n&&(n.expressionSymbolMs+=S.now()-i),o)return o;n&&(n.typeFallbacks+=1);let s=n?S.now():0,a=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=S.now()-s),a}compilerCheckerForSourceFile(e){let t=e.getProject(),n=this.compilerCheckerCache.get(t);return n||(n=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,n)),n}};function jt(r){let e=[],t=r.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});let n=r.getNamespaceImport();n&&e.push({identifier:n,importedName:"*",localName:n.getText(),kind:"namespace",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});for(let i of r.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(r.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function es(r,e,t){return{importer:r,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function ts(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function rs(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function ns(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function is(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of jt(t))n.localName&&e.add(n.localName);return e}function os(r,e){let t=null;for(let n of r)e<n.startLine||e>n.endLine||(!t||n.startLine>=t.startLine)&&(t=n);return t}function Nt(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function jn(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function On(r){return r.symbol.includes("#")?B(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function ss(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function as(r){return{...r,callerLookupMs:Math.round(r.callerLookupMs),expressionSymbolMs:Math.round(r.expressionSymbolMs),typeSymbolMs:Math.round(r.typeSymbolMs),targetLookupMs:Math.round(r.targetLookupMs),declarationsMs:Math.round(r.declarationsMs),declarationLocationMs:Math.round(r.declarationLocationMs),indexedLookupMs:Math.round(r.indexedLookupMs)}}function Wn(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function qn(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function cs(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function ls(r){let e=new Set,t=[];for(let n of r){let i=`${n.symbol}|${n.file}|${n.line}`;e.has(i)||(e.add(i),t.push(n))}return t}function $n(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ue=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??Or,this.discoverTsconfigs=t.discoverTsconfigs??Nn,this.createProjects=t.createProjects??Wr,this.createProvider=t.createProvider??((n,i,o)=>Gn(n,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let n=ds(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?n.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,n):(n.mode==="refresh"&&(us(this.projects,e.config.projectRoot,n),this.stats.sessionsRefreshed+=1),n):n}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=yt("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=yt("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function ds(r){let e=new Set;r.projectIdentityChanged&&e.add("project-identity-changed");for(let o of r.uncertainty)e.add(o);for(let o of r.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=Ot(r.changes,"added"),n=Ot(r.changes,"modified"),i=Ot(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function Ot(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function us(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(Bn(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(Bn(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var He=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new Ue(t)),this.generationIdentity=e.generationIdentity?t=>e.generationIdentity(t.config.dbPath):t=>t.generation.identity,this.readSnapshot=e.readSnapshot?t=>e.readSnapshot(t.config.dbPath):hs,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let n=this.host.semanticProvider();switch(this.available=n.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return n.availability();case"import-usage":return n.importUsage(t.file);case"references":return[...fs(n,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!n.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...n.referenceFragmentsForFiles(t.files)];case"callees":return[...ms(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return ys(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(e){let t=this.host?.snapshotStats();return{protocolVersion:ee,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:t?.sessionsCreated??0,sessionsReused:t?.sessionsReused??0,sessionsRefreshed:t?.sessionsRefreshed??0,sessionsReplaced:t?.sessionsReplaced??0,projectsCreated:t?.projectsCreated??0,...e?{mailbox:e}:{}}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),n=this.generationIdentity(t);if(!n||n!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let i=this.readSnapshot(t);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,gs(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function Wt(r){ke(r)}function Hn(r,e,t={}){Wt(r);let n=t.nowMs??Date.now(),i=Ee(r,{ownerId:t.ownerId??Ss,nowMs:n,limits:t.limits,owner:bs,liveness:vs}),o=0;for(let s of i){let a=s.requestId,c=null;try{let l=dn(De(s,t.limits));if(a=l.id,a!==s.requestId)throw new Error("TypeScript semantic request identity does not match its mailbox path.");if(l.deadlineAtMs<n)throw new Error("TypeScript semantic request expired before processing.");c=cr(),it(l.profileEnvironment??{}),t.beforeRequest?.(l.deadlineAtMs);let d=e.handle(l.generation,l.request);Fe(r,s,{ok:!0,protocolVersion:ee,id:a,generation:l.generation,response:d},{nowMs:n,limits:t.limits})}catch(l){let d=l instanceof Error?l.message:String(l);Ae(r,s,{ok:!1,protocolVersion:ee,id:a,error:d},d,{nowMs:n,limits:t.limits})}finally{c&&it(c),t.afterRequest?.(),o+=1}}return o}function Vn(r){return _e(r)}function fs(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function ms(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function hs(r){if(!r.generation.metadataRaw)return null;let e=Ie(r.generation.metadataRaw);return e.kind!=="legacy"&&e.kind!=="supported"||!e.capabilities.usableForEvidenceCache?null:nr(e.metadata.fingerprint)}function gs(r,e){return e?ir(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function ys(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}var Ss=`typescript-semantic-${process.pid}-${ps()}`,Un=F(process.pid),bs={pid:process.pid,...Un?{processIdentity:Un}:{}},vs={isProcessAlive:A,readProcessIdentity:F};import{randomUUID as xs}from"crypto";import{resolve as Is}from"path";var Ve=class{projectRoot;currentGeneration;createEmitter;wallNow;monotonicNow;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=Is(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Vr,this.wallNow=e.wallNow??e.now??Date.now,this.monotonicNow=e.monotonicNow??e.now??T}handle(e,t){let n=this.monotonicNow();try{if(this.currentGeneration()!==e)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(t);if(i.emitter.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),s=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),a=this.monotonicNow()-n;return this.requests+=1,this.lastRequestAtMs=this.wallNow(),this.lastDurationMs=a,this.lastError=null,this.unavailable=!1,{producerIdentity:s.producerIdentity,cold:s.stats.initializations>o.initializations,durationMs:a,fragments:s.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(e){let t=this.active?.emitter.snapshotStats();return{protocolVersion:Ne,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:t?.initializations??0,programUpdates:t?.programUpdates??0,documentsEmitted:t?.documentsEmitted??0,documentsRemoved:t?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{},...e?{mailbox:e}:{}}}close(){this.active=null}emitterFor(e){let t=`${e.tsconfigPath}\0${e.projectArgument}`;if(this.active&&this.active.sessionKey===t&&this.active.projectIdentity===e.projectIdentity)return this.active;let n=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!n.available)throw this.unavailable=!0,new Error(n.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:n.emitter},this.sessionsCreated+=1,this.active}};function qt(r){ke(r)}function Kn(r,e,t={}){qt(r);let n=t.nowMs??Date.now(),i=Ee(r,{ownerId:t.ownerId??Rs,nowMs:n,limits:t.limits,owner:Cs,liveness:ws}),o=0;for(let s of i){let a=s.requestId;try{let c=Jr(De(s,t.limits));if(a=c.id,a!==s.requestId)throw new Error("TypeScript index request identity does not match its mailbox path.");if(c.deadlineAtMs<n)throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.baseGeneration,c.request);Fe(r,s,{ok:!0,protocolVersion:Ne,id:a,baseGeneration:c.baseGeneration,response:l},{nowMs:n,limits:t.limits})}catch(c){let l=c instanceof Error?c.message:String(c);Ae(r,s,{ok:!1,protocolVersion:Ne,id:a,error:l},l,{nowMs:n,limits:t.limits})}finally{t.afterRequest?.(),o+=1}}return o}function zn(r){return _e(r)}var Rs=`typescript-index-${process.pid}-${xs()}`,Yn=F(process.pid),Cs={pid:process.pid,...Yn?{processIdentity:Yn}:{}},ws={isProcessAlive:A,readProcessIdentity:F};import{spawn as Ws}from"child_process";import{existsSync as qs,rmSync as pi}from"fs";import{dirname as id,resolve as Kt}from"path";import{fileURLToPath as sd}from"url";import{createHash as Ps,randomUUID as $t}from"crypto";import{existsSync as Ms,linkSync as Ts,mkdirSync as Jn,readdirSync as ks,rmSync as ie}from"fs";import{basename as Es,dirname as Ds,join as v}from"path";var H=1,Fs=10*6e4,As=10080*6e4,Ke="requests",ue="claims",Ye="completions",Qn="staging";function Zn(r,e,t={}){let n=t.now?.()??new Date,i=Ns(t.ttlMs),o=Ls(t.idempotencyKey),s=o?`key-${Ps("sha256").update(o).digest("hex")}`:`request-${(t.randomId??$t)()}`,a={version:H,requestId:s,...o?{idempotencyKey:o}:{},createdAt:n.toISOString(),deadlineAt:new Date(n.getTime()+i).toISOString(),detail:e.trim().slice(0,2048)||"stale index observed by a command"},c=li(r,s);if(Ut(r,c,a,t.onStage))return{disposition:"accepted",request:a};let d=Bt(c);if(!d)throw new Error(`Watch refresh request identity ${s} exists but is malformed.`);return{disposition:"duplicate",request:d}}function ei(r,e={}){let t=e.now?.()??new Date,n=`claim-${(e.randomId??$t)()}`,i=Math.max(1,Math.floor(e.limit??64)),o=si(r).sort(js),s=[];for(let a of o){if(s.length>=i)break;if(Xn(r,a.requestId))continue;if(Date.parse(a.deadlineAt)<=t.getTime()){oi(r,{version:H,requestId:a.requestId,outcome:"expired",completedAt:t.toISOString()});continue}let c={version:H,requestId:a.requestId,claimId:n,claimedAt:t.toISOString()};if(Ut(r,di(r,a.requestId),c)){if(Xn(r,a.requestId)){ai(r,a.requestId,n);continue}s.push(a)}}return{claimId:n,requests:s}}function ti(r,e,t=()=>new Date,n){let i=t().toISOString();for(let o of e.requests)oi(r,{version:H,requestId:o.requestId,claimId:e.claimId,outcome:"completed",completedAt:i});n?.("after-completion"),ze(r,e),n?.("after-claim-release")}function ze(r,e){for(let t of e.requests)ai(r,t.requestId,e.claimId)}function ri(r){let e=0;for(let t of V(v(r,ue)))ie(t,{force:!0}),e++;return e>0&&z(v(r,ue)),ci(r),e}function Gt(r){let e=si(r),t=new Map,n=_s(v(r,Ke),Bt);for(let c of V(v(r,Ye))){let l=Je(c);if(!l){n++;continue}t.set(l.requestId,l)}let i=new Set;for(let c of V(v(r,ue))){let l=ii(c);if(!l){n++;continue}i.add(l.requestId)}let o=e.filter(c=>!t.has(c.requestId)&&!i.has(c.requestId)),s=[...t.values()].filter(c=>c.outcome==="completed").length,a=[...t.values()].filter(c=>c.outcome==="expired").length;return{pending:o.length,claimed:e.filter(c=>!t.has(c.requestId)&&i.has(c.requestId)).length,completed:s,expired:a,invalid:n,...o.length>0?{oldestPendingAt:o.map(c=>c.createdAt).reduce((c,l)=>Os(c,l))}:{}}}function ni(r,e={}){let t=(e.now?.()??new Date).getTime(),n=Math.max(0,e.retentionMs??As),i=0;for(let o of V(v(r,Ye))){let s=Je(o);!s||t-Date.parse(s.completedAt)<n||(ie(o,{force:!0}),ie(li(r,s.requestId),{force:!0}),i++)}return i>0&&(z(v(r,Ye)),z(v(r,Ke))),ci(r),i}function Bt(r){return Ht(r,e=>{let t=e;return t.version===H&&pe(t.requestId)&&(t.idempotencyKey===void 0||typeof t.idempotencyKey=="string")&&ae(t.createdAt)&&ae(t.deadlineAt)&&Date.parse(t.deadlineAt)>=Date.parse(t.createdAt)&&typeof t.detail=="string"&&t.detail.length>0})}function ii(r){return Ht(r,e=>{let t=e;return t.version===H&&pe(t.requestId)&&pe(t.claimId)&&ae(t.claimedAt)})}function Je(r){return Ht(r,e=>{let t=e;return t.version===H&&pe(t.requestId)&&(t.claimId===void 0||pe(t.claimId))&&(t.outcome==="completed"||t.outcome==="expired")&&ae(t.completedAt)})}function oi(r,e){let t=ui(r,e.requestId);if(Ut(r,t,e))return;let n=Je(t);if(!n||n.requestId!==e.requestId||n.outcome!==e.outcome)throw new Error(`Watch refresh completion ${e.requestId} conflicts with an existing record.`)}function Ut(r,e,t,n){let i=v(r,Qn),o=Ds(e);Jn(i,{recursive:!0}),Jn(o,{recursive:!0});let s=v(i,`${Es(e)}.${process.pid}.${$t()}.tmp`);try{Ce(s,t,{spacing:2,trailingNewline:!0}),n?.("after-staged");try{Ts(s,e)}catch(a){if(a.code==="EEXIST")return!1;throw a}return z(o),n?.("after-published"),!0}finally{ie(s,{force:!0})}}function si(r){let e=[];for(let t of V(v(r,Ke))){let n=Bt(t);n&&e.push(n)}return e}function ai(r,e,t){let n=di(r,e),i=ii(n);!i||i.claimId!==t||(ie(n,{force:!0}),z(v(r,ue)))}function ci(r){for(let e of V(v(r,Qn),".tmp"))ie(e,{force:!0})}function _s(r,e){return V(r).filter(t=>!e(t)).length}function V(r,e=".json"){return Ms(r)?ks(r,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(e)).map(t=>v(r,t.name)).sort():[]}function Ht(r,e){try{let t=JSON.parse(D(r,"watch refresh request record"));return e(t)?t:null}catch{return null}}function li(r,e){return v(r,Ke,`${e}.json`)}function di(r,e){return v(r,ue,`${e}.json`)}function ui(r,e){return v(r,Ye,`${e}.json`)}function Xn(r,e){return Je(ui(r,e))!==null}function Ns(r){if(r===void 0)return Fs;if(!Number.isFinite(r)||r<=0)throw new Error("Watch refresh request ttlMs must be positive.");return Math.floor(r)}function Ls(r){let e=r?.trim();return e?e.slice(0,512):void 0}function pe(r){return typeof r=="string"&&/^[a-z0-9][a-z0-9-]{0,127}$/i.test(r)}function js(r,e){return Date.parse(r.createdAt)-Date.parse(e.createdAt)||r.requestId.localeCompare(e.requestId)}function Os(r,e){return Date.parse(e)<Date.parse(r)?e:r}var $s=2e3,Gs=10;function mi(r,e,t){let n=ct(Kt(r));if(t&&ct(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=mr(n);if(i.kind==="error")throw new Error(`Could not establish Git worktree identity for ${n}: ${i.message}`);return i.kind==="non-git"?{projectRoot:n,worktreeKind:"non-git",cliVersion:e}:{projectRoot:n,worktreeKind:"git",worktreeId:i.identity.worktreeId,cliVersion:e}}function hi(r){let e=r.runtime??Hs,t=X(r.cacheDir),n=Qr(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=Bs("stop",i);if(o.kind==="signal-stop")return fi(o.state,r,e),Vt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return Vt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let s=bi(t.lockPath);return o.kind==="already-stopped"&&s&&e.isProcessAlive(s.pid)?(fi(s,r,e),Vt(t,s.pid,e),{disposition:"stopped",pid:s.pid}):{disposition:"already-stopped"}}function gi(r,e){Ce(r,e)}function yi(r){try{let e=JSON.parse(D(r,"watch activity record"));return e.version!==1||!Le(e.at)||e.refreshRequestedAt!==void 0&&!Le(e.refreshRequestedAt)||e.refreshDetail!==void 0&&typeof e.refreshDetail!="string"?null:{atMs:Date.parse(e.at),...e.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(e.refreshRequestedAt)},...e.refreshDetail===void 0?{}:{refreshDetail:e.refreshDetail}}}catch{return null}}function Si(r,e,t={}){let n=t.pid??process.pid,i=t.isProcessAlive??A,o=()=>{},s=t.readProcessIdentity??F,a=t.now??(()=>new Date),c={...lt,wallNow:()=>a().getTime(),isProcessAlive:i,readProcessIdentity:s},l=yr(r,{kind:"watch",pid:n,processIdentity:s(n),detail:{projectRoot:Kt(e)},parseLegacy:Xe,runtime:c});if(l.kind==="contended"){let d=vi(l.observation);return{acquired:!1,lockPath:r,message:Us(r,e,d),release:o}}return{acquired:!0,lockPath:r,message:"",release:()=>{l.lock.release()}}}function bi(r){return vi(dt(r,{parseLegacy:Xe}))}var Xe=r=>{let e=xi(r);return e?{pid:e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{}}:null};function vi(r){if(r.state==="valid"&&r.record?.kind==="watch"){let e=r.record.detail?.projectRoot;return typeof e!="string"?null:{version:1,pid:r.record.pid,...r.record.processIdentity?{processIdentity:r.record.processIdentity}:{},projectRoot:e,startedAt:r.record.startedAt}}return xi(r.parsed)}function xi(r){try{let e=r;if(e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!Le(e.startedAt))return null;let t=e.processIdentity===void 0?null:ur(e.processIdentity);return e.processIdentity!==void 0&&(!t||t.pid!==e.pid)?null:{version:1,pid:e.pid,...t?{processIdentity:t}:{},projectRoot:e.projectRoot,startedAt:e.startedAt}}catch{return null}}function Bs(r,e){switch(r){case"status":return{kind:"report",classification:e};case"ensure":switch(e.kind){case"stopped":return{kind:"start"};case"stale":return e.reason==="old-heartbeat"?{kind:"refuse-replace",state:e.state,reason:"old-heartbeat"}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return Yt(e)}case"stop":switch(e.kind){case"stopped":return{kind:"already-stopped"};case"stale":return e.reason==="old-heartbeat"?{kind:"signal-stop",state:e.state}:{kind:"clean-stale",state:e.state};case"live":case"incompatible":return{kind:"signal-stop",state:e.state};default:return Yt(e)}default:return Yt(r)}}function Ii(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function fi(r,e,t){let{pid:n}=r;if(!t.isProcessAlive(n))return;Vs(r,t),t.signalProcess(n);let i=e.stopTimeoutMs??$s,o=t.monotonicNow??T,s=o()+i;for(;o()<=s;){if(!t.isProcessAlive(n))return;t.sleep(Gs)}throw new Error(`scip-query watch service pid ${n} did not stop within ${i}ms.`)}function Vt(r,e,t){if(pi(r.statePath,{force:!0}),pi(r.activityPath,{force:!0}),bi(r.lockPath)?.pid===e&&!t.isProcessAlive(e)){let i={...lt,wallNow:t.now,isProcessAlive:t.isProcessAlive,readProcessIdentity:t.readProcessIdentity},o=dt(r.lockPath,{parseLegacy:Xe,runtime:i});Sr(r.lockPath,o,{parseLegacy:Xe,runtime:i})}}function Us(r,e,t){return`error: scip-query watch is already running for ${Kt(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}var Hs={now:Date.now,monotonicNow:T,isProcessAlive:A,readProcessIdentity:F,spawnServer(r,e,t,n){if(!qs(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);Ws(process.execPath,[r,e,t,JSON.stringify(n)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(r){process.kill(r,"SIGTERM")},sleep(r){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,r)}};function Vs(r,e){if(!r.processIdentity)throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its ownership record has no process identity.`);let t=e.readProcessIdentity(r.pid);if(!t)throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its process identity is unavailable.`);if(!pr(r.processIdentity,t))throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its process identity does not match the ownership record.`)}function Yt(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as Pi,lstatSync as Qe,readdirSync as Mi,realpathSync as Ri,rmSync as fe,statSync as Ys}from"fs";import{join as w,resolve as me,sep as Ci}from"path";var Ks=3600*1e3,zs=2*1024*1024*1024,Js=300*1e3;function Xs(r){let e=r.leases.filter(a=>a.managed&&!a.live&&!a.busy),t=Qs(r.leases,r.locks),n={};for(let a of r.generations)t.has(a.generationId)||(n[a.generationId]=a.unreferencedAt??r.nowMs);let i=r.generations.filter(a=>!t.has(a.generationId)).sort((a,c)=>n[a.generationId]-n[c.generationId]||a.generationId.localeCompare(c.generationId)),o=new Set;for(let a of i)r.nowMs-n[a.generationId]>=r.policy.generationTtlMs&&o.add(a.generationId);let s=r.generations.filter(a=>!o.has(a.generationId)).reduce((a,c)=>a+c.size,0);for(let a of i){if(s<=r.policy.budgetBytes)break;o.has(a.generationId)||(o.add(a.generationId),s-=a.size)}for(let a of o)delete n[a];return{deleteWorktrees:e,deleteGenerations:r.generations.filter(a=>o.has(a.generationId)),deleteLocks:r.locks.filter(a=>!a.live),deleteTemporaries:r.temporaries.filter(a=>!a.live),protectedGenerationIds:[...t].sort(),unreferencedSince:n}}function Qs(r,e){let t=new Set(r.filter(n=>n.managed&&(n.live||n.busy)).flatMap(n=>[n.lease.baseGenerationId,n.lease.activeGenerationId]).filter(n=>n!==void 0));for(let n of e)n.live&&t.add(n.generationId);return t}function Ti(r,e,t={}){if(!dr())return{kind:"disabled"};let n=fr(r);if(!n)return{kind:"unavailable"};let i=w(ot(),"repositories",n.repositoryId);if(!Pi(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),s=w(i,"gc-state.json"),a=ta(s);if(!t.force&&a&&o-Date.parse(a.lastSweepAt)<Js)return{kind:"throttled",sweptAt:a.lastSweepAt};let c=br(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=Zs(r,i,n.repositoryId,a?.unreferencedSince??{}),d=Xs({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??Ks,budgetBytes:t.policy?.budgetBytes??zs}}),u=0,p=0;for(let h of d.deleteWorktrees){if(!ki(h.lease))continue;let m=vr(w(h.lease.localCacheDir,"cache-lifecycle.lock"));if(m)try{if(Jt(h.lease,!0))continue;try{hi({projectRoot:h.lease.projectRoot,cacheDir:h.lease.localCacheDir,cliVersion:e})}catch{continue}if(Jt(h.lease,!0))continue;fe(h.lease.localCacheDir,{recursive:!0,force:!0}),fe(h.leasePath,{force:!0}),p+=1}finally{m.release()}}for(let h of d.deleteLocks)fe(h.path,{force:!0});for(let h of d.deleteTemporaries)fe(h.path,{recursive:!0,force:!0});for(let h of d.deleteGenerations)fe(h.path,{recursive:!0,force:!0}),u+=h.size;wr(w(i,"evidence.db"));let y={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:p,deletedGenerations:d.deleteGenerations.length,deletedBytes:u,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:y.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:y};return pt(s,f,{spacing:2,trailingNewline:!0}),y}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function Zs(r,e,t,n){let i=new Set(hr(r).map(l=>me(l.path))),o=[];for(let l of zt(w(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=w(e,"worktrees",l),u=ea(d);if(!u)continue;let p=me(u.projectRoot);o.push({leasePath:d,lease:u,managed:u.repositoryId===t&&ki(u),live:i.has(p)||Pi(p),busy:Jt(u)})}let s=[];for(let l of zt(w(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let u=w(e,"locks",l),p=Xt(u),y=p!==void 0&&A(p),f=d[1];s.push({generationId:f,path:u,live:y})}let a=[],c=[];for(let l of zt(w(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let y=w(e,"generations",l),f=Number(d[1]);try{c.push({path:y,size:wi(y),live:Number.isSafeInteger(f)&&A(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let u=w(e,"generations",l),p;try{p=Qe(u)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||a.push({generationId:l,path:u,size:wi(u),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:a,locks:s,temporaries:c}}function ki(r){if(r.ownershipChecksum!==Hr(r)||st(r.localCacheDir)!==st(lr(r.projectRoot)))return!1;let e=me(ot()),t=me(w(e,"projects")),n=me(r.localCacheDir);if(!n.startsWith(`${t}${Ci}`))return!1;try{let i=Qe(e),o=Qe(t),s=Qe(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!s.isDirectory()||s.isSymbolicLink())return!1;let a=Ri(t);return Ri(n).startsWith(`${a}${Ci}`)}catch{return!1}}function Jt(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=Xt(w(r.localCacheDir,n));if(i!==void 0&&A(i))return!0}let t=Xt(X(r.localCacheDir).lockPath);return t!==void 0&&A(t)}function ea(r){try{let e=JSON.parse(D(r,"worktree cache lease"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function Xt(r){try{let e=JSON.parse(D(r,"watch lock record"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function ta(r){try{let e=JSON.parse(D(r,"repository cache GC state"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function zt(r){try{return Mi(r)}catch{return[]}}function wi(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of Mi(n,{withFileTypes:!0})){let o=w(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Ys(o).size)}}return e}var Ze=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(e,t={}){this.root=e,this.now=t.now??Date.now,this.randomId=t.randomId,this.retryDelayMs=Math.max(1,Math.floor(t.retryDelayMs??1e3)),this.currentStatus=Gt(e)}initializeAfterOwnershipAcquired(){let e=ri(this.root),t=ni(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:e,prunedHistory:t}}observeLegacyRequest(e,t){Zn(this.root,t??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${e}`,now:()=>new Date(e)}),this.refreshStatus()}poll(e,t){if(this.active||e.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let n=ei(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),n.requests.length===0)return!1;this.active=n;try{return t(ra(n)),!0}catch(i){throw ze(this.root,n),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),i}}completeActive(){return this.active?(ti(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(ze(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=Gt(this.root)}};function ra(r){if(r.requests.length===1)return r.requests[0].detail;let t=[...new Set(r.requests.map(n=>n.detail))].slice(0,3).join("; ");return`${r.requests.length} coalesced refresh requests${t?`: ${t}`:""}`.slice(0,2048)}var oa=1e3,sa=250,aa=6e4,ca=10,la=50;function da(r){return r>0?ca:la}function ua(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function pa(r,e,t={}){let n=mi(r,e),i=n.projectRoot,o=Z(i);o.watch={...o.watch,...t};let s=Oe(o);if(!s.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let a=K(i,o),c=X(a.cacheDir),l=F(P.pid),d=Si(c.lockPath,i,{readProcessIdentity:b=>b===P.pid?l:F(b)});if(!d.acquired)return;let u=new Ze(c.refreshRequestsPath,{retryDelayMs:Math.max(1e3,s.cooldownMs)});u.initializeAfterOwnershipAcquired();let p=Date.now(),y=T(),f=p,h=y,m={state:"idle"},g,R,M,k=Te(a.dbPath),O=!1,j=!1,N=0,I=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY,Qt=Number.NEGATIVE_INFINITY,Zt=Number.NEGATIVE_INFINITY,he,ge,ye=ln(a.cacheDir),Se=zr(a.cacheDir);Wt(ye),qt(Se);let et=new He({openDb:()=>mn(i)}),tt=new Ve({projectRoot:i,currentGeneration:()=>Xr(a.dbPath)}),L=(b=!1)=>{if(!j)return;let xe=Date.now(),se=T();!b&&se-I<oa||(I=se,gi(c.statePath,{version:1,protocolVersion:It,pid:P.pid,...l?{processIdentity:l}:{},projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(p).toISOString(),heartbeatAt:new Date(xe).toISOString(),lastActivityAt:new Date(f).toISOString(),...s.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(f+s.idleTimeoutMs).toISOString()},watcher:m,...m.state==="idle"&&g?{indexGeneration:g}:{},...R?{lastRefresh:R}:{},...M?{lastError:M}:{},reindexActivity:k,refreshRequests:u.status(),typescriptSemantic:{...et.status(Vn(ye)),...he===void 0?{}:{busyUntil:new Date(he).toISOString()}},typescriptIndex:{...tt.status(zn(Se)),...ge===void 0?{}:{busyUntil:new Date(ge).toISOString()}}}))},Y=()=>{f=Date.now(),h=T()},be=new We({projectRoot:i,config:{...o,watch:s},languages:o.languages,onStatus(b){m=b,b.state!=="idle"&&(g=void 0),b.state!=="idle"&&Y(),L(!0)},onReindexComplete(){Y();let b=Rt(i,o,a);return R=b.lastRefresh,g=b.state==="fresh"?Ct(a.dbPath)??void 0:void 0,k=Te(a.dbPath),u.completeActive(),M=void 0,L(!0),b.state==="fresh"},onReindexError(){u.failActive()},onRefreshSuppressed(b){Br(a.dbPath,b),k=Te(a.dbPath)},onError(b){Y(),g=void 0,M={at:new Date().toISOString(),message:b.message},L(!0)}}),ve=()=>{O=!0};P.once("SIGINT",ve),P.once("SIGTERM",ve);let rt=!1,nt,oe;try{be.start();let b=Rt(i,o,a);R=b.lastRefresh,g=b.state==="fresh"?Ct(a.dbPath)??void 0:void 0;let xe=ua(b.state);for(xe&&be.requestRefresh(xe,{immediate:!0}),Y(),j=!0,L(!0);!O;){let se=Kn(Se,tt,{beforeRequest(E){ge=E+5e3,L(!0)},afterRequest(){ge=void 0,L(!0)}}),er=Hn(ye,et,{beforeRequest(E){he=E+5e3,L(!0)},afterRequest(){he=void 0,L(!0)}}),q=T();if(q-Zt>=aa&&(Zt=q,xt(Se),xt(ye)),q-Qt>=6e4&&(Qt=q,Ti(i,e)),q-C>=sa){C=q;let E=yi(c.activityPath);E&&E.atMs>f&&(f=E.atMs,h=q),E?.refreshRequestedAtMs!==void 0&&E.refreshRequestedAtMs>N&&(N=E.refreshRequestedAtMs,u.observeLegacyRequest(E.refreshRequestedAtMs,E.refreshDetail??"stale index observed by a legacy command")),u.poll(m,Di=>{Y(),be.requestRefresh({kind:"watch-demand",detail:Di},{immediate:!0})})}if((er>0||se>0)&&(Y(),L(!0)),L(),Ii({watcher:m,lastActivityAtMs:h,nowMs:T(),idleTimeoutMs:s.idleTimeoutMs}))break;await fa(da(er+se))}}catch(b){rt=!0,nt=b}finally{P.off("SIGINT",ve),P.off("SIGTERM",ve),et.closeTypeScriptService(),tt.close();let b=await be.stop();b.state==="stopped"?(Ei(c.statePath,{force:!0}),Ei(c.activityPath,{force:!0}),d.release()):(M={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${b.reasons.join("; ")}`},L(!0),oe=new Error(M.message))}if(rt&&oe)throw new AggregateError([nt,oe],"Watch service execution and shutdown both failed.");if(rt)throw nt;if(oe)throw oe}function fa(r){return new Promise(e=>setTimeout(e,r))}var ma=P.argv[1]?ia(na(P.argv[1])).href:null;if(ma===import.meta.url){let r=P.argv[2],e=P.argv[3],t=ha(P.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),P.exitCode=1;else try{await pa(r,e,t)}catch(n){console.error(`watch-service: ${tn(n instanceof Error?n.message:String(n))}`),P.exitCode=1}}function ha(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{pa as runWatchServiceServer,ua as startupRefreshTrigger,da as watchServiceLoopDelayMs};
1
+ import{c as vt,f as yt,g as ee,h as Le,i as L,j as Wt,k as re,m as Tt,n as Et,o as Pt}from"./chunk-L5GJNV2T.js";import"./chunk-IZYYAFN5.js";import{b as Ct,c as ie,d as ne,e as Oe,f as se,g as Mt,h as De,i as At,k as qt}from"./chunk-DAFAHMNB.js";import{Aa as kt,B as gt,g as ke,h as st,i as ot,j as K,l as We,m as ct,n as lt,o as dt,p as Ee,q as ut,r as Pe,s as ft,t as mt,va as Rt,ya as te,za as xt}from"./chunk-HZ72SESS.js";import{g as St}from"./chunk-FJH2NW7J.js";import"./chunk-WUPW3UN3.js";import{A as wt,B as bt,C as Ae,D as qe,E as _e,F as It,b as N,i as xe,j as _,k as nt,l as I,m as Ce,n as ht,o as Me,p as pt,r as Q,s as Z}from"./chunk-AIE7TFJW.js";import"./chunk-HGFDYOVB.js";import{a as b,b as at,c as Te,d as x}from"./chunk-MNE7YG56.js";import{h as E}from"./chunk-46XGSFNI.js";import R from"process";import{rmSync as kr}from"fs";import{resolve as Ei}from"path";import{pathToFileURL as Pi}from"url";import{statSync as Tr}from"fs";import{basename as Er,isAbsolute as Pr,join as Cr,relative as Mr}from"path";import{watch as Ar}from"chokidar";import qr from"ignore";var Dt=5e3,ae=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=ne(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onReindexError=e.onReindexError??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(r=>console.error(r.message)),this.clock=e.clock??jr,jt.set(this,Hr(e.stopTimeoutMs??Dt,"watcher stop timeout")),this.reindexRunner=e.reindexRunner??Vr(),this.subscriptionFactory=e.subscriptionFactory??Nr,this.gitignoreFilter=St(e.projectRoot),this.extraIgnore=qr(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,oe(this).errors=[],this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let e=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer();let r=this.activeOperation;r&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...oe(this).closures],n=Lr(this),s=this.clock.now()+n;return this.stopPromise=this.finishStop(e,i,r,s,n).catch(a=>{throw this.stopInProgress=!1,a}),this.stopPromise}requestRefresh(e,r={}){if(!this.stopped){if(!r.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=Ot(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(e=!1){let r=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(i,n)=>this.isIgnoredWatchPath(i,n?.isDirectory()??!1),usePolling:e,...e?{interval:500,binaryInterval:1e3}:{}});r.on("all",(i,n)=>{this.stopped||this.handleFileChange(n)}),r.on("error",i=>this.handleSourceWatcherError(r,i,e)),this.fsWatchers.push(r)}handleSourceWatcherError(e,r,i){if(i||this.sourcePollingFallbackStarted||!Ur(r)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(r)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(n=>n!==e),Or(oe(this),e,n=>this.onError(n));try{this.startSourceWatcher(!0)}catch(n){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`))}}isIgnoredWatchPath(e,r){let i=this.relativeWatchPath(e);if(!i)return!1;let n=r?`${i}/`:i;return n===".git/"||n.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)}handleFileChange(e){let r=this.relativeWatchPath(e);!r||r===".."||r.startsWith("../")||r===".git"||r.startsWith(".git/")||this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)||r.endsWith("index.db")||r.endsWith("index.scip")||r.endsWith("index.db.tmp")||Er(r).startsWith(vt)||this.scheduleReindex({kind:"watch-source",detail:r})}relativeWatchPath(e){let r=Pr(e)?e:Cr(this.projectRoot,e);return Mr(this.projectRoot,r).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=Ot(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let r=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:r}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let s=this.watchConfig.cooldownMs-e;this.dirty=!0;let a=this.wallNow()+s;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},s);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let r=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let i=this.wallNow();this.setStatus({state:"indexing",startedAt:i});let n=this.reindexRunner.start(this.reindexRequest(r));this.activeOperation=n,n.completion.then(s=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=!1;try{a=this.onReindexComplete(s,r)===!0}catch(o){this.onError(o instanceof Error?o:new Error(String(o)))}if(this.dirty&&!this.stopped){if(a){let c=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(c),this.setStatus({state:"idle"});return}let o=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(s=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=s instanceof Error?s:new Error(String(s));this.onReindexError(a,r),this.onError(a),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===n&&(this.activeOperation=null)})}async finishStop(e,r,i,n,s){let a=[],o=e.map(async m=>{try{await m.close()}catch(h){a.push(`watch subscription close failed: ${String(h)}`)}});o.push(...r),i&&o.push((async()=>{try{let m=await i.cancel();m.state==="degraded"&&a.push(m.reason)}catch(m){a.push(`reindex cancellation failed: ${m instanceof Error?m.message:String(m)}`)}})());let c=o.length,l=o.map(m=>m.finally(()=>{c-=1})),u=await _r(l,n,this.clock),d=oe(this);return a.push(...d.errors),d.errors=[],u?this.stopInProgress=!1:(a.push(`watch shutdown exceeded the ${s}ms deadline with ${c} operation(s) still pending`),Promise.all(l).then(()=>{this.stopInProgress=!1})),a.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:a.join("; ")}),{state:"degraded",reasons:a}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}reindexRequest(e){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:e}}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,r=this.readGitState();if(!e||!r||this.stopped){this.lastGitState=r;return}this.lastGitState=r;let i=e.head!==r.head,n=e.indexPath!==r.indexPath||e.indexMtimeMs!==r.indexMtimeMs||e.indexSize!==r.indexSize;i&&n?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):i?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):n&&this.scheduleReindex({kind:"watch-git-index",detail:r.indexPath??"index changed"})}readGitState(){let e=Ee(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let r=ut(this.projectRoot,e),i={head:Ee(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:r};try{let n=Tr(r);i.indexMtimeMs=n.mtimeMs,i.indexSize=n.size}catch{i.indexMtimeMs=void 0,i.indexSize=void 0}return i}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function _r(t,e,r){if(t.length===0)return!0;let i=Promise.all(t).then(()=>!0),n=Math.max(0,e-r.now()),s=null,a=new Promise(c=>{s=r.setTimeout(()=>c(!1),n)}),o=await Promise.race([i,a]);return o&&s&&r.clearTimeout(s),o}var _t=new WeakMap,jt=new WeakMap;function oe(t){let e=_t.get(t);if(e)return e;let r={closures:new Set,errors:[]};return _t.set(t,r),r}function Lr(t){return jt.get(t)??Dt}function Or(t,e,r){let i=Promise.resolve().then(()=>e.close()).catch(n=>{let s=`watch subscription close failed during polling fallback: ${String(n)}`;t.errors.push(s),r(new Error(s))});t.closures.add(i),i.then(()=>t.closures.delete(i))}function Dr(t){let{projectRoot:e,config:r,languages:i,pnpmWorkspaces:n,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:o,indexerConcurrency:c,trigger:l}=t,u=ie(e),d=Object.keys(u).length>0?u:r,m=K(e,d),h=d.indexer?.typescript,g=d.indexer?.clojure;return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:e,SCIP_REINDEX_OUTPUT_SCIP:m.indexPath,SCIP_REINDEX_OUTPUT_DB:m.dbPath,SCIP_REINDEX_LANGUAGES:(d.languages??i)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(d.indexerConcurrency??c??""),SCIP_REINDEX_PNPM_WORKSPACES:h?.pnpmWorkspaces??n?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:h?.projectMode??s,projects:h?.projects??a??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:g?.configPath??o??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1"}}}var jr={now:b,wallNow:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},Nr=(t,e)=>Ar(t,e),Gr=15*6e4,Fr=1e3,$r=64*1024;function Br(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function Lt(t,e){let r=t instanceof Error?t.message:String(t),i=e.stderrTail.trim()||e.stdoutTail.trim();return i?`${r}
2
+ ${i}`:r}function Vr(t={}){let e=t.timeoutMs??Gr,r=t.terminationGraceMs??Fr,i=t.maxOutputBytes??$r,n=t.resolveLaunch??Dr;return{start(s){let a=n(s),o=new AbortController,c=Br(),l=!1,u=Et({command:process.execPath,args:[...process.execArgv,a.workerPath],label:"watch reindex worker",env:a.env,timeoutMs:e,terminationGraceMs:r,maxStdoutBytes:i,maxStderrBytes:i,outputLimitBehavior:"truncate-tail",signal:o.signal,detached:!0}).then(d=>{if(c={stdoutTail:d.stdout,stderrTail:d.stderr,stdoutTruncated:d.stdoutTruncated,stderrTruncated:d.stderrTruncated},d.status!==0)throw new Error(Lt(new Error(`Reindex worker exited with ${d.signal?`signal ${d.signal}`:`code ${d.status}`}`),c));return d.durationMs}).catch(d=>{throw d instanceof Tt&&(c={stdoutTail:d.stdout,stderrTail:d.stderr,stdoutTruncated:d.stdoutTruncated,stderrTruncated:d.stderrTruncated}),new Error(Lt(d,c),{cause:d})}).finally(()=>{l=!0});return{completion:u,async cancel(){l||o.abort();try{await u}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Ot(t,e){return t?t.kind===e.kind?t.detail===e.detail?t:{kind:t.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${t.kind}, ${e.kind}`}:e}function Ur(t){return t instanceof Error&&"code"in t&&t.code==="EMFILE"||String(t).includes("EMFILE: too many open files")}function Hr(t,e){if(!Number.isSafeInteger(t)||t<=0)throw new Error(`${e} must be a positive integer.`);return t}import{spawn as oi}from"child_process";import{existsSync as ai,rmSync as er}from"fs";import{dirname as mn,resolve as Ue}from"path";import{fileURLToPath as Sn}from"url";import{createHash as zr,randomUUID as je}from"crypto";import{existsSync as Yr,linkSync as Jr,readdirSync as Xr,rmSync as O}from"fs";import{basename as Kr,dirname as Qr,join as v}from"path";var A=1,Zr=10*6e4,ei=10080*6e4,le="requests",G="claims",ce="completions",Gt="staging";function Ft(t,e,r={}){let i=r.now?.()??new Date,n=ri(r.ttlMs),s=ii(r.idempotencyKey),a=s?`key-${zr("sha256").update(s).digest("hex")}`:`request-${(r.randomId??je)()}`,o={version:A,requestId:a,...s?{idempotencyKey:s}:{},createdAt:i.toISOString(),deadlineAt:new Date(i.getTime()+n).toISOString(),detail:e.trim().slice(0,2048)||"stale index observed by a command"},c=Kt(t,a),l=Fe(t,c,o,r.onStage);if(l.published)return{disposition:"accepted",request:o,achievedDurability:l.achievedDurability,directorySync:l.directorySync};let u=Ge(c);if(!u)throw new Error(`Watch refresh request identity ${a} exists but is malformed.`);return{disposition:"duplicate",request:u}}function $t(t,e={}){let r=e.now?.()??new Date,i=`claim-${(e.randomId??je)()}`,n=Math.max(1,Math.floor(e.limit??64)),s=Yt(t).sort(ni),a=[];for(let o of s){if(a.length>=n)break;if(Nt(t,o.requestId))continue;if(Date.parse(o.deadlineAt)<=r.getTime()){zt(t,{version:A,requestId:o.requestId,outcome:"expired",completedAt:r.toISOString()});continue}let c={version:A,requestId:o.requestId,claimId:i,claimedAt:r.toISOString()};if(Fe(t,Qt(t,o.requestId),c).published){if(Nt(t,o.requestId)){Jt(t,o.requestId,i);continue}a.push(o)}}return{claimId:i,requests:a}}function Bt(t,e,r=()=>new Date,i){let n=r().toISOString();for(let s of e.requests)zt(t,{version:A,requestId:s.requestId,claimId:e.claimId,outcome:"completed",completedAt:n});i?.("after-completion"),de(t,e),i?.("after-claim-release")}function de(t,e){for(let r of e.requests)Jt(t,r.requestId,e.claimId)}function Vt(t){let e=0;for(let r of q(v(t,G)))O(r,{force:!0}),e++;return e>0&&_(v(t,G)),Xt(t),e}function Ne(t){let e=Yt(t),r=new Map,i=ti(v(t,le),Ge);for(let c of q(v(t,ce))){let l=ue(c);if(!l){i++;continue}r.set(l.requestId,l)}let n=new Set;for(let c of q(v(t,G))){let l=Ht(c);if(!l){i++;continue}n.add(l.requestId)}let s=e.filter(c=>!r.has(c.requestId)&&!n.has(c.requestId)),a=[...r.values()].filter(c=>c.outcome==="completed").length,o=[...r.values()].filter(c=>c.outcome==="expired").length;return{pending:s.length,claimed:e.filter(c=>!r.has(c.requestId)&&n.has(c.requestId)).length,completed:a,expired:o,invalid:i,...s.length>0?{oldestPendingAt:s.map(c=>c.createdAt).reduce((c,l)=>si(c,l))}:{}}}function Ut(t,e={}){let r=(e.now?.()??new Date).getTime(),i=Math.max(0,e.retentionMs??ei),n=0;for(let s of q(v(t,ce))){let a=ue(s);!a||r-Date.parse(a.completedAt)<i||(O(s,{force:!0}),O(Kt(t,a.requestId),{force:!0}),n++)}return n>0&&(_(v(t,ce)),_(v(t,le))),Xt(t),n}function Ge(t){return $e(t,e=>{let r=e;return r.version===A&&F(r.requestId)&&(r.idempotencyKey===void 0||typeof r.idempotencyKey=="string")&&N(r.createdAt)&&N(r.deadlineAt)&&Date.parse(r.deadlineAt)>=Date.parse(r.createdAt)&&typeof r.detail=="string"&&r.detail.length>0})}function Ht(t){return $e(t,e=>{let r=e;return r.version===A&&F(r.requestId)&&F(r.claimId)&&N(r.claimedAt)})}function ue(t){return $e(t,e=>{let r=e;return r.version===A&&F(r.requestId)&&(r.claimId===void 0||F(r.claimId))&&(r.outcome==="completed"||r.outcome==="expired")&&N(r.completedAt)})}function zt(t,e){let r=Zt(t,e.requestId);if(Fe(t,r,e).published)return;let i=ue(r);if(!i||i.requestId!==e.requestId||i.outcome!==e.outcome)throw new Error(`Watch refresh completion ${e.requestId} conflicts with an existing record.`)}function Fe(t,e,r,i){let n=v(t,Gt),s=Qr(e),a=xe(n),o=xe(s),c=v(n,`${Kr(e)}.${process.pid}.${je()}.tmp`);try{let l=Z(c,r,{spacing:2,trailingNewline:!0});i?.("after-staged");try{Jr(c,e)}catch(d){if(d.code==="EEXIST")return{published:!1};throw d}let u=nt(a,o,l.directorySync,_(s));return i?.("after-published"),{published:!0,achievedDurability:u==="synced"?"directory-durable":"file-flushed",directorySync:u}}finally{O(c,{force:!0})}}function Yt(t){let e=[];for(let r of q(v(t,le))){let i=Ge(r);i&&e.push(i)}return e}function Jt(t,e,r){let i=Qt(t,e),n=Ht(i);!n||n.claimId!==r||(O(i,{force:!0}),_(v(t,G)))}function Xt(t){for(let e of q(v(t,Gt),".tmp"))O(e,{force:!0})}function ti(t,e){return q(t).filter(r=>!e(r)).length}function q(t,e=".json"){return Yr(t)?Xr(t,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.endsWith(e)).map(r=>v(t,r.name)).sort():[]}function $e(t,e){try{let r=JSON.parse(E(t,"watch refresh request record"));return e(r)?r:null}catch{return null}}function Kt(t,e){return v(t,le,`${e}.json`)}function Qt(t,e){return v(t,G,`${e}.json`)}function Zt(t,e){return v(t,ce,`${e}.json`)}function Nt(t,e){return ue(Zt(t,e))!==null}function ri(t){if(t===void 0)return Zr;if(!Number.isFinite(t)||t<=0)throw new Error("Watch refresh request ttlMs must be positive.");return Math.floor(t)}function ii(t){let e=t?.trim();return e?e.slice(0,512):void 0}function F(t){return typeof t=="string"&&/^[a-z0-9][a-z0-9-]{0,127}$/i.test(t)}function ni(t,e){return Date.parse(t.createdAt)-Date.parse(e.createdAt)||t.requestId.localeCompare(e.requestId)}function si(t,e){return Date.parse(e)<Date.parse(t)?e:t}var ci=6e3,li=1e3,tr=10;function nr(t,e,r){let i=Pe(Ue(t));if(r&&Pe(r.projectRoot)===i)return{projectRoot:i,worktreeKind:"git",worktreeId:r.worktreeId,cliVersion:e};let n=lt(i);if(n.kind==="error")throw new Error(`Could not establish Git worktree identity for ${i}: ${n.message}`);return n.kind==="non-git"?{projectRoot:i,worktreeKind:"non-git",cliVersion:e}:{projectRoot:i,worktreeKind:"git",worktreeId:n.identity.worktreeId,cliVersion:e}}function sr(t){let e=t.runtime??hi,r=L(t.cacheDir),i=Wt(r.statePath),n=i?e.isProcessAlive(i.pid)?{kind:"live",state:i}:{kind:"stale",state:i,reason:"dead-process"}:{kind:"stopped"},s=di("stop",n);if(s.kind==="signal-stop")return rr(s.state,t,e),Be(r,s.state.pid,e),{disposition:"stopped",pid:s.state.pid};if(s.kind==="clean-stale")return Be(r,s.state.pid,e),{disposition:"stopped",pid:s.state.pid};let a=lr(r.lockPath);return s.kind==="already-stopped"&&a&&e.isProcessAlive(a.pid)?(rr(a,t,e),Be(r,a.pid,e),{disposition:"stopped",pid:a.pid}):{disposition:"already-stopped"}}function or(t,e,r={}){let{durability:i="durable",...n}=r;i==="durable"?Z(t,e,n):Q(t,e,n)}function ar(t){try{let e=JSON.parse(E(t,"watch activity record"));return e.version!==1||!re(e.at)||e.refreshRequestedAt!==void 0&&!re(e.refreshRequestedAt)||e.refreshDetail!==void 0&&typeof e.refreshDetail!="string"?null:{atMs:Date.parse(e.at),...e.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(e.refreshRequestedAt)},...e.refreshDetail===void 0?{}:{refreshDetail:e.refreshDetail}}}catch{return null}}function cr(t,e,r={}){let i=r.pid??process.pid,n=r.isProcessAlive??I,s=()=>{},a=r.readProcessIdentity??x,o=r.now??(()=>new Date),c={...Ce,wallNow:()=>o().getTime(),isProcessAlive:n,readProcessIdentity:a},l=ht(t,{kind:"watch",pid:i,processIdentity:a(i),detail:{projectRoot:Ue(e)},parseLegacy:he,runtime:c});if(l.kind==="contended"){let u=dr(l.observation);return{acquired:!1,lockPath:t,message:ui(t,e,u),release:s}}return{acquired:!0,lockPath:t,message:"",release:()=>{l.lock.release()}}}function lr(t){return dr(Me(t,{parseLegacy:he}))}var he=t=>{let e=ur(t);return e?{pid:e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{}}:null};function dr(t){if(t.state==="valid"&&t.record?.kind==="watch"){let e=t.record.detail?.projectRoot;return typeof e!="string"?null:{version:1,pid:t.record.pid,...t.record.processIdentity?{processIdentity:t.record.processIdentity}:{},projectRoot:e,startedAt:t.record.startedAt}}return ur(t.parsed)}function ur(t){try{let e=t;if(e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!re(e.startedAt))return null;let r=e.processIdentity===void 0?null:at(e.processIdentity);return e.processIdentity!==void 0&&(!r||r.pid!==e.pid)?null:{version:1,pid:e.pid,...r?{processIdentity:r}:{},projectRoot:e.projectRoot,startedAt:e.startedAt}}catch{return null}}function di(t,e){switch(t){case"status":return{kind:"report",classification:e};case"ensure":switch(e.kind){case"stopped":return{kind:"start"};case"stale":return e.reason==="old-heartbeat"?{kind:"refuse-replace",state:e.state,reason:"old-heartbeat"}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return Ve(e)}case"stop":switch(e.kind){case"stopped":return{kind:"already-stopped"};case"stale":return e.reason==="old-heartbeat"?{kind:"signal-stop",state:e.state}:{kind:"clean-stale",state:e.state};case"live":case"incompatible":return{kind:"signal-stop",state:e.state};default:return Ve(e)}default:return Ve(t)}}function hr(t){return t.idleTimeoutMs===0||t.watcher.state!=="idle"?!1:t.nowMs-t.lastActivityAtMs>=t.idleTimeoutMs}function rr(t,e,r){let{pid:i}=t;if(!r.isProcessAlive(i))return;ir(t,r),r.signalProcess(i);let n=e.stopTimeoutMs??ci,s=r.monotonicNow??b,a=s()+n;for(;s()<=a;){if(!r.isProcessAlive(i))return;r.sleep(tr)}if(!r.forceSignalProcess)throw new Error(`scip-query watch service pid ${i} did not stop within ${n}ms and forced termination is unavailable.`);ir(t,r),r.forceSignalProcess(i);let o=e.forceStopTimeoutMs??li,c=s()+o;for(;s()<=c;){if(!r.isProcessAlive(i))return;let l=r.readProcessIdentity(i);if(t.processIdentity&&l&&!Te(t.processIdentity,l))return;r.sleep(tr)}throw new Error(`scip-query watch service pid ${i} remained alive ${o}ms after forced termination.`)}function Be(t,e,r){if(er(t.statePath,{force:!0}),er(t.activityPath,{force:!0}),lr(t.lockPath)?.pid===e&&!r.isProcessAlive(e)){let n={...Ce,wallNow:r.now,isProcessAlive:r.isProcessAlive,readProcessIdentity:r.readProcessIdentity},s=Me(t.lockPath,{parseLegacy:he,runtime:n});pt(t.lockPath,s,{parseLegacy:he,runtime:n})}}function ui(t,e,r){return`error: scip-query watch is already running for ${Ue(e)}${r?` (pid ${r.pid}, started ${r.startedAt}; lock: ${t})`:` (lock: ${t})`}. Stop that watcher before starting another.`}var hi={now:Date.now,monotonicNow:b,isProcessAlive:I,readProcessIdentity:x,spawnServer(t,e,r,i){if(!ai(t))throw new Error(`Watch service helper was not found at ${t}. Run npm run build first.`);oi(process.execPath,[t,e,r,JSON.stringify(i)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(t){process.kill(t,"SIGTERM")},forceSignalProcess(t){process.kill(t,"SIGKILL")},sleep(t){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,t)}};function ir(t,e){if(!t.processIdentity)throw new Error(`Refusing to signal scip-query watch pid ${t.pid}: its ownership record has no process identity.`);let r=e.readProcessIdentity(t.pid);if(!r)throw new Error(`Refusing to signal scip-query watch pid ${t.pid}: its process identity is unavailable.`);if(!Te(t.processIdentity,r))throw new Error(`Refusing to signal scip-query watch pid ${t.pid}: its process identity does not match the ownership record.`)}function Ve(t){throw new Error(`Unhandled watch service value: ${JSON.stringify(t)}`)}import{existsSync as gr,lstatSync as pe,readdirSync as Sr,realpathSync as pr,rmSync as $,statSync as pi}from"fs";import{join as y,resolve as B,sep as fr}from"path";var fi=3600*1e3,mi=2*1024*1024*1024,gi=300*1e3;function Si(t){let e=t.leases.filter(o=>o.managed&&!o.live&&!o.busy),r=vi(t.leases,t.locks),i={};for(let o of t.generations)r.has(o.generationId)||(i[o.generationId]=o.unreferencedAt??t.nowMs);let n=t.generations.filter(o=>!r.has(o.generationId)).sort((o,c)=>i[o.generationId]-i[c.generationId]||o.generationId.localeCompare(c.generationId)),s=new Set;for(let o of n)t.nowMs-i[o.generationId]>=t.policy.generationTtlMs&&s.add(o.generationId);let a=t.generations.filter(o=>!s.has(o.generationId)).reduce((o,c)=>o+c.size,0);for(let o of n){if(a<=t.policy.budgetBytes)break;s.has(o.generationId)||(s.add(o.generationId),a-=o.size)}for(let o of s)delete i[o];return{deleteWorktrees:e,deleteGenerations:t.generations.filter(o=>s.has(o.generationId)),deleteLocks:t.locks.filter(o=>!o.live),deleteTemporaries:t.temporaries.filter(o=>!o.live),protectedGenerationIds:[...r].sort(),unreferencedSince:i}}function vi(t,e){let r=new Set(t.filter(i=>i.managed&&(i.live||i.busy)).flatMap(i=>[i.lease.baseGenerationId,i.lease.activeGenerationId]).filter(i=>i!==void 0));for(let i of e)i.live&&r.add(i.generationId);return r}function vr(t,e,r={}){if(!ot())return{kind:"disabled"};let i=ct(t);if(!i)return{kind:"unavailable"};let n=y(ke(),"repositories",i.repositoryId);if(!gr(n))return{kind:"unavailable"};let s=(r.now??Date.now)(),a=y(n,"gc-state.json"),o=wi(a);if(!r.force&&o&&s-Date.parse(o.lastSweepAt)<gi)return{kind:"throttled",sweptAt:o.lastSweepAt};let c=ft(n,{now:()=>s});if(!c)return{kind:"busy"};try{let l=yi(t,n,i.repositoryId,o?.unreferencedSince??{}),u=Si({nowMs:s,...l,policy:{generationTtlMs:r.policy?.generationTtlMs??fi,budgetBytes:r.policy?.budgetBytes??mi}}),d=0,m=0;for(let p of u.deleteWorktrees){if(!yr(p.lease))continue;let S=mt(y(p.lease.localCacheDir,"cache-lifecycle.lock"));if(S)try{if(ze(p.lease,!0))continue;try{sr({projectRoot:p.lease.projectRoot,cacheDir:p.lease.localCacheDir,cliVersion:e})}catch{continue}if(ze(p.lease,!0))continue;$(p.lease.localCacheDir,{recursive:!0,force:!0}),$(p.leasePath,{force:!0}),m+=1}finally{S.release()}}for(let p of u.deleteLocks)$(p.path,{force:!0});for(let p of u.deleteTemporaries)$(p.path,{recursive:!0,force:!0});for(let p of u.deleteGenerations)$(p.path,{recursive:!0,force:!0}),d+=p.size;gt(y(n,"evidence.db"));let h={kind:"swept",sweptAt:new Date(s).toISOString(),deletedWorktrees:m,deletedGenerations:u.deleteGenerations.length,deletedBytes:d,protectedGenerations:u.protectedGenerationIds.length},g={version:1,lastSweepAt:h.sweptAt,unreferencedSince:u.unreferencedSince,lastResult:h};return Q(a,g,{spacing:2,trailingNewline:!0}),h}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function yi(t,e,r,i){let n=new Set(dt(t).map(l=>B(l.path))),s=[];for(let l of He(y(e,"worktrees"))){if(!l.endsWith(".json"))continue;let u=y(e,"worktrees",l),d=Ri(u);if(!d)continue;let m=B(d.projectRoot);s.push({leasePath:u,lease:d,managed:d.repositoryId===r&&yr(d),live:n.has(m)||gr(m),busy:ze(d)})}let a=[];for(let l of He(y(e,"locks"))){let u=/^([a-f0-9]{64})\.lock$/.exec(l);if(!u)continue;let d=y(e,"locks",l),m=Ye(d),h=m!==void 0&&I(m),g=u[1];a.push({generationId:g,path:d,live:h})}let o=[],c=[];for(let l of He(y(e,"generations"))){let u=/^\.tmp-(\d+)-/.exec(l);if(u){let h=y(e,"generations",l),g=Number(u[1]);try{c.push({path:h,size:mr(h),live:Number.isSafeInteger(g)&&I(g)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let d=y(e,"generations",l),m;try{m=pe(d)}catch{continue}!m.isDirectory()||m.isSymbolicLink()||o.push({generationId:l,path:d,size:mr(d),...i[l]===void 0?{}:{unreferencedAt:i[l]}})}return{leases:s,generations:o,locks:a,temporaries:c}}function yr(t){if(t.ownershipChecksum!==Rt(t)||We(t.localCacheDir)!==We(st(t.projectRoot)))return!1;let e=B(ke()),r=B(y(e,"projects")),i=B(t.localCacheDir);if(!i.startsWith(`${r}${fr}`))return!1;try{let n=pe(e),s=pe(r),a=pe(i);if(!n.isDirectory()||n.isSymbolicLink()||!s.isDirectory()||s.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let o=pr(r);return pr(i).startsWith(`${o}${fr}`)}catch{return!1}}function ze(t,e=!1){for(let i of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let n=Ye(y(t.localCacheDir,i));if(n!==void 0&&I(n))return!0}let r=Ye(L(t.localCacheDir).lockPath);return r!==void 0&&I(r)}function Ri(t){try{let e=JSON.parse(E(t,"worktree cache lease"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function Ye(t){try{let e=JSON.parse(E(t,"watch lock record"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function wi(t){try{let e=JSON.parse(E(t,"repository cache GC state"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function He(t){try{return Sr(t)}catch{return[]}}function mr(t){let e=0,r=[t];for(;r.length>0;){let i=r.pop();for(let n of Sr(i,{withFileTypes:!0})){let s=y(i,n.name);n.isDirectory()?r.push(s):n.isFile()&&(e+=pi(s).size)}}return e}var fe=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(e,r={}){this.root=e,this.now=r.now??Date.now,this.randomId=r.randomId,this.retryDelayMs=Math.max(1,Math.floor(r.retryDelayMs??1e3)),this.currentStatus=Ne(e)}initializeAfterOwnershipAcquired(){let e=Vt(this.root),r=Ut(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:e,prunedHistory:r}}observeLegacyRequest(e,r){Ft(this.root,r??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${e}`,now:()=>new Date(e)}),this.refreshStatus()}poll(e,r){if(this.active||e.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let i=$t(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),i.requests.length===0)return!1;this.active=i;try{return r(bi(i)),!0}catch(n){throw de(this.root,i),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),n}}completeActive(){return this.active?(Bt(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(de(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=Ne(this.root)}};function bi(t){if(t.requests.length===1)return t.requests[0].detail;let r=[...new Set(t.requests.map(i=>i.detail))].slice(0,3).join("; ");return`${t.requests.length} coalesced refresh requests${r?`: ${r}`:""}`.slice(0,2048)}import{randomUUID as xi}from"crypto";import{Worker as ki}from"worker_threads";var me=class{constructor(e){this.options=e;this.now=e.now??Date.now,this.setTimer=e.setTimer??setTimeout,this.clearTimer=e.clearTimer??clearTimeout}options;now;setTimer;clearTimer;worker=null;active=null;activeFailure=null;terminating=null;closed=!1;workerGeneration=0;canAccept(){return!this.closed&&this.active===null&&this.terminating===null}start(e){if(!this.canAccept())return!1;if(e.deadlineAtMs<this.now()){try{this.options.onReject(e,`${this.options.name} request expired before processing.`)}catch(s){this.closed=!0,this.options.onFatal(Je(s))}return!0}let r=this.ensureWorker(),i=Math.max(1,Math.min(2147483647,e.deadlineAtMs-this.now())),n=this.setTimer(()=>{this.failActiveAfterTermination(`${this.options.name} request exceeded its deadline.`)},i);this.active={request:e,timer:n};try{r.postMessage({kind:"request",...e})}catch(s){this.failActiveAfterTermination(Rr(s))}return!0}async close(e=`${this.options.name} service is shutting down.`){if(this.closed=!0,this.active){await this.failActiveAfterTermination(e);return}await this.terminateWorker()}ensureWorker(){if(this.worker)return this.worker;let e=this.options.createWorker(),r=++this.workerGeneration;return e.on("message",i=>this.handleMessage(r,i)),e.on("error",i=>{r===this.workerGeneration&&this.failActiveAfterTermination(`${this.options.name} worker failed: ${i.message}`)}),e.on("exit",i=>{r!==this.workerGeneration||this.terminating||(this.worker=null,this.active&&this.failActiveAfterTermination(`${this.options.name} worker exited unexpectedly with code ${i}.`))}),this.worker=e,e}handleMessage(e,r){if(e!==this.workerGeneration||this.closed||!this.active)return;let i=Ii(r);if(!i){this.failActiveAfterTermination(`${this.options.name} worker returned an invalid response.`);return}if(i.requestId!==this.active.request.requestId){this.failActiveAfterTermination(`${this.options.name} worker returned a mismatched request identity.`);return}if(this.now()>this.active.request.deadlineAtMs){this.failActiveAfterTermination(`${this.options.name} request expired while it was processing.`);return}let n=this.active;try{this.options.onStatus(i.status),i.ok?this.options.onComplete(n.request,i.result,i.status):this.options.onReject(n.request,i.error,i.status)}catch(s){this.closed=!0,this.clearTimer(n.timer),this.options.onFatal(Je(s));return}this.releaseActive(n)}async failActiveAfterTermination(e){if(this.activeFailure){await this.activeFailure;return}let r=this.active;if(!r){await this.terminateWorker();return}this.clearTimer(r.timer);let i=(async()=>{if(await this.terminateWorker()){try{this.options.onReject(r.request,e)}catch(s){this.closed=!0,this.options.onFatal(Je(s));return}this.releaseActive(r)}})();this.activeFailure=i;try{await i}finally{this.activeFailure===i&&(this.activeFailure=null)}}releaseActive(e){this.active===e&&(this.active=null,this.clearTimer(e.timer))}async terminateWorker(){if(this.terminating)return this.terminating;let e=this.worker;if(!e)return!0;this.worker=null;let r=++this.workerGeneration;return this.terminating=(async()=>{try{return await e.terminate(),!0}catch(i){return this.closed=!0,this.options.onFatal(new Error(`${this.options.name} worker termination failed: ${Rr(i)}`,{cause:i})),!1}finally{r===this.workerGeneration&&(this.terminating=null)}})(),this.terminating}};function Ii(t){if(!t||typeof t!="object")return null;let e=t;if(e.kind!=="response"||typeof e.requestId!="string"||!("status"in e))return null;if(e.ok===!0){if(!("result"in e)||"error"in e)return null}else if(e.ok===!1){if("result"in e||typeof e.error!="string")return null}else return null;return e}function Je(t){return t instanceof Error?t:new Error(String(t))}function Rr(t){return t instanceof Error?t.message:String(t)}function wr(t){let e=()=>({protocolVersion:te,state:"idle",requests:0,sessionsCreated:0,sessionsReplaced:0,initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0});return Ir({name:"TypeScript index",paths:t.paths,now:t.now,limits:t.limits,initialStatus:e,parseEnvelope:kt,createWorker:()=>xr(t,{kind:"index",projectRoot:t.projectRoot,dbPath:t.dbPath}),complete(r,i,n,s){Ae(t.paths,r,{ok:!0,protocolVersion:te,id:i.id,baseGeneration:i.baseGeneration,response:n},{nowMs:s,limits:t.limits})},reject(r,i,n,s){qe(t.paths,r,{ok:!1,protocolVersion:te,id:i,error:n},n,{nowMs:s,limits:t.limits})},onBusy:t.onBusy,onFatal:t.onFatal})}function br(t){let e=()=>({protocolVersion:se,state:"idle",requests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0});return Ir({name:"TypeScript semantic",paths:t.paths,now:t.now,limits:t.limits,initialStatus:e,parseEnvelope:At,createWorker:()=>xr(t,{kind:"semantic",projectRoot:t.projectRoot}),complete(r,i,n,s){Ae(t.paths,r,{ok:!0,protocolVersion:se,id:i.id,generation:i.generation,response:n},{nowMs:s,limits:t.limits})},reject(r,i,n,s){qe(t.paths,r,{ok:!1,protocolVersion:se,id:i,error:n},n,{nowMs:s,limits:t.limits})},onBusy:t.onBusy,onFatal:t.onFatal})}function Ir(t){let e=t.now??Date.now,r=x(process.pid),i={pid:process.pid,...r?{processIdentity:r}:{}},n=`${t.name.toLowerCase().replaceAll(" ","-")}-${process.pid}-${xi()}`,s={...t.limits,maxBatch:1},a=null,o=t.initialStatus(),c=!1,l=h=>{c=!0,t.onFatal(h)},u=new me({name:t.name,createWorker:t.createWorker,now:e,onComplete(h,g,p){let S=d(h.requestId);o=p,t.complete(S.claim,S.envelope,g,e()),m(S)},onReject(h,g,p){let S=d(h.requestId);p!==void 0&&(o=p),t.reject(S.claim,S.envelope.id,g,e()),m(S)},onStatus(h){o=h},onFatal:l});return{poll(){if(c||!u.canAccept())return 0;let h=wt(t.paths,{ownerId:n,nowMs:e(),limits:s,owner:i,liveness:{isProcessAlive:I,readProcessIdentity:x}})[0];if(!h)return 0;let g=h.requestId;try{let p=t.parseEnvelope(bt(h,s));if(g=p.id,p.id!==h.requestId)throw new Error(`${t.name} request identity does not match its mailbox path.`);if(p.deadlineAtMs<e())throw new Error(`${t.name} request expired before processing.`);if(a={claim:h,envelope:p},t.onBusy?.(p.deadlineAtMs),!u.start({requestId:p.id,deadlineAtMs:p.deadlineAtMs,payload:p}))throw new Error(`${t.name} worker lane closed admission after claiming a request.`)}catch(p){let S=Ti(p);try{t.reject(h,g,S,e()),a?.claim===h&&m(a)}catch(k){l(Wi(k))}}return 1},status(){return{...o,mailbox:It(t.paths)}},async close(h){await u.close(h)}};function d(h){let g=a;if(!g||g.envelope.id!==h)throw new Error(`${t.name} parent lost the active mailbox claim.`);return g}function m(h){a===h&&(a=null,t.onBusy?.(void 0))}}function xr(t,e){if(t.createWorker)return t.createWorker(e);let r=t.workerUrl??new URL("./typescript-mailbox-worker.js",import.meta.url);return new ki(r,{workerData:e})}function Wi(t){return t instanceof Error?t:new Error(String(t))}function Ti(t){return t instanceof Error?t.message:String(t)}var Ci=1e3,Mi=250,Ai=6e4,qi=10,_i=50,Li=250;function Oi(t,e=1){if(t>0)return qi;let r=Math.max(0,Math.min(3,e-1));return Math.min(Li,_i*2**r)}async function Di(t,e){let r=e.processIndexRequests(),i=e.processSemanticRequests(),n=r+i,s=n>0?0:t+1;if(e.afterMailboxPoll({indexRequests:r,semanticRequests:i,processedRequests:n}),e.shouldStop())return{indexRequests:r,semanticRequests:i,processedRequests:n,consecutiveIdlePolls:s,stopped:!0};let a=Oi(n,s);return await e.wait(a),{indexRequests:r,semanticRequests:i,processedRequests:n,consecutiveIdlePolls:s,stopped:!1,delayMs:a}}function ji(t){return t==="fresh"?null:{kind:"watch-startup",detail:`index ${t} when watch service started`}}async function Ni(t,e,r={}){let i=nr(t,e),n=i.projectRoot,s=ie(n);s.watch={...s.watch,...r};let a=ne(s);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let o=K(n,s),c=L(o.cacheDir),l=x(R.pid),u=cr(c.lockPath,n,{readProcessIdentity:f=>f===R.pid?l:x(f)});if(!u.acquired)return;let d=new fe(c.refreshRequestsPath,{retryDelayMs:Math.max(1e3,a.cooldownMs)});d.initializeAfterOwnershipAcquired();let m=Date.now(),h=b(),g=m,p=h,S={state:"idle"},k,V,W,U,ge=ee(o.dbPath),Se=!1,Xe=!1,Ke=0,Qe=Number.NEGATIVE_INFINITY,Ze=Number.NEGATIVE_INFINITY,et=Number.NEGATIVE_INFINITY,tt=Number.NEGATIVE_INFINITY,ve,ye,rt=0,Re=Mt(o.cacheDir),we=xt(o.cacheDir);qt(Re),Ct(we);let w=(f=!1,C=f?"durable":"visibility")=>{if(!Xe)return;let J=Date.now(),X=b();!f&&X-Qe<Ci||(Qe=X,or(c.statePath,{version:1,protocolVersion:Le,pid:R.pid,...l?{processIdentity:l}:{},projectRoot:n,...i.worktreeId?{worktreeId:i.worktreeId}:{},cliVersion:e,startedAt:new Date(m).toISOString(),heartbeatAt:new Date(J).toISOString(),lastActivityAt:new Date(g).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(g+a.idleTimeoutMs).toISOString()},watcher:S,...S.state==="idle"&&k?{indexGeneration:k}:{},...V?{lastRefresh:V}:{},...W?{lastError:W}:{},reindexActivity:ge,refreshRequests:d.status(),typescriptSemantic:{...be.status(),...ve===void 0?{}:{busyUntil:new Date(ve).toISOString()}},typescriptIndex:{...Ie.status(),...ye===void 0?{}:{busyUntil:new Date(ye).toISOString()}}},{durability:C}))},P=()=>{g=Date.now(),p=b()},it=f=>{P(),U??=f,W={at:new Date().toISOString(),message:f.message},w(!0,"visibility")},be=br({paths:Re,projectRoot:n,onBusy(f){ve=f===void 0?void 0:f+5e3,w(!0,"visibility")},onFatal:it}),Ie=wr({paths:we,projectRoot:n,dbPath:o.dbPath,onBusy(f){ye=f===void 0?void 0:f+5e3,w(!0,"visibility")},onFatal:it}),H=new ae({projectRoot:n,config:{...s,watch:a},languages:s.languages,onStatus(f){S=f,f.state!=="idle"&&(k=void 0),f.state!=="idle"&&P(),w(!0)},onReindexComplete(){P();let f=Oe(n,s,o);return V=f.lastRefresh,k=f.state==="fresh"?De(o.dbPath)??void 0:void 0,ge=ee(o.dbPath),d.completeActive(),W=void 0,w(!0),f.state==="fresh"},onReindexError(){d.failActive()},onRefreshSuppressed(f){let C=yt(o.dbPath,f);C.state==="failed"&&(W={at:new Date().toISOString(),message:`Suppressed-refresh telemetry was not recorded: ${C.reason}`},w(!0,"visibility")),ge=ee(o.dbPath)},onError(f){P(),k=void 0,W={at:new Date().toISOString(),message:f.message},w(!0)}}),z=()=>{Se=!0};R.once("SIGINT",z),R.once("SIGTERM",z);let D=!1,Y,j;try{H.start();let f=Oe(n,s,o);V=f.lastRefresh,k=f.state==="fresh"?De(o.dbPath)??void 0:void 0;let C=ji(f.state);for(C&&H.requestRefresh(C,{immediate:!0}),P(),Xe=!0,w(!0);!Se;){let J=await Di(rt,{processIndexRequests:()=>Ie.poll(),processSemanticRequests:()=>be.poll(),afterMailboxPoll:({processedRequests:X})=>{let M=b();if(M-tt>=Ai&&(tt=M,_e(we),_e(Re)),M-et>=6e4&&(et=M,vr(n,e)),M-Ze>=Mi){Ze=M;let T=ar(c.activityPath);T&&T.atMs>g&&(g=T.atMs,p=M),T?.refreshRequestedAtMs!==void 0&&T.refreshRequestedAtMs>Ke&&(Ke=T.refreshRequestedAtMs,d.observeLegacyRequest(T.refreshRequestedAtMs,T.refreshDetail??"stale index observed by a legacy command")),d.poll(S,Wr=>{P(),H.requestRefresh({kind:"watch-demand",detail:Wr},{immediate:!0})})}X>0&&(P(),w(!0,"visibility")),w()},shouldStop:()=>Se||U!==void 0||hr({watcher:S,lastActivityAtMs:p,nowMs:b(),idleTimeoutMs:a.idleTimeoutMs}),wait:Gi});if(rt=J.consecutiveIdlePolls,J.stopped)break}}catch(f){D=!0,Y=f}finally{R.off("SIGINT",z),R.off("SIGTERM",z),await Promise.all([be.close("TypeScript semantic service stopped before completing the request."),Ie.close("TypeScript index service stopped before completing the request.")]);let f=await H.stop();f.state==="stopped"?(kr(c.statePath,{force:!0}),kr(c.activityPath,{force:!0}),u.release()):(W={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${f.reasons.join("; ")}`},w(!0),j=new Error(W.message))}if(!D&&U&&(D=!0,Y=U),D&&j)throw new AggregateError([Y,j],"Watch service execution and shutdown both failed.");if(D)throw Y;if(j)throw j}function Gi(t){return new Promise(e=>setTimeout(e,t))}function Fi(t,e={report:r=>console.error(r),exit:r=>R.exit(r)}){return e.report(`watch-service: ${Pt(t instanceof Error?t.message:String(t))}`),e.exit(1)}var $i=R.argv[1]?Pi(Ei(R.argv[1])).href:null;if($i===import.meta.url){let t=R.argv[2],e=R.argv[3],r=Bi(R.argv[4]);if(!t||!e)console.error("watch-service: expected <project-root> <cli-version>"),R.exitCode=1;else try{await Ni(t,e,r)}catch(i){Fi(i)}}function Bi(t){if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}export{Di as runWatchServiceLoopIteration,Ni as runWatchServiceServer,ji as startupRefreshTrigger,Fi as terminateWatchServiceProcess,Oi as watchServiceLoopDelayMs};
43
3
  //# sourceMappingURL=watch-server.js.map
@@ -25,7 +25,8 @@ For analyzer implementation work, follow [Regex Policy](REGEX_POLICY.md): regex
25
25
  install state, smoke tests, health score, issue list, health dossier paths,
26
26
  and setup verdict. A project with no watch decision is enabled; an existing
27
27
  explicit `watch.enabled: false` is preserved. Use `scip-query setup --guided`
28
- for a recommended automatic-indexing choice, or
28
+ in an interactive terminal for a recommended automatic-indexing choice, use
29
+ `scip-query setup --yes` for automatic defaults, or
29
30
  `scip-query setup --no-hooks --json` when the repo should not write Codex or
30
31
  Claude Code lifecycle hooks. Non-interactive setup and ordinary reindex
31
32
  diagnose missing global tools without installing them. Pass
@@ -39,8 +40,8 @@ For analyzer implementation work, follow [Regex Policy](REGEX_POLICY.md): regex
39
40
  gate run changes them. Checkout preferences configure only one clone, so do
40
41
  not commit `.codex/hooks.json` or `.claude/settings.local.json`; setup keeps
41
42
  them out of Git through `.git/info/exclude`. User-environment changes install
42
- skills or indexers for the current machine. Use `setup --guided` to answer
43
- each repository, checkout, or user-scope question separately; use
43
+ skills or indexers for the current machine. Use `setup --guided` from a TTY
44
+ to answer each repository, checkout, or user-scope question separately; use
44
45
  `setup --install-missing` for an explicit non-interactive installation
45
46
  grant.
46
47
 
@@ -472,10 +473,16 @@ Numeric thresholds below are recommended starting points for review sessions; co
472
473
  - **Retrieve complete output**: an incomplete page is not evidence. Before
473
474
  making a conclusion, changing to another evidence command, or reporting
474
475
  completion, run every emitted `Continue exactly:` command unchanged until
475
- `complete: true`. Never pipe scip-query through `head`, `tail`, or a
476
- line-range `sed`. The universal `--output-cursor` pages the
476
+ the human footer reports transport completion or a JSON page reports
477
+ `complete: true`. Transport completion means every rendered character was
478
+ retrieved; it does not make bounded command coverage exhaustive. Never pipe
479
+ scip-query through `head`, `tail`, or a line-range `sed`. The universal `--output-cursor` pages the
477
480
  rendered output; a result cursor such as `refs --cursor` advances logical
478
- query coverage and is a separate obligation.
481
+ query coverage and is a separate obligation. Follow every `refs --cursor`
482
+ continuation before claiming all references. Ordinary limited reference
483
+ pages resume by `(path, line)` without rebuilding prior pages; JSON reports
484
+ `pagination.producer: "complete-only"` when the selected evidence provider
485
+ had to materialize the complete answer despite the result limit.
479
486
  - **Use `--json` on `health`** for programmatic consumption — parse the JSON to make decisions
480
487
  - **Run `change-surface` before every file modification** — it takes <1 second and prevents surprises
481
488
  - **Run `diff-impact --json` before committing** — catches unexpected blast radius across downstream consumers
@@ -1,4 +1,30 @@
1
- # CLI JSON output contract
1
+ # CLI output modes
2
+
3
+ Human output is the default for people and agents. It is the command-owned
4
+ presentation: reports retain sections and whitespace, and `code` retains a
5
+ path/range header, source indentation, and one-based line numbers. It omits
6
+ transport metadata that does not help answer the command's question.
7
+
8
+ Public commands that support structured output share the same three options:
9
+
10
+ ```text
11
+ --json Emit the stable versioned CLI envelope.
12
+ --result-only With --json, emit only the command-owned result.
13
+ --compact With --json, minify the selected JSON form for a program.
14
+ ```
15
+
16
+ Use plain `--json` for an integration that depends on producer, schema,
17
+ coverage, evidence, arguments, or invocation options. Use `--json
18
+ --result-only` for a program that needs just the result. Agents should run the
19
+ ordinary command instead; pretty JSON remains structurally noisier than the
20
+ human renderer. Both modifiers are rejected without `--json`.
21
+
22
+ For example, `scip-query code <symbol>` prints source directly. Its result-only
23
+ form contains only `file`, resolved `symbol`, `language`, a one-based `range`,
24
+ and ordered `{ line, text }` rows. Resolution alternatives are added only when
25
+ the requested symbol is ambiguous.
26
+
27
+ ## Stable JSON envelope
2
28
 
3
29
  A CLI JSON envelope is the public transport record printed by a scip-query
4
30
  command when a caller selects `--json`. Its real-world units are the JSON
@@ -13,12 +39,12 @@ The current envelope is schema version 1:
13
39
  {
14
40
  "kind": "scip-query-result",
15
41
  "schemaVersion": 1,
16
- "producer": { "name": "scip-query", "version": "0.19.8" },
42
+ "producer": { "name": "scip-query", "version": "0.20.0" },
17
43
  "command": "refs",
18
44
  "resultSchemaVersion": 1,
19
45
  "evidence": "graph-fact",
20
46
  "args": ["login"],
21
- "options": { "json": true, "compact": true },
47
+ "options": { "json": true },
22
48
  "result": {},
23
49
  "coverage": {}
24
50
  }
@@ -53,14 +79,23 @@ Every command accepts these global options:
53
79
  --output-cursor <cursor>
54
80
  ```
55
81
 
56
- Human output larger than 12,000 characters is paged automatically. The page
57
- prints its exact continuation command both before and after its content.
58
- Agents must run that command unchanged and continue until the page reports
59
- completion. Do not pipe scip-query through `head`, `tail`, or a line-range
60
- `sed`; those programs discard output without creating a resumable position.
82
+ Run commands normally without choosing a page size. Human output larger than
83
+ 12,000 characters is paged automatically as ordinary multiline text, not as a
84
+ JSON object. Each incomplete page prints one exact continuation command after
85
+ its content. Agents must run that command unchanged until the output-complete
86
+ marker. Supplying `--output-page-size` changes the character budget; it does
87
+ not select JSON. The value counts rendered JavaScript string characters, not
88
+ rows, results, model tokens, or bytes. If the complete result fits, scip-query
89
+ returns it unchanged and removes the temporary snapshot; a page wrapper exists
90
+ only when more content remains. Partial human pages end at the last complete
91
+ line within that budget whenever one exists, so the next page begins with its
92
+ own heading or source line number; a single line longer than the budget is the
93
+ only case that requires a character-boundary split. Do not pipe scip-query
94
+ through `head`, `tail`, or a line-range `sed`; those programs discard output
95
+ without creating a resumable position.
61
96
 
62
- Default `--json` output remains the ordinary `scip-query-result` envelope
63
- byte-for-byte so existing scripts are not broken. When that envelope exceeds
97
+ Default `--json` output remains the ordinary, additively extensible
98
+ `scip-query-result` envelope. When that envelope exceeds
64
99
  12,000 characters, scip-query writes an early stderr warning containing the
65
100
  exact command that opts into output pages. The paged command returns:
66
101
 
@@ -68,7 +103,7 @@ exact command that opts into output pages. The paged command returns:
68
103
  {
69
104
  "kind": "scip-query-output-page",
70
105
  "schemaVersion": 1,
71
- "producer": { "name": "scip-query", "version": "0.19.8" },
106
+ "producer": { "name": "scip-query", "version": "0.20.0" },
72
107
  "command": "architecture",
73
108
  "contentType": "application/json",
74
109
  "agentInstruction": "INCOMPLETE EVIDENCE: do not draw conclusions or report completion from this partial page. Run page.continuation.command exactly, then repeat until page.complete is true.",
@@ -89,17 +124,26 @@ exact command that opts into output pages. The paged command returns:
89
124
  }
90
125
  ```
91
126
 
92
- The cursor is bound to the command, working directory, complete
93
- non-pagination argument list, next character offset, private output snapshot,
94
- and SHA-256 of the complete rendered output. SHA-256 is a fixed-size content
95
- fingerprint: the same bytes produce the same identity with overwhelming
96
- reliability. A continuation reads the immutable snapshot rather than re-running
97
- the command, so timestamps, durations, edits, or reindexes cannot mix
98
- different result generations between pages. Missing, expired, or changed
99
- snapshot data is rejected with the exact command that restarts at page one.
100
- Every incomplete machine-readable page also carries a direct
101
- `agentInstruction`. A partial page is not sufficient evidence for a conclusion
102
- or completion claim; consumers must follow `page.continuation.command` until
127
+ The cursor is bound to the executable or package-runner prefix, command,
128
+ working directory, complete non-pagination argument list, immutable page
129
+ number and size, private output snapshot, and SHA-256 of the complete rendered
130
+ output. The initial capture records that invocation identity plus each page's
131
+ UTF-8 byte range and hash. A continuation reads and verifies only that range,
132
+ so retrieving all pages performs linear snapshot I/O and never re-runs the
133
+ command. A changed executable identity, page, page size, missing snapshot, or
134
+ expired snapshot is rejected with the exact page-one restart command using the
135
+ same prefix that created it.
136
+
137
+ A genuinely partial JSON page must carry `content` as a string because an
138
+ arbitrary character boundary is not necessarily valid nested JSON. Run the
139
+ emitted continuation exactly until completion. Normal agent work should use
140
+ human output, where partial pages remain multiline text rather than a JSON
141
+ string.
142
+
143
+ One snapshot is bounded to 32 million characters, 64 MiB, and 32,768 pages.
144
+ The per-user pool is bounded to 32 snapshots and 256 MiB under atomic
145
+ reservation. Every incomplete machine-readable page carries a direct
146
+ `agentInstruction`; consumers must follow `page.continuation.command` until
103
147
  `page.complete` is `true`.
104
148
 
105
149
  Output pages and result coverage answer different questions:
@@ -112,6 +156,27 @@ A completely retrieved page can therefore still contain a bounded or sampled
112
156
  analysis. Use the result envelope's stated `--full` remediation when present,
113
157
  then follow output continuation commands until complete.
114
158
 
159
+ Invocation coverage counts the semantic result units declared by the command
160
+ descriptor. A list command counts top-level rows; a report counts one report;
161
+ and a command with a named result field counts only that field. Unrelated
162
+ diagnostic arrays do not inflate `returned`. Symbol-selecting commands also
163
+ report a separate `coverage.resolution` state—`exact`, `ambiguous`, or
164
+ `missing` with its candidate count—because resolving one requested identity
165
+ and enumerating that identity's result rows are different completeness
166
+ questions.
167
+
168
+ `refs --limit <n>` uses a generation-bound keyset cursor: each ordinary page
169
+ continues after the last returned `(relativePath, line)` and stops once it has
170
+ found the requested rows plus one continuation witness. The JSON result reports
171
+ `pagination.producer: "source-keyset"` for that bounded producer. Explicit
172
+ semantic enrichment (`--full`), Ruby supplemental evidence, and the coarse SCIP
173
+ chunk fallback cannot currently resume before complete materialization; those
174
+ pages preserve their evidence but report
175
+ `pagination.producer: "complete-only"` instead of implying that `--limit`
176
+ bounded the analysis work. Version-1 offset cursors remain readable and their
177
+ next continuation is upgraded to the version-2 keyset format. Every result
178
+ cursor is rejected after the index generation changes.
179
+
115
180
  The machine-readable page schema is
116
181
  [`schemas/cli-output-page.schema.json`](schemas/cli-output-page.schema.json).
117
182
  Page sizes range from 256 through 100,000 characters and cursors are limited
@@ -144,6 +209,29 @@ The committed v0 and v1 fixtures in `tests/fixtures/` prove that the newest
144
209
  decoder reads both generations. The v1 fixture also contains an unknown
145
210
  additive field so tests prove tolerant reads rather than exact-key coupling.
146
211
 
212
+ ## Effectiveness telemetry authority
213
+
214
+ `effectiveness --json` reports both handling outcomes and the authority of the
215
+ observer that produced them. Repository-local agents and humans can edit the
216
+ same `.scipquery/events/` and suppression files being summarized, so their
217
+ rows use `authority: "local-writable-telemetry"` and expose
218
+ `resolutionVsSuppressionRate`. The legacy `precision` result field remains
219
+ present but is `null` for writable, mixed, or self-asserted populations. It is
220
+ numeric only when every event in that population is a `protected-ci`
221
+ observation with `protected-external` authority and the caller supplies its
222
+ gate-run ID through a separately controlled attestation set. The built-in
223
+ repository-history command supplies no such set, so writable JSON cannot
224
+ self-promote into an independent grade. External evaluators can call the
225
+ public `computeEffectiveness()` export from `scip-query/queries` with
226
+ `protectedGateRunIds` obtained from their separately controlled corpus.
227
+
228
+ The result also includes observer counts, distinct and missing gate-run
229
+ identities, and bounded anomaly samples. Those samples identify calibration
230
+ work without requiring a human to approve every ordinary automated
231
+ suppression. `recordCompatibility.outcomeEvents` remains the independent
232
+ statement about whether every event file was readable; neither compatibility
233
+ nor Git can prove that a writable event file was never deleted.
234
+
147
235
  ## Other JSON protocols
148
236
 
149
237
  The hidden `__health-phase` and `__diff-impact-batch` commands are