scip-query 0.19.6 → 0.19.10

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 (377) hide show
  1. package/CHANGELOG.md +116 -0
  2. package/README.md +156 -44
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/chunk-26QA6FAI.js +8 -0
  5. package/dist/{chunk-J7VT2CRB.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-2CVXCGL4.js → chunk-3CLX5EOX.js} +2 -2
  9. package/dist/{chunk-5OC3HWP5.js → chunk-3G66UZBH.js} +2 -2
  10. package/dist/{chunk-S2GP3CU3.js → chunk-3ORVDL3H.js} +2 -2
  11. package/dist/chunk-46XGSFNI.js +2 -0
  12. package/dist/chunk-4MAK2HOY.js +6 -0
  13. package/dist/chunk-4TURLRL5.js +16 -0
  14. package/dist/chunk-4UQVNCQE.js +2 -0
  15. package/dist/chunk-55Q3WLZX.js +2 -0
  16. package/dist/{chunk-OQ2A4G2G.js → chunk-5E4WNAVD.js} +2 -2
  17. package/dist/{chunk-YGQN3XGZ.js → chunk-5I5G2QOX.js} +2 -2
  18. package/dist/chunk-6LDJQXAH.js +2 -0
  19. package/dist/{chunk-WXAAURU7.js → chunk-6O5TICIZ.js} +2 -2
  20. package/dist/{chunk-OBKDTVZ3.js → chunk-6SHPK5ZE.js} +2 -2
  21. package/dist/chunk-7BAVHKMJ.js +49 -0
  22. package/dist/chunk-7O5IKBTZ.js +16 -0
  23. package/dist/chunk-7PIO7NKH.js +60 -0
  24. package/dist/chunk-7S5E7KWT.js +2 -0
  25. package/dist/{chunk-GK3GRUJX.js → chunk-7SQQWSY3.js} +2 -2
  26. package/dist/chunk-7WPLAODU.js +5 -0
  27. package/dist/chunk-A73XVBCR.js +20 -0
  28. package/dist/chunk-AFHORGLH.js +42 -0
  29. package/dist/chunk-AIE7TFJW.js +9 -0
  30. package/dist/chunk-AQOFWNQJ.js +1 -0
  31. package/dist/{chunk-MGBJHRFB.js → chunk-AZJQQKDD.js} +2 -2
  32. package/dist/{chunk-IYAOX36F.js → chunk-B2PX5I6M.js} +2 -2
  33. package/dist/{chunk-EVOC5I5I.js → chunk-B7PBSLZN.js} +2 -2
  34. package/dist/{chunk-ZLJLE6LK.js → chunk-BBW6JFHN.js} +2 -2
  35. package/dist/{chunk-NBRUH7OE.js → chunk-BDCC2NPY.js} +2 -2
  36. package/dist/{chunk-DD5BOU5I.js → chunk-BNXCIFVY.js} +2 -2
  37. package/dist/{chunk-FHCTEANE.js → chunk-BPAPWKP6.js} +2 -2
  38. package/dist/chunk-BS2NMXQZ.js +4 -0
  39. package/dist/chunk-C3KV2II6.js +2 -0
  40. package/dist/chunk-C43RDDP4.js +20 -0
  41. package/dist/{chunk-QBYYWGAT.js → chunk-CJST5ETY.js} +2 -2
  42. package/dist/chunk-DAFAHMNB.js +42 -0
  43. package/dist/chunk-DHEQMPLW.js +2 -0
  44. package/dist/{chunk-336DC5NJ.js → chunk-DQGFVPUV.js} +2 -2
  45. package/dist/chunk-DQLPXMH6.js +8 -0
  46. package/dist/chunk-EKZTZXHZ.js +117 -0
  47. package/dist/{chunk-KLVJABXA.js → chunk-EN3O7VJA.js} +2 -2
  48. package/dist/{chunk-U5CNPPTZ.js → chunk-EW2NTSFA.js} +2 -2
  49. package/dist/chunk-F3Z4OUDS.js +8 -0
  50. package/dist/chunk-FJH2NW7J.js +66 -0
  51. package/dist/{chunk-3OIKRYU5.js → chunk-FKSELJQF.js} +2 -2
  52. package/dist/chunk-FTFP6O3L.js +11 -0
  53. package/dist/chunk-FYLK2DEJ.js +2 -0
  54. package/dist/chunk-GH74ASD6.js +11 -0
  55. package/dist/{chunk-NQLSSVOB.js → chunk-GMXWZP2B.js} +2 -2
  56. package/dist/chunk-GOUBFH5O.js +3 -0
  57. package/dist/{chunk-RJHCPSZ7.js → chunk-HLF2TX6R.js} +2 -2
  58. package/dist/{chunk-PC44K7RF.js → chunk-HX4GQPZP.js} +2 -2
  59. package/dist/chunk-HX7M4BDI.js +30 -0
  60. package/dist/chunk-HZ72SESS.js +128 -0
  61. package/dist/{chunk-YTUD45PU.js → chunk-IB2N4FIY.js} +2 -2
  62. package/dist/chunk-ILMHV3KM.js +2 -0
  63. package/dist/chunk-IZYYAFN5.js +2 -0
  64. package/dist/{chunk-A43URCQ3.js → chunk-JAYYFEQY.js} +2 -2
  65. package/dist/{chunk-RWRLUZ6U.js → chunk-JDOEX4E6.js} +2 -2
  66. package/dist/chunk-JFGGXWQF.js +947 -0
  67. package/dist/chunk-JN4NMBEX.js +8 -0
  68. package/dist/{chunk-JELJLXEE.js → chunk-JVYA47YU.js} +2 -2
  69. package/dist/{chunk-F42A3AKG.js → chunk-JW56N3KI.js} +2 -2
  70. package/dist/{chunk-FQTPPXNA.js → chunk-JZ2OXNWB.js} +2 -2
  71. package/dist/chunk-KFZNKUNT.js +2 -0
  72. package/dist/chunk-KMKTIO2G.js +8 -0
  73. package/dist/chunk-L5GJNV2T.js +8 -0
  74. package/dist/{chunk-RBFFD4V2.js → chunk-L7AW2QB5.js} +2 -2
  75. package/dist/chunk-L7JDSCDF.js +4 -0
  76. package/dist/chunk-LU47HG23.js +14 -0
  77. package/dist/chunk-LVY7NPF7.js +2 -0
  78. package/dist/chunk-LY4WC4AD.js +74 -0
  79. package/dist/{chunk-MLGTCX56.js → chunk-MKCDWWGV.js} +2 -2
  80. package/dist/chunk-MNE7YG56.js +2 -0
  81. package/dist/{chunk-YWB2EBNB.js → chunk-MRXBEXSY.js} +2 -2
  82. package/dist/chunk-MV7OWDUX.js +2 -0
  83. package/dist/{chunk-2GSQR6YA.js → chunk-N5W4YZMK.js} +2 -2
  84. package/dist/chunk-NGEXCJJW.js +11 -0
  85. package/dist/{chunk-CYJM7CYF.js → chunk-NIW6JDC5.js} +2 -2
  86. package/dist/{chunk-YHXBD52M.js → chunk-O64IZ6UX.js} +2 -2
  87. package/dist/chunk-PBUQFCNB.js +16 -0
  88. package/dist/{chunk-UQK5CRUK.js → chunk-POAVPHH7.js} +2 -2
  89. package/dist/{chunk-TYQ76QHQ.js → chunk-PQCI4SQX.js} +2 -2
  90. package/dist/chunk-PXY7F6Y4.js +5 -0
  91. package/dist/chunk-RDO52JGY.js +2 -0
  92. package/dist/chunk-RJT3TUUZ.js +2 -0
  93. package/dist/{chunk-OHWZKLVA.js → chunk-RUJURYSV.js} +2 -2
  94. package/dist/{chunk-CSTYYXKC.js → chunk-RVLDN63O.js} +2 -2
  95. package/dist/chunk-RXOXSKY3.js +2 -0
  96. package/dist/chunk-S7OYBOCK.js +2 -0
  97. package/dist/chunk-SMNXQT5Z.js +3 -0
  98. package/dist/{chunk-QQWOFXNW.js → chunk-SRAFT254.js} +2 -2
  99. package/dist/{chunk-6XHTISLI.js → chunk-SXP2MBJH.js} +2 -2
  100. package/dist/chunk-T7YQSHPQ.js +3 -0
  101. package/dist/{chunk-2EZSOTSY.js → chunk-TFRAYKN6.js} +2 -2
  102. package/dist/{chunk-XVJ3V7LM.js → chunk-UJCOIXDY.js} +2 -2
  103. package/dist/{chunk-7LABSJSR.js → chunk-UJPRPGCO.js} +5 -5
  104. package/dist/chunk-W4ETQAXM.js +2 -0
  105. package/dist/chunk-WCCFZ7V7.js +113 -0
  106. package/dist/chunk-WUPW3UN3.js +3 -0
  107. package/dist/{chunk-VP542C25.js → chunk-WXZLAAWK.js} +2 -2
  108. package/dist/{chunk-LMFVTUW2.js → chunk-X54AGLVX.js} +2 -2
  109. package/dist/chunk-XKWKXZKW.js +20 -0
  110. package/dist/{chunk-OP3MTFJR.js → chunk-XSRF6Q77.js} +2 -2
  111. package/dist/chunk-Y2MVPNKY.js +5 -0
  112. package/dist/{chunk-6XFC7PQ5.js → chunk-YKUU5AIC.js} +2 -2
  113. package/dist/chunk-YLCJLTPL.js +2 -0
  114. package/dist/{chunk-47X75ZKH.js → chunk-YTQVETEO.js} +2 -2
  115. package/dist/chunk-Z4N3MZYA.js +38 -0
  116. package/dist/chunk-ZHXX42OH.js +18 -0
  117. package/dist/chunk-ZJOOT3BG.js +2 -0
  118. package/dist/chunk-ZK26BAQL.js +2 -0
  119. package/dist/{chunk-UUJBLG6J.js → chunk-ZTETIQ35.js} +2 -2
  120. package/dist/cli.js +3 -3
  121. package/dist/command-descriptors-4A4HWV4F.js +642 -0
  122. package/dist/{config-types-BWQ5xPGI.d.ts → config-types-jVM3D7MA.d.ts} +72 -2
  123. package/dist/{db-B0r1o7Vt.d.ts → db-B5PM5yNk.d.ts} +20 -2
  124. package/dist/{diff-gate-types-C9BoYwYD.d.ts → diff-gate-types-B0QYpDv1.d.ts} +2 -1
  125. package/dist/direct-navigation-6YHV6IB5.js +3 -0
  126. package/dist/{health-CFnlCiTz.d.ts → health-Do5TKSJI.d.ts} +1 -1
  127. package/dist/index.d.ts +3 -3
  128. package/dist/index.js +1 -1
  129. package/dist/postinstall.js +1 -1
  130. package/dist/queries/affected.d.ts +2 -2
  131. package/dist/queries/affected.js +1 -1
  132. package/dist/queries/architecture.d.ts +2 -2
  133. package/dist/queries/architecture.js +1 -1
  134. package/dist/queries/bottlenecks.d.ts +2 -2
  135. package/dist/queries/bottlenecks.js +1 -1
  136. package/dist/queries/by-kind.d.ts +2 -2
  137. package/dist/queries/by-kind.js +1 -1
  138. package/dist/queries/call-graph.d.ts +2 -2
  139. package/dist/queries/call-graph.js +1 -1
  140. package/dist/queries/change-surface.d.ts +22 -3
  141. package/dist/queries/change-surface.js +1 -1
  142. package/dist/queries/cleanup-plan.d.ts +2 -2
  143. package/dist/queries/cleanup-plan.js +1 -1
  144. package/dist/queries/co-change.d.ts +2 -2
  145. package/dist/queries/co-change.js +1 -1
  146. package/dist/queries/code.d.ts +2 -2
  147. package/dist/queries/code.js +1 -1
  148. package/dist/queries/complexity-hotspots.d.ts +3 -3
  149. package/dist/queries/complexity-hotspots.js +1 -1
  150. package/dist/queries/complexity.d.ts +3 -3
  151. package/dist/queries/complexity.js +1 -1
  152. package/dist/queries/convergence.d.ts +2 -2
  153. package/dist/queries/convergence.js +1 -1
  154. package/dist/queries/coupling.d.ts +2 -2
  155. package/dist/queries/coupling.js +1 -1
  156. package/dist/queries/cycles.d.ts +2 -2
  157. package/dist/queries/cycles.js +1 -1
  158. package/dist/queries/dataflow.d.ts +2 -2
  159. package/dist/queries/dataflow.js +1 -1
  160. package/dist/queries/dead.d.ts +2 -2
  161. package/dist/queries/dead.js +1 -1
  162. package/dist/queries/decorative-checkers.d.ts +2 -2
  163. package/dist/queries/decorative-checkers.js +1 -1
  164. package/dist/queries/deep-chains.d.ts +2 -2
  165. package/dist/queries/deep-chains.js +1 -1
  166. package/dist/queries/deps.d.ts +2 -2
  167. package/dist/queries/deps.js +1 -1
  168. package/dist/queries/diff-gate.d.ts +40 -7
  169. package/dist/queries/diff-gate.js +1 -1
  170. package/dist/queries/diff-impact.d.ts +84 -6
  171. package/dist/queries/diff-impact.js +1 -1
  172. package/dist/queries/doc-drift.d.ts +3 -3
  173. package/dist/queries/doc-drift.js +1 -1
  174. package/dist/queries/drift.d.ts +2 -2
  175. package/dist/queries/drift.js +1 -1
  176. package/dist/queries/duplicate-bodies.d.ts +3 -3
  177. package/dist/queries/duplicate-bodies.js +1 -1
  178. package/dist/queries/extract-candidates.d.ts +2 -2
  179. package/dist/queries/extract-candidates.js +1 -1
  180. package/dist/queries/fan.d.ts +2 -2
  181. package/dist/queries/fan.js +1 -1
  182. package/dist/queries/files.d.ts +12 -3
  183. package/dist/queries/files.js +1 -1
  184. package/dist/queries/health.d.ts +3 -3
  185. package/dist/queries/health.js +1 -1
  186. package/dist/queries/hierarchy.d.ts +2 -2
  187. package/dist/queries/hierarchy.js +1 -1
  188. package/dist/queries/hotspots.d.ts +2 -2
  189. package/dist/queries/hotspots.js +1 -1
  190. package/dist/queries/imports.d.ts +2 -2
  191. package/dist/queries/imports.js +1 -1
  192. package/dist/queries/incomplete-migration.d.ts +8 -6
  193. package/dist/queries/incomplete-migration.js +1 -1
  194. package/dist/queries/index.d.ts +141 -10
  195. package/dist/queries/index.js +1 -1
  196. package/dist/queries/isolated.d.ts +2 -2
  197. package/dist/queries/isolated.js +1 -1
  198. package/dist/queries/locality-candidates.d.ts +2 -2
  199. package/dist/queries/locality-candidates.js +1 -1
  200. package/dist/queries/members.d.ts +2 -2
  201. package/dist/queries/members.js +1 -1
  202. package/dist/queries/methods.d.ts +34 -3
  203. package/dist/queries/methods.js +1 -1
  204. package/dist/queries/not-implemented.d.ts +2 -2
  205. package/dist/queries/not-implemented.js +1 -1
  206. package/dist/queries/outline.d.ts +2 -2
  207. package/dist/queries/outline.js +1 -1
  208. package/dist/queries/passthrough-candidates.d.ts +3 -3
  209. package/dist/queries/passthrough-candidates.js +1 -1
  210. package/dist/queries/plan-context.d.ts +3 -3
  211. package/dist/queries/plan-context.js +1 -1
  212. package/dist/queries/react-component-duplicates.d.ts +2 -2
  213. package/dist/queries/react-component-duplicates.js +1 -1
  214. package/dist/queries/react-hook-candidates.d.ts +2 -2
  215. package/dist/queries/react-hook-candidates.js +1 -1
  216. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  217. package/dist/queries/react-large-component-pressure.js +1 -1
  218. package/dist/queries/recent-duplicates.d.ts +2 -2
  219. package/dist/queries/recent-duplicates.js +1 -1
  220. package/dist/queries/redundant-reexports.d.ts +2 -2
  221. package/dist/queries/redundant-reexports.js +1 -1
  222. package/dist/queries/refs.d.ts +2 -2
  223. package/dist/queries/refs.js +1 -1
  224. package/dist/queries/self-audit.d.ts +2 -2
  225. package/dist/queries/self-audit.js +1 -1
  226. package/dist/queries/similar-chains.d.ts +2 -2
  227. package/dist/queries/similar-chains.js +1 -1
  228. package/dist/queries/similar-files.d.ts +2 -2
  229. package/dist/queries/similar-files.js +1 -1
  230. package/dist/queries/similar-signatures.d.ts +2 -2
  231. package/dist/queries/similar-signatures.js +1 -1
  232. package/dist/queries/similar.d.ts +2 -2
  233. package/dist/queries/similar.js +1 -1
  234. package/dist/queries/slice.d.ts +2 -2
  235. package/dist/queries/slice.js +1 -1
  236. package/dist/queries/stale-abstractions.d.ts +2 -2
  237. package/dist/queries/stale-abstractions.js +1 -1
  238. package/dist/queries/stats.d.ts +2 -2
  239. package/dist/queries/surface.d.ts +2 -2
  240. package/dist/queries/surface.js +1 -1
  241. package/dist/queries/symbols.d.ts +2 -2
  242. package/dist/queries/symbols.js +1 -1
  243. package/dist/queries/system.d.ts +2 -2
  244. package/dist/queries/system.js +1 -1
  245. package/dist/queries/test-quality.d.ts +2 -2
  246. package/dist/queries/test-quality.js +1 -1
  247. package/dist/queries/trace.d.ts +2 -2
  248. package/dist/queries/trace.js +1 -1
  249. package/dist/queries/twin-ab.d.ts +14 -3
  250. package/dist/queries/twin-ab.js +1 -1
  251. package/dist/queries/twin-drift.d.ts +2 -2
  252. package/dist/queries/twin-drift.js +1 -1
  253. package/dist/queries/unused-imports.d.ts +2 -2
  254. package/dist/queries/unused-imports.js +1 -1
  255. package/dist/queries/unused-params.d.ts +2 -2
  256. package/dist/queries/unused-params.js +1 -1
  257. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  258. package/dist/queries/vue-component-duplicates.js +1 -1
  259. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  260. package/dist/queries/vue-composable-candidates.js +1 -1
  261. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  262. package/dist/queries/vue-large-view-pressure.js +1 -1
  263. package/dist/queries/wrapper-candidates.d.ts +2 -2
  264. package/dist/queries/wrapper-candidates.js +1 -1
  265. package/dist/reindex-worker.js +26 -25
  266. package/dist/reindex.d.ts +7 -3
  267. package/dist/reindex.js +34 -33
  268. package/dist/runtime.d.ts +5 -10
  269. package/dist/runtime.js +3 -3
  270. package/dist/rust-semantic-session-server.js +1 -1
  271. package/dist/rust-semantic-session-worker.js +1 -1
  272. package/dist/rust-semantic-worker.js +1 -1
  273. package/dist/{scip-cli-DCvnlZCu.d.ts → scip-cli-BnEwZRLJ.d.ts} +2 -2
  274. package/dist/{symbol-types-BgWU6lhL.d.ts → symbol-types-BIQwfoAx.d.ts} +7 -1
  275. package/dist/typescript-mailbox-worker.js +2 -0
  276. package/dist/watch-server.js +2 -42
  277. package/docs/AGENT_GUIDE.md +28 -5
  278. package/docs/CLI_JSON_OUTPUT.md +176 -3
  279. package/docs/COMMAND_REFERENCE.md +89 -87
  280. package/docs/COMMITTED_RECORD_COMPATIBILITY.md +55 -18
  281. package/docs/DURABILITY.md +88 -38
  282. package/docs/INDEX_GENERATIONS.md +65 -19
  283. package/docs/MAILBOX_LIFECYCLE.md +28 -1
  284. package/docs/REINDEX_METADATA_COMPATIBILITY.md +18 -8
  285. package/docs/SECURITY_MODEL.md +146 -0
  286. package/docs/TELEMETRY_RETENTION.md +16 -4
  287. package/docs/WATCH_REFRESH_REQUESTS.md +34 -21
  288. package/docs/WINDOWS_SIDECAR_RELEASE.md +9 -4
  289. package/docs/analyzer-inventory.md +31 -22
  290. package/docs/analyzer-validation-ledger.md +8 -0
  291. package/docs/schemas/cli-output-page.schema.json +104 -0
  292. package/docs/schemas/outcome-event-record.schema.json +57 -1
  293. package/docs/schemas/project-config.schema.json +82 -1
  294. package/docs/schemas/suppression-record.schema.json +84 -3
  295. package/package.json +9 -8
  296. package/skills/_shared/SKILL.md +5 -3
  297. package/skills/_shared/references/agent-contract-catalog.md +1 -1
  298. package/skills/_shared/references/detector-precision-and-diffgate.md +1 -1
  299. package/skills/scip-audit/SKILL.md +9 -8
  300. package/skills/scip-audit/references/claims.md +1 -1
  301. package/skills/scip-audit/references/cleanup.md +19 -20
  302. package/skills/scip-audit/references/directory.md +4 -4
  303. package/skills/scip-audit/references/frontend.md +10 -10
  304. package/skills/scip-audit/references/twin-drift.md +2 -2
  305. package/skills/scip-diagnose/references/debug.md +8 -8
  306. package/skills/scip-diagnose/references/root-cause.md +3 -3
  307. package/skills/scip-diagnose/references/triage.md +10 -10
  308. package/skills/scip-explore/SKILL.md +4 -4
  309. package/skills/scip-improve/SKILL.md +10 -10
  310. package/skills/scip-improve/references/cleanup-batches.md +3 -3
  311. package/skills/scip-improve/references/directory-moves.md +3 -3
  312. package/skills/scip-improve/references/doc-reconcile.md +1 -1
  313. package/skills/scip-improve/references/frontend-extraction.md +2 -2
  314. package/skills/scip-improve/references/twin-drift.md +3 -3
  315. package/skills/scip-plan/SKILL.md +3 -3
  316. package/skills/scip-plan/references/api-impact.md +5 -5
  317. package/skills/scip-plan/references/conductor.md +2 -2
  318. package/skills/scip-plan/references/hyper-optimization.md +1 -1
  319. package/skills/scip-query/SKILL.md +15 -5
  320. package/skills/scip-setup/references/bootstrap-workflow.md +7 -8
  321. package/skills/scip-setup/references/language-verification.md +2 -2
  322. package/skills/scip-setup/references/per-repo-triage.md +1 -1
  323. package/skills/scip-verify/SKILL.md +16 -11
  324. package/skills/scip-verify/references/calibrate-detectors.md +7 -7
  325. package/dist/chunk-24QNP7MN.js +0 -2
  326. package/dist/chunk-26X7KCJR.js +0 -5
  327. package/dist/chunk-273W2U4Y.js +0 -40
  328. package/dist/chunk-2OXVAGGT.js +0 -3
  329. package/dist/chunk-2ZOCHAL2.js +0 -8
  330. package/dist/chunk-35SQLYCQ.js +0 -2
  331. package/dist/chunk-4CGVLUDP.js +0 -18
  332. package/dist/chunk-4RI4BJGT.js +0 -8
  333. package/dist/chunk-52HQTTPB.js +0 -2
  334. package/dist/chunk-64MNV6AB.js +0 -8
  335. package/dist/chunk-7E3TH5ZN.js +0 -33
  336. package/dist/chunk-7Q6VYYCH.js +0 -2
  337. package/dist/chunk-A63U2W3P.js +0 -3
  338. package/dist/chunk-ADFSIJP2.js +0 -16
  339. package/dist/chunk-AOLE4DYM.js +0 -6
  340. package/dist/chunk-APMMR5Y2.js +0 -2
  341. package/dist/chunk-B5MHCHP3.js +0 -107
  342. package/dist/chunk-DGAGY7RJ.js +0 -60
  343. package/dist/chunk-DGMCFMPG.js +0 -11
  344. package/dist/chunk-E2ZXPB7J.js +0 -38
  345. package/dist/chunk-FKGN4A4E.js +0 -61
  346. package/dist/chunk-G4UQL4CP.js +0 -2
  347. package/dist/chunk-GA64UPMI.js +0 -6
  348. package/dist/chunk-HEBAY673.js +0 -2
  349. package/dist/chunk-HELS7KFF.js +0 -2
  350. package/dist/chunk-IPDCSB6N.js +0 -6
  351. package/dist/chunk-JERWGHQT.js +0 -16
  352. package/dist/chunk-JJJCO4QC.js +0 -945
  353. package/dist/chunk-JZNLMHWY.js +0 -56
  354. package/dist/chunk-K42M2KWT.js +0 -2
  355. package/dist/chunk-KP4KBDVF.js +0 -3
  356. package/dist/chunk-LRTP3DKL.js +0 -3
  357. package/dist/chunk-N3SE646F.js +0 -2
  358. package/dist/chunk-NN4ZIRPK.js +0 -8
  359. package/dist/chunk-P6HBYNBE.js +0 -5
  360. package/dist/chunk-QHKUY4FW.js +0 -2
  361. package/dist/chunk-QHRL4LKM.js +0 -2
  362. package/dist/chunk-SHKZ7OVJ.js +0 -35
  363. package/dist/chunk-TFUU5MQQ.js +0 -2
  364. package/dist/chunk-UXP636P5.js +0 -144
  365. package/dist/chunk-VEVBIAOJ.js +0 -16
  366. package/dist/chunk-VKRQDBW5.js +0 -9
  367. package/dist/chunk-VOQFGC2W.js +0 -67
  368. package/dist/chunk-WMXRRBII.js +0 -8
  369. package/dist/chunk-X3NLZHPA.js +0 -20
  370. package/dist/chunk-XF3KLXN3.js +0 -11
  371. package/dist/chunk-YCPASUCX.js +0 -2
  372. package/dist/chunk-YLVE3SXZ.js +0 -20
  373. package/dist/chunk-Z2LHPIOM.js +0 -2
  374. package/dist/chunk-Z5QQPJ3U.js +0 -30
  375. package/dist/chunk-ZTTISZ7J.js +0 -112
  376. package/dist/command-descriptors-SJDZ7QGR.js +0 -617
  377. package/dist/direct-navigation-HTKOZEOM.js +0 -3
@@ -1,43 +1,3 @@
1
- import{$ as Pe,A as ft,Aa as Or,B as vr,Ba as Ae,C as xr,Ca as $r,D as Ir,Da as Gr,E as ce,Ea as Br,F as Rr,Fa as bt,G as Cr,Ga as J,H as wr,Ha as Hr,I as Pr,Ia as Ne,J as Mr,K as Re,Ka as Ur,L as Ce,La as Vr,M as Tr,O as kr,P as mt,Q as Er,T as Dr,X as Fr,_ as Ar,a as er,aa as ht,ba as Nr,c as ve,ca as _r,da as z,f as ir,g as or,h as sr,i as ot,j as ar,k as st,l as dr,m as ur,n as fr,o as mr,pa as Lr,q as dt,r as ut,s as hr,sa as gt,t as gr,v as yr,x as Sr,y as br,ya as jr,z as pt}from"./chunk-UXP636P5.js";import{b as Jt,c as Xt,g as pr,i as ae,m as Y,n as we}from"./chunk-VOQFGC2W.js";import{A as Ee,B as De,C as Fe,a as Qt,b as se,c as Zt,g as rr,h as nr,i as D,j as F,k as at,l as cr,m as ct,n as lr,o as K,p as lt,q as Ie,s as yt,t as Wr,u as Me,v as St,w as qr,y as Te,z as ke}from"./chunk-VKRQDBW5.js";import{a as xe,c as tr,d as it,e as O}from"./chunk-HGFDYOVB.js";import{a as T}from"./chunk-APMMR5Y2.js";import P from"process";import{rmSync as Si}from"fs";import{resolve as zs}from"path";import{pathToFileURL as Js}from"url";import{existsSync as Ii,readFileSync as Ri}from"fs";import{isAbsolute as da,join as Ci,relative as ua,resolve as pa}from"path";var W=1,X=2,xi="./node_modules/scip-query/docs/schemas/project-config.schema.json";function Kr(r){let e=r;if(typeof r=="string")try{e=JSON.parse(r)}catch(s){return{kind:"malformed",reason:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}}if(!Qt(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?W:t;if(n!==W&&n!==X)return{kind:"unsupported",schemaVersion:n,direction:n<W?"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=Yr(e),a=n!==X||typeof e.$schema!="string";return n===W?{kind:"legacy",sourceVersion:W,config:o,needsMigration:a}:{kind:"supported",sourceVersion:X,config:o,needsMigration:a}}function Yr(r){let e=r,{$schema:t,schemaVersion:n,...i}=e;return{$schema:typeof t=="string"&&t.trim()!==""?t:xi,schemaVersion:X,...i}}var _e=".scipquery.json",wi=250,Pi=0,Mi=10*6e4,Ti={enabled:!1,debounceMs:wi,cooldownMs:Pi,gitPollMs:2e3,idleTimeoutMs:Mi,autoRefresh:!0,ignore:[]};var ha=new Set(er);function Q(r){let e=Ci(r,_e);if(!Ii(e))return{};let t;try{t=Ri(e,"utf-8")}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`unable to read ${_e} at ${e}: ${i}`,{cause:n})}return ki(Kr(t),e,"read").config}function Le(r){return{...Ti,...r.watch}}function ki(r,e,t){if(r.kind==="legacy"||r.kind==="supported")return r;if(r.kind==="malformed"){let i=t==="read"?`invalid ${_e} 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 ${_e} 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${W} and current v${X}). Upgrade scip-query before retrying; the file was left untouched.`)}import{existsSync as zr,readFileSync as Ei}from"fs";function vt(r,e,t){let n=new Date().toISOString();if(!zr(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!zr(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=ve(Ei(t.metaPath,"utf-8"));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,a=e.languages??Dr(r),s=Di(r,a,e),c=[...o.indexedLanguages??[]].sort(),l=i.capabilities.publishableGeneration&&JSON.stringify(o.fingerprint)===JSON.stringify(s)&&JSON.stringify(c)===JSON.stringify(s.languages),d=Lr(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 Di(r,e,t){return pr(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 Fi}from"fs";import{basename as Ai,isAbsolute as Ni,join as _i,relative as Li}from"path";import{watch as ji}from"chokidar";import Oi from"ignore";var je=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=Le(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??qi,this.reindexRunner=e.reindexRunner??Vi(),this.subscriptionFactory=e.subscriptionFactory??$i,this.gitignoreFilter=we(e.projectRoot),this.extraIgnore=Oi(),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=Xr(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||!Ki(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")||Ai(t).startsWith(Fr)||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=Ni(e)?e:_i(this.projectRoot,e);return Li(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=Xr(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 a=this.wallNow()+o;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())},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 a=!1;try{a=this.onReindexComplete(o,t)===!0}catch(s){this.onError(s instanceof Error?s:new Error(String(s)))}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 s=this.wallNow()+this.watchConfig.cooldownMs;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()):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 a=o instanceof Error?o:new Error(String(o));this.onReindexError(a,t),this.onError(a),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(a=>Promise.resolve().then(()=>a.close())));for(let a of o)a.status==="rejected"&&n.push(`watch subscription close failed: ${String(a.reason)}`);if(i)try{let a=await i;a.state==="degraded"&&n.push(a.reason)}catch(a){n.push(`reindex cancellation failed: ${a instanceof Error?a.message:String(a)}`)}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=ot(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=ar(this.projectRoot,e),n={head:ot(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=Fi(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 Wi(r){let{projectRoot:e,config:t,languages:n,pnpmWorkspaces:i,typescriptProjectMode:o,typescriptProjects:a,clojureConfigPath:s,indexerConcurrency:c,trigger:l}=r,d=Q(e),u=Object.keys(d).length>0?d:t,p=z(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??a??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:f?.configPath??s??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1"}}}var qi={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)},$i=(r,e)=>ji(r,e),Gi=15*6e4,Bi=1e3,Hi=64*1024;function Ui(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function Jr(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 Vi(r={}){let e=r.timeoutMs??Gi,t=r.terminationGraceMs??Bi,n=r.maxOutputBytes??Hi,i=r.resolveLaunch??Wi;return{start(o){let a=i(o),s=new AbortController,c=Ui(),l=!1,d=Vr({command:process.execPath,args:[...process.execArgv,a.workerPath],label:"watch reindex worker",env:a.env,timeoutMs:e,terminationGraceMs:t,maxStdoutBytes:n,maxStderrBytes:n,outputLimitBehavior:"truncate-tail",signal:s.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(Jr(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c));return u.durationMs}).catch(u=>{throw u instanceof Ur&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(Jr(u,c),{cause:u})}).finally(()=>{l=!0});return{completion:d,async cancel(){l||s.abort();try{await d}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Xr(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 Ki(r){return r instanceof Error&&"code"in r&&r.code==="EMFILE"||String(r).includes("EMFILE: too many open files")}import{existsSync as nn,statSync as Qi}from"fs";import{join as Zi}from"path";import{join as Yi}from"path";var Z=3,zi=2,Ji="typescript-semantic";function Zr(r){let e=Yi(r,Ji),t=Wr(e);return{...t,requestDir:t.legacyRequestDir}}function xt(r){return fr(r)}function en(r){let e=JSON.parse(r),t=e.protocolVersion,n=t===zi;if(!n&&t!==Z||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||!Number.isFinite(e.deadlineAtMs)||e.profileEnvironment!==void 0&&!Zt(e.profileEnvironment)||!e.request||!Xi(e.request)||!n&&(e.mailboxVersion!==yt||typeof e.operationKey!="string"||!/^[a-f0-9]{64}$/.test(e.operationKey)||e.id!==qr(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,a=St("typescript-semantic-v3",{generation:o.generation,profileEnvironment:o.profileEnvironment,request:o.request});if(o.operationKey!==a)throw new Error("TypeScript semantic service received a mismatched mailbox operation identity.");return o}let i=St("typescript-semantic-v2",{id:e.id,generation:e.generation,request:e.request});return{protocolVersion:Z,mailboxVersion:yt,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 Xi(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 vr(e.files)!==null;case"references":return Qr(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Qr(e.definitions);case"signature":return tn(e.definition);default:return!1}}function Qr(r){return Array.isArray(r)&&r.every(tn)}function tn(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 eo(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var rn;function to(r=eo(),e=void 0){if(e===void 0&&rn?.projectRoot===r)return rn;let t=Q(r),n=z(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(nn(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=Zi(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:ro(o,n.dbPath),gitContext:e}}function on(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=to(r);if(!nn(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&a&&console.error(a);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:r,sharedEvidenceDbPath:gt(r,t,s),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=we(r);return new mr(c,l)}function ro(r,e){let t="unknown time";try{t=Qi(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 rs}from"crypto";import{resolve as Dn}from"path";import{performance as S}from"perf_hooks";function Oe(r){return{forFile(e,t){return sn(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,sn(r,i,t));return n}}}function sn(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=xr(r,e)),t.lines&&(n.lines=Ir(r,e)),t.ast&&(n.ast=Rr(r,e)),t.imports&&(n.imports=Mr(r,e)),t.reexports&&(n.reexports=Pr(r,e)),i){let o=Cr(r,e),a=o.facts;t.facts&&(n.facts=a),o.unavailable&&(n.sourceFactsUnavailable=o.unavailable),t.identifiers&&a&&(n.identifiers=a.fileIdentifiers,n.identifierLineMap=a.identifierLineMap)}return n}var no={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function We(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 a,s=i.indexOf(" ");s===-1?(a=i,i=""):(a=i.slice(0,s),i=i.slice(s+1));let c=io(i);return{scheme:t,manager:n,packageName:o,version:a,descriptors:c,raw:r}}function ee(r){let e=We(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 io(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||an(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&&!an(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=no[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function an(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function q(r){let e=We(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 $(r){let e=We(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function cn(r){let e=$(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 oo(r,e={}){if(ee(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 ln(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!oo(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,a)=>o.start_line-a.start_line||o.end_line-a.end_line||o.symbol.localeCompare(a.symbol)):i}var so=ae("file-definitions",{clearGroups:["definition-catalog"]}),yc=ae("file-function-like-definitions",{clearGroups:["definition-catalog"]});function G(r,e,t={}){return t.includeClassMemberFallbacks?dn(r,e,void 0,{includeClassMemberFallbacks:!0}):so.get(r,e,()=>{let n=ao(r,e);if(n)return n;let i=dn(r,e),o=ut(r),a=Oe(r).forFile(e,{text:!0}).text;return o&&a&&pn.write(r,e,dt(r,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var pn=gr({kind:"file-definitions",invalidation:yr("file-definitions"),serialize:co,deserialize:lo});function ao(r,e){let t=ut(r);if(!t)return null;let n=Oe(r).forFile(e,{text:!0}).text;if(!n)return null;let i=pn.read(r,e,dt(r,e,n));return i?uo(i,t,e):null}function co(r){return JSON.stringify(r)}function lo(r){try{let e=JSON.parse(r);return!ft(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function uo(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=po(i,t);if(!o)return null;n.push(o)}return n}function po(r,e){return!ft(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 dn(r,e,t,n={}){let i=ln(fo(r,e),mo(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(ho);return t&&(i=i.filter(t)),yo(r,e,i)}function fo(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 mo(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 ho(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:q(r.symbol),parentTypeName:ee(r.symbol),isFunctionLike:cn(r.symbol),isTypeLike:$(r.symbol)==="type",kind:r.kind??null,documentation:r.documentation??null,enclosingSymbol:r.enclosing_symbol??null}}function fn(r,e={}){return go(r,e.scope)}function go(r,e){return Y(r,{scope:e,includeIgnored:!1}).flatMap(t=>G(r,t)).filter(t=>!r.isIgnored(t.relativePath))}function yo(r,e,t){let n=Oe(r).forFile(e,{text:!0}).text,i=wr(r,e);return i?Ro(t,i,n):n?So(t,n):t}function So(r,e){let t=e.split(/\r?\n/),n=bo(r,t),i=vo(r,n),o=xo(i,t);return Io(r,o)}function bo(r,e){let t=r.some(i=>qe(i.symbol))?Eo(e):null,n=new Map;for(let i of r)n.set(i.symbolId,ko(e,t,i));return n}function vo(r,e){return r.filter(t=>qe(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 xo(r,e){let t=new Map;for(let n=0;n<r.length;n+=1){let i=r[n],o=r[n+1],a=o?Math.max(i.startLine,o.startLine-1):e.length-1;t.set(i.definition.symbolId,{startLine:i.startLine,endLine:Do(e,i.definition,i.startLine,a)})}return t}function Io(r,e){return r.map(t=>{let n=e.get(t.symbolId);return n?{...t,startLine:n.startLine,endLine:n.endLine}:t})}function Ro(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(!To(i)||!i.leaf)return un(i,t);let o=n.get(i.leaf);if(!o||o.length===0)return un(i,t);let a=t?Co(i,o,t):null;if(a)return{...i,startLine:a.startLine,endLine:a.endLine};let s=o[0],c=Math.abs(s.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&&(s=d,c=u)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function Co(r,e,t){let n=wo(r.symbol);if(!n)return null;let i=t.split(/\r?\n/),o=new RegExp(`\\b${ce(n)}\\b`);for(let a of e){let s=Po(i,a.startLine);if(s&&o.test(s))return a}return null}function wo(r){return r.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function Po(r,e){for(let t=e;t>=0;t-=1){let n=r[t]?.trim()??"";if(n){if(/^impl\b/.test(n))return Mo(r,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(n))return null}}return null}function Mo(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 To(r){return qe(r.symbol)?!0:$(r.symbol)==="term"&&ee(r.symbol)===null}function un(r,e){if(!e||!r.leaf||$(r.symbol)!=="term"||ee(r.symbol)!==null)return r;let t=ce(r.leaf),n=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${t}\\b`),o=e.split(/\r?\n/).findIndex(a=>n.test(a));return o>=0?{...r,startLine:o,endLine:o}:r}function ko(r,e,t){if(!qe(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 a of i){let s=Math.abs(a-t.startLine);(!o||s<o.distance)&&(o={line:a,distance:s})}return o?.line??n}function Eo(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,a=(s,c)=>{let l=o.get(s);if(!l){o.set(s,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let s=0;s<r.length;s+=1){let c=r[s]??"";for(let d of c.matchAll(e))d[1]&&a(d[1],s);for(let d of c.matchAll(t))d[1]&&a(d[1],s);let l=c.match(n);l?.[1]&&a(l[1],s);for(let d of c.matchAll(i))d[1]&&a(d[1],s)}return o}function Do(r,e,t,n){let i=Math.max(t,Math.min(r.length-1,n)),o=Math.max(t,Math.min(i,e.endLine)),a=0,s=0,c=!1;for(let l=t;l<=i;l+=1){let d=Fo(r[l]??"");for(let u of d)u==="{"?(a+=1,c=!0):u==="}"?a=Math.max(0,a-1):u==="("?s+=1:u===")"&&(s=Math.max(0,s-1));if(c&&a===0||!c&&s===0&&l>=o)return l}return o}function Fo(r){let e="",t=null,n=!1;for(let i=0;i<r.length;i+=1){let o=r[i],a=r[i+1];if(!t&&o==="/"&&a==="/"){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 qe(r){return r.includes("().")}function A(r,e,t){if(r.has(e))return r.get(e);let n=t();return r.set(e,n),n}import mn from"path";function Ao(r,e){return r.getReferences().map(t=>{let n=t.getNode();return $e(n,e)})}function No(r){let e=r;return typeof e.findReferences=="function"?e.findReferences():[]}function hn(r,e,t,n){let i=[];for(let o of No(r))for(let a of Ao(o,n))a.file===e.relativePath&&a.line>=e.startLine&&a.line<=e.endLine||i.push(a);for(let o of t)i.push(o);return te(i)}function gn(r,e,t,n){let i=[],o=t?.getStart();for(let a of r.getReferences()){let s=a.getNode();re(n,s.getSourceFile().getFilePath())===e&&(o!==void 0&&s.getStart()===o||i.push({location:$e(s,n),node:s}))}return i}function $e(r,e){let t=r.getSourceFile(),n=t.getLineAndColumnAtPos(r.getStart());return{file:re(e,t.getFilePath())??t.getBaseName(),line:n.line-1,column:n.column-1}}function yn(r,e,t){let n=r.getSourceFile(),i=Rt(n,r),o=r.getText(),a=new RegExp(`\\b${ce(o)}\\b`,"g"),s=n.getFullText().split(`
42
- `),c=[];for(let l=0;l<s.length;l++){if(l===i)continue;let d=s[l]??"";a.lastIndex=0;let u;for(;(u=a.exec(d))!==null;)c.push({file:e,line:l,column:u.index})}return te(c.filter(l=>re(t,mn.join(t,l.file))===e))}function It(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 Rt(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function te(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 re(r,e){let t=mn.relative(r||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function Sn(r,e,t,n){let i=_o(e,n);return i.size===0?new Map:Lo(r,t,i)}function _o(r,e){let t=new Map;for(let n of G(r,e)){let i=q(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function Lo(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of jo(r,o)){let s=t.get(a);if(!s)continue;let c=Rt(e,o);for(let l of s){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 jo(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 Oo=ae("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function bn(r,e,t,n){let i=Pt(r,e),o=Ct(i.get(n)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||q(c.symbol)||"").includes(n)||c.symbol.includes(n))&&a.push(c);return Ct(a,t)}function wt(r,e,t,n){return Ct(Pt(r,e).get(n)??[],t)}function vn(r,e){let t=new Map;for(let[n,i]of Pt(r,e)){let o=i[0];o&&t.set(n,o)}return t}function Pt(r,e){return Oo.get(r,e,()=>{let t=new Map;for(let n of G(r,e)){let i=n.leaf||q(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 Ct(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 Mt from"path";function xn(r,e){let t=new Map,n=null,i=null,o=()=>(i??=Y(r,{extensions:Re}),i),a=()=>(n??=O("typescript.source-file-index",()=>Wo(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),s=c=>Ce(c)?A(t,c,()=>{let l=le(Mt.resolve(r.config.projectRoot,c));for(let{project:d,sourceFiles:u}of a()){let p=u.get(l)??null;if(p||(p=d.addSourceFileAtPathIfExists(l)??null,p&&u.set(le(p.getFilePath()),p)),p)return{project:d,sourceFile:p}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function Wo(r,e,t){let n=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[le(o.getFilePath()),o]))}));for(let i of t){let o=le(Mt.resolve(r,i));for(let a of n){if(a.sourceFiles.has(o))break;let s=a.project.addSourceFileAtPathIfExists(o)??null;if(s){a.sourceFiles.set(le(s.getFilePath()),s);break}}}return n}function le(r){return Mt.resolve(r)}function Tt(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function In(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as de,readFileSync as qo}from"fs";import x from"path";var kt=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Et(r,e){let n=e?x.dirname(x.join(r,e)):r,i=x.resolve(r);for(;n.startsWith(i);){for(let a of kt){let s=x.join(n,a);if(de(s))return s}let o=x.dirname(n);if(o===n)break;n=o}for(let o of kt){let a=x.join(r,o);if(de(a))return a}return null}function Rn(r){let e=r.config.projectRoot,t=new Set($o(e,r.config.semantic?.typescript?.tsconfigs)),n=Y(r,{includeIgnored:!1,extensions:Re});for(let i of n){let o=Et(e,i);o&&t.add(x.resolve(o))}if(t.size===0){let i=Et(e);i&&t.add(x.resolve(i))}return[...t].filter(i=>!Cn(e,i)).sort((i,o)=>i.localeCompare(o))}function $o(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 Go(r))for(let i of kt){let o=x.join(n,i);de(o)&&t.add(x.resolve(o))}if(t.size===0){let n=Et(r);n&&t.add(x.resolve(n))}return[...t].filter(n=>!Cn(r,n)).sort((n,i)=>n.localeCompare(i))}function Go(r){let e=x.join(r,"package.json");if(!de(e))return[];let t;try{t=JSON.parse(qo(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>br(r,i))}function Cn(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 Bo=32;function En(r,e,t,n={}){return O("typescript.provider.construct",()=>new Ft(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var Ft=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=Sr(e.config.projectRoot),this.sourceFiles=xn(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 A(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=Uo();return O("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return A(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=xe(),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 a=o,s=t.exact?[]:o.filter(d=>!Pn(d));if(s.length>=Bo){let d=this.referencesForDefinitionsBySymbolScan(s);for(let u of s){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}if(a=o.filter(u=>Pn(u)),a.length===0)return n}let c=new Map;for(let d of a){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=Mn();O("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,...Tn(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=fn(this.db).filter(o=>Ce(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return Er(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=xe(),i=Mn(),o=new Map,a=new Set(e.map(c=>c.symbolId)),s=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return O("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,a,s,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=te(g);o.set(m,R),n&&(i.referenceCount+=R.length)}},()=>({definitions:e.length,...Tn(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,a,s,c,l,d){let u=this.compilerCheckerForSourceFile(e),p=e.compilerNode,y=Yo(e),f=h=>{if(this.tsMorph.ts.isIdentifier(h)){if(d&&(d.identifiers+=1),!a.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;s.has(m)?g=s.get(m)??null:(g=this.referenceDefinitionFromCompilerSymbol(m),s.set(m,g)),d&&(g?d.targetHits+=1:d.targetMisses+=1);let R=A(c,m,()=>this.compilerSymbolKeys(m)),M=null,k=null,j=g&&n.has(g.symbolId)?i.get(g.symbolId):void 0;if(j&&(M=Dt(p,h),!wn(j,t,M))){let L=p.getLineAndCharacterOfPosition(h.getStart(p));k={file:t,line:L.line,column:L.character};let N=l.get(j.symbolId)??[];N.push(k),l.set(j.symbolId,N),d&&(d.requestedHits+=1)}for(let L of R)for(let N of o.get(L)?.values()??[]){if(M??=Dt(p,h),wn(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 a=o.parent;if(!this.isHierarchyContainer(a))continue;let s=this.compilerCheckerForSourceFile(i.getSourceFile()),c=s.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(s,a,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,a=(s,c,l)=>{if(!o.has(s)){o.add(s),i.add(c);for(let d of l){let u=d.getProperty(n.name);u&&a(d,u,this.hierarchyAncestorTypesForType(e,d))}}};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,n){let i=new Map;for(let o of e){let a=this.nodeForDefinition(o),s=a?.compilerNode;if(!s||!this.isHierarchyMethod(s))continue;let c=s.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(a.getSourceFile()),d=l.getSymbolAtLocation(s.name);if(!d)continue;let u=s.getSourceFile(),p=u.getLineAndCharacterOfPosition(s.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:a}of o.values()){let s=t.get(a.symbolId)??[];for(let c of o.values())c.definition.symbolId!==a.symbolId&&(s.push(c.location),n&&(n.hierarchyReferences+=1));t.set(a.symbolId,s)}}}hierarchyRootMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(o.has(s))return;o.add(s);let d=!1;for(let u of l){let p=u.getProperty(n.name);p&&(d=!0,a(u,p,this.hierarchyAncestorTypesForType(e,u)))}if(!d)for(let u of this.compilerSymbolKeys(c))i.add(u)};return a(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=re(this.db.config.projectRoot,i.fileName);if(!o)continue;let a=n.name,s=i.getLineAndCharacterOfPosition((a??n).getStart(i));t.push({file:o,line:s.line,column:s.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 a of o.types)n.add(e.getTypeAtLocation(a));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 A(this.calleesCache,e.symbolId,()=>A(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 a=this.fileCalleesCache.get(i),s=new Set(o.map(l=>l.symbolId)),c=a??this.calleeMapForFile(i,s);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 a=n?S.now():0,s=hn(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=S.now()-a,n.referenceCount+=s.length),s}signatureFor(e){return A(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(a=>{let s=a.getDeclarations()[0],c=s?a.getTypeAtLocation(s).getText(s):a.getValueDeclaration()?.getType().getText()??"unknown";return kn(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${kn(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let a of t.getImportDeclarations()){n.declarations+=1;let s=pt(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of At(a)){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:s,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(a=>{if(a.getKindName()!=="Identifier")return;let s=o.get(a.getText());if(!s||Vo(a))return;n.scannedIdentifiers+=1;let c=a.getSymbol()?.compilerSymbol;if(n.symbolLookups+=1,!!c){for(let l of s)if(l.bindingSymbol===c){l.references.push({location:$e(a,this.db.config.projectRoot),node:a}),n.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?Ho(e,a.sourcePath,a.entry):a.entry.identifier&&!a.bindingSymbol?(n.fallbackEntries+=1,this.valueImportUsageForEntry(e,a.sourcePath,a.entry)):this.valueImportUsageFromLocations(e,a.sourcePath,a.entry,a.references))}valueImportUsageForEntry(e,t,n){let i=n.identifier?n.identifier.findReferences():[],o=[];for(let a of i)for(let s of gn(a,e,n.identifier,this.db.config.projectRoot))o.push(s);return this.valueImportUsageFromLocations(e,t,n,o)}valueImportUsageFromLocations(e,t,n,i){let o=i.some(c=>!It(c.node)),a=i.some(c=>It(c.node)),s=n.isTypeOnly;return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:s,isUsed:s||i.length>0,isTypeUsed:s||a,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 a=this.sourceFiles.sourceFile(o);if(a)for(let s of a.getImportDeclarations()){let c=Tt(this.workspacePackages,s.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,a]of t)t.set(o,te(a));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,te(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=Tt(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of At(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=yn(s.identifier,n,this.db.config.projectRoot);l.length>0&&Qo(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 In(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 a of o.getExportDeclarations()){let s=a.getModuleSpecifierValue(),c=s?pt(this.db,t,s):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=a.getNamedExports();if(l.length===0){if(a.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 A(this.indexedDefinitionLeafCache,e,()=>vn(this.db,e)).get(t)??null}nodeForDefinition(e){return A(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return A(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?Sn(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,a=e.declarations??[];t&&(t.declarationsMs+=S.now()-o,t.declarationChecks+=a.length);for(let s of a){let c=t?S.now():0,l=s.getSourceFile(),d=re(this.db.config.projectRoot,l.fileName),u=l.getLineAndCharacterOfPosition(s.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(s),f=n?wt(this.db,d,u,i)??(y&&y!==i?wt(this.db,d,u,y):null):bn(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=xe(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,u=0,p=n?Jo():void 0;return O("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=G(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 j=new Map,L=I=>{if(this.tsMorph.ts.isCallExpression(I)||this.tsMorph.ts.isNewExpression(I)){n&&(o+=1);let C=this.semanticCalleeForCallNode(M,k,m,I,j,t,p);C&&(n&&(a+=1),Ko(g,C.callerId,C.target))}this.tsMorph.ts.forEachChild(I,L)},N=n?S.now():0;L(k),n&&(u=Math.round(S.now()-N));for(let[I,C]of g)g.set(I,Zo(C));return s=g.size,g},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:u,...p?Xo(p):{}}))}semanticCalleeForCallNode(e,t,n,i,o,a,s){let c=s?S.now():0,l=zo(n,Dt(t,i));if(s&&(s.callerLookupMs+=S.now()-c),!l)return null;if(a&&!a.has(l.symbolId))return s&&(s.skippedUnrequestedCallers+=1),null;let d=i.expression,u=this.compilerSymbolForExpression(e,d,s),p=null;if(u)if(s&&(s.targetSymbolHits+=1),o.has(u))s&&(s.compilerSymbolCacheHits+=1),p=o.get(u)??null;else{s&&(s.compilerSymbolCacheMisses+=1);let y=s?S.now():0;p=this.definitionFromCompilerSymbol(u,s),s&&(s.targetLookupMs+=S.now()-y),o.set(u,p)}else s&&(s.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 a=n?S.now():0,s=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=S.now()-a),s}compilerCheckerForSourceFile(e){let t=e.getProject(),n=this.compilerCheckerCache.get(t);return n||(n=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,n)),n}};function At(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(),s=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:s,importedName:o.getText(),localName:s?.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 Ho(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 Uo(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function Vo(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function Ko(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function Yo(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of At(t))n.localName&&e.add(n.localName);return e}function zo(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 Dt(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function wn(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function Pn(r){return r.symbol.includes("#")?$(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function Jo(){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 Xo(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 Mn(){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 Tn(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function Qo(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function Zo(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 kn(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ge=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??Tr,this.discoverTsconfigs=t.discoverTsconfigs??Rn,this.createProjects=t.createProjects??kr,this.createProvider=t.createProvider??((n,i,o)=>En(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=es(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"&&(ts(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=mt("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=mt("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 es(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=Nt(r.changes,"added"),n=Nt(r.changes,"modified"),i=Nt(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function Nt(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function ts(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(Dn(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(Dn(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var Be=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 Ge(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):os,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[...ns(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[...is(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return as(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(e){let t=this.host?.snapshotStats();return{protocolVersion:Z,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,ss(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function _t(r){Me(r)}function An(r,e,t={}){_t(r);let n=t.nowMs??Date.now(),i=Te(r,{ownerId:t.ownerId??cs,nowMs:n,limits:t.limits,owner:ls,liveness:ds}),o=0;for(let a of i){let s=a.requestId,c=null;try{let l=en(ke(a,t.limits));if(s=l.id,s!==a.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=tr(),it(l.profileEnvironment??{}),t.beforeRequest?.(l.deadlineAtMs);let d=e.handle(l.generation,l.request);Ee(r,a,{ok:!0,protocolVersion:Z,id:s,generation:l.generation,response:d},{nowMs:n,limits:t.limits})}catch(l){let d=l instanceof Error?l.message:String(l);De(r,a,{ok:!1,protocolVersion:Z,id:s,error:d},d,{nowMs:n,limits:t.limits})}finally{c&&it(c),t.afterRequest?.(),o+=1}}return o}function Nn(r){return Fe(r)}function ns(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function is(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function os(r){if(!r.generation.metadataRaw)return null;let e=ve(r.generation.metadataRaw);return e.kind!=="legacy"&&e.kind!=="supported"||!e.capabilities.usableForEvidenceCache?null:Jt(e.metadata.fingerprint)}function ss(r,e){return e?Xt(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function as(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}var cs=`typescript-semantic-${process.pid}-${rs()}`,Fn=D(process.pid),ls={pid:process.pid,...Fn?{processIdentity:Fn}:{}},ds={isProcessAlive:F,readProcessIdentity:D};import{randomUUID as us}from"crypto";import{resolve as ps}from"path";var He=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=ps(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Or,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(),a=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),s=this.monotonicNow()-n;return this.requests+=1,this.lastRequestAtMs=this.wallNow(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.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:Ae,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 Lt(r){Me(r)}function Ln(r,e,t={}){Lt(r);let n=t.nowMs??Date.now(),i=Te(r,{ownerId:t.ownerId??fs,nowMs:n,limits:t.limits,owner:ms,liveness:hs}),o=0;for(let a of i){let s=a.requestId;try{let c=Gr(ke(a,t.limits));if(s=c.id,s!==a.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);Ee(r,a,{ok:!0,protocolVersion:Ae,id:s,baseGeneration:c.baseGeneration,response:l},{nowMs:n,limits:t.limits})}catch(c){let l=c instanceof Error?c.message:String(c);De(r,a,{ok:!1,protocolVersion:Ae,id:s,error:l},l,{nowMs:n,limits:t.limits})}finally{t.afterRequest?.(),o+=1}}return o}function jn(r){return Fe(r)}var fs=`typescript-index-${process.pid}-${us()}`,_n=D(process.pid),ms={pid:process.pid,..._n?{processIdentity:_n}:{}},hs={isProcessAlive:F,readProcessIdentity:D};import{spawn as Es}from"child_process";import{existsSync as Ds,readFileSync as Fs,rmSync as ei}from"fs";import{dirname as ql,resolve as Ht}from"path";import{fileURLToPath as Gl}from"url";import{createHash as gs,randomUUID as jt}from"crypto";import{existsSync as ys,linkSync as Ss,mkdirSync as On,readFileSync as bs,readdirSync as vs,rmSync as ne}from"fs";import{basename as xs,dirname as Is,join as v}from"path";var B=1,Rs=10*6e4,Cs=10080*6e4,Ve="requests",ue="claims",Ue="completions",qn="staging";function $n(r,e,t={}){let n=t.now?.()??new Date,i=Ps(t.ttlMs),o=Ms(t.idempotencyKey),a=o?`key-${gs("sha256").update(o).digest("hex")}`:`request-${(t.randomId??jt)()}`,s={version:B,requestId:a,...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=Xn(r,a);if(qt(r,c,s,t.onStage))return{disposition:"accepted",request:s};let d=Wt(c);if(!d)throw new Error(`Watch refresh request identity ${a} exists but is malformed.`);return{disposition:"duplicate",request:d}}function Gn(r,e={}){let t=e.now?.()??new Date,n=`claim-${(e.randomId??jt)()}`,i=Math.max(1,Math.floor(e.limit??64)),o=Yn(r).sort(Ts),a=[];for(let s of o){if(a.length>=i)break;if(Wn(r,s.requestId))continue;if(Date.parse(s.deadlineAt)<=t.getTime()){Kn(r,{version:B,requestId:s.requestId,outcome:"expired",completedAt:t.toISOString()});continue}let c={version:B,requestId:s.requestId,claimId:n,claimedAt:t.toISOString()};if(qt(r,Qn(r,s.requestId),c)){if(Wn(r,s.requestId)){zn(r,s.requestId,n);continue}a.push(s)}}return{claimId:n,requests:a}}function Bn(r,e,t=()=>new Date,n){let i=t().toISOString();for(let o of e.requests)Kn(r,{version:B,requestId:o.requestId,claimId:e.claimId,outcome:"completed",completedAt:i});n?.("after-completion"),Ke(r,e),n?.("after-claim-release")}function Ke(r,e){for(let t of e.requests)zn(r,t.requestId,e.claimId)}function Hn(r){let e=0;for(let t of H(v(r,ue)))ne(t,{force:!0}),e++;return e>0&&K(v(r,ue)),Jn(r),e}function Ot(r){let e=Yn(r),t=new Map,n=ws(v(r,Ve),Wt);for(let c of H(v(r,Ue))){let l=Ye(c);if(!l){n++;continue}t.set(l.requestId,l)}let i=new Set;for(let c of H(v(r,ue))){let l=Vn(c);if(!l){n++;continue}i.add(l.requestId)}let o=e.filter(c=>!t.has(c.requestId)&&!i.has(c.requestId)),a=[...t.values()].filter(c=>c.outcome==="completed").length,s=[...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:a,expired:s,invalid:n,...o.length>0?{oldestPendingAt:o.map(c=>c.createdAt).reduce((c,l)=>ks(c,l))}:{}}}function Un(r,e={}){let t=(e.now?.()??new Date).getTime(),n=Math.max(0,e.retentionMs??Cs),i=0;for(let o of H(v(r,Ue))){let a=Ye(o);!a||t-Date.parse(a.completedAt)<n||(ne(o,{force:!0}),ne(Xn(r,a.requestId),{force:!0}),i++)}return i>0&&(K(v(r,Ue)),K(v(r,Ve))),Jn(r),i}function Wt(r){return $t(r,e=>{let t=e;return t.version===B&&pe(t.requestId)&&(t.idempotencyKey===void 0||typeof t.idempotencyKey=="string")&&se(t.createdAt)&&se(t.deadlineAt)&&Date.parse(t.deadlineAt)>=Date.parse(t.createdAt)&&typeof t.detail=="string"&&t.detail.length>0})}function Vn(r){return $t(r,e=>{let t=e;return t.version===B&&pe(t.requestId)&&pe(t.claimId)&&se(t.claimedAt)})}function Ye(r){return $t(r,e=>{let t=e;return t.version===B&&pe(t.requestId)&&(t.claimId===void 0||pe(t.claimId))&&(t.outcome==="completed"||t.outcome==="expired")&&se(t.completedAt)})}function Kn(r,e){let t=Zn(r,e.requestId);if(qt(r,t,e))return;let n=Ye(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 qt(r,e,t,n){let i=v(r,qn),o=Is(e);On(i,{recursive:!0}),On(o,{recursive:!0});let a=v(i,`${xs(e)}.${process.pid}.${jt()}.tmp`);try{Ie(a,t,{spacing:2,trailingNewline:!0}),n?.("after-staged");try{Ss(a,e)}catch(s){if(s.code==="EEXIST")return!1;throw s}return K(o),n?.("after-published"),!0}finally{ne(a,{force:!0})}}function Yn(r){let e=[];for(let t of H(v(r,Ve))){let n=Wt(t);n&&e.push(n)}return e}function zn(r,e,t){let n=Qn(r,e),i=Vn(n);!i||i.claimId!==t||(ne(n,{force:!0}),K(v(r,ue)))}function Jn(r){for(let e of H(v(r,qn),".tmp"))ne(e,{force:!0})}function ws(r,e){return H(r).filter(t=>!e(t)).length}function H(r,e=".json"){return ys(r)?vs(r,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(e)).map(t=>v(r,t.name)).sort():[]}function $t(r,e){try{let t=JSON.parse(bs(r,"utf8"));return e(t)?t:null}catch{return null}}function Xn(r,e){return v(r,Ve,`${e}.json`)}function Qn(r,e){return v(r,ue,`${e}.json`)}function Zn(r,e){return v(r,Ue,`${e}.json`)}function Wn(r,e){return Ye(Zn(r,e))!==null}function Ps(r){if(r===void 0)return Rs;if(!Number.isFinite(r)||r<=0)throw new Error("Watch refresh request ttlMs must be positive.");return Math.floor(r)}function Ms(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 Ts(r,e){return Date.parse(r.createdAt)-Date.parse(e.createdAt)||r.requestId.localeCompare(e.requestId)}function ks(r,e){return Date.parse(e)<Date.parse(r)?e:r}var As=2e3,Ns=10;function ri(r,e,t){let n=st(Ht(r));if(t&&st(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=or(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 ni(r){let e=r.runtime??js,t=J(r.cacheDir),n=Hr(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=_s("stop",i);if(o.kind==="signal-stop")return ti(o.state,r,e),Gt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return Gt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let a=ai(t.lockPath);return o.kind==="already-stopped"&&a&&e.isProcessAlive(a.pid)?(ti(a,r,e),Gt(t,a.pid,e),{disposition:"stopped",pid:a.pid}):{disposition:"already-stopped"}}function ii(r,e){Ie(r,e)}function oi(r){try{let e=JSON.parse(Fs(r,"utf8"));return e.version!==1||!Ne(e.at)||e.refreshRequestedAt!==void 0&&!Ne(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??F,o=()=>{},a=t.readProcessIdentity??D,s=t.now??(()=>new Date),c={...at,wallNow:()=>s().getTime(),isProcessAlive:i,readProcessIdentity:a},l=cr(r,{kind:"watch",pid:n,processIdentity:a(n),detail:{projectRoot:Ht(e)},parseLegacy:ze,runtime:c});if(l.kind==="contended"){let d=ci(l.observation);return{acquired:!1,lockPath:r,message:Ls(r,e,d),release:o}}return{acquired:!0,lockPath:r,message:"",release:()=>{l.lock.release()}}}function ai(r){return ci(ct(r,{parseLegacy:ze}))}var ze=r=>{let e=li(r);return e?{pid:e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{}}:null};function ci(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 li(r.parsed)}function li(r){try{let e=r;if(e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!Ne(e.startedAt))return null;let t=e.processIdentity===void 0?null:rr(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 _s(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 Bt(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 Bt(e)}default:return Bt(r)}}function di(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function ti(r,e,t){let{pid:n}=r;if(!t.isProcessAlive(n))return;Os(r,t),t.signalProcess(n);let i=e.stopTimeoutMs??As,o=t.monotonicNow??T,a=o()+i;for(;o()<=a;){if(!t.isProcessAlive(n))return;t.sleep(Ns)}throw new Error(`scip-query watch service pid ${n} did not stop within ${i}ms.`)}function Gt(r,e,t){if(ei(r.statePath,{force:!0}),ei(r.activityPath,{force:!0}),ai(r.lockPath)?.pid===e&&!t.isProcessAlive(e)){let i={...at,wallNow:t.now,isProcessAlive:t.isProcessAlive,readProcessIdentity:t.readProcessIdentity},o=ct(r.lockPath,{parseLegacy:ze,runtime:i});lr(r.lockPath,o,{parseLegacy:ze,runtime:i})}}function Ls(r,e,t){return`error: scip-query watch is already running for ${Ht(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}var js={now:Date.now,monotonicNow:T,isProcessAlive:F,readProcessIdentity:D,spawnServer(r,e,t,n){if(!Ds(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);Es(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 Os(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(!nr(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 Bt(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as mi,lstatSync as Je,readFileSync as Yt,readdirSync as hi,realpathSync as ui,rmSync as fe,statSync as Ws}from"fs";import{join as w,resolve as U,sep as pi}from"path";var qs=3600*1e3,$s=2*1024*1024*1024,Gs=300*1e3;function Bs(r){let e=r.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=Hs(r.leases,r.locks),n={};for(let s of r.generations)t.has(s.generationId)||(n[s.generationId]=s.unreferencedAt??r.nowMs);let i=r.generations.filter(s=>!t.has(s.generationId)).sort((s,c)=>n[s.generationId]-n[c.generationId]||s.generationId.localeCompare(c.generationId)),o=new Set;for(let s of i)r.nowMs-n[s.generationId]>=r.policy.generationTtlMs&&o.add(s.generationId);let a=r.generations.filter(s=>!o.has(s.generationId)).reduce((s,c)=>s+c.size,0);for(let s of i){if(a<=r.policy.budgetBytes)break;o.has(s.generationId)||(o.add(s.generationId),a-=s.size)}for(let s of o)delete n[s];return{deleteWorktrees:e,deleteGenerations:r.generations.filter(s=>o.has(s.generationId)),deleteLocks:r.locks.filter(s=>!s.live),deleteTemporaries:r.temporaries.filter(s=>!s.live),protectedGenerationIds:[...t].sort(),unreferencedSince:n}}function Hs(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 gi(r,e,t={}){if(!_r())return{kind:"disabled"};let n=ir(r);if(!n)return{kind:"unavailable"};let i=w(ht(),"repositories",n.repositoryId);if(!mi(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=w(i,"gc-state.json"),s=Ks(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<Gs)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=dr(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=Us(r,i,n.repositoryId,s?.unreferencedSince??{}),d=Bs({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??qs,budgetBytes:t.policy?.budgetBytes??$s}}),u=0,p=0;for(let h of d.deleteWorktrees){if(!yi(h.lease))continue;let m=ur(w(h.lease.localCacheDir,"cache-lifecycle.lock"));if(m)try{if(Vt(h.lease,!0))continue;try{ni({projectRoot:h.lease.projectRoot,cacheDir:h.lease.localCacheDir,cliVersion:e})}catch{continue}if(Vt(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;hr(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 lt(a,f,{spacing:2,trailingNewline:!0}),y}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function Us(r,e,t,n){let i=new Set(sr(r).map(l=>U(l.path))),o=[];for(let l of Ut(w(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=w(e,"worktrees",l),u=Vs(d);if(!u)continue;let p=U(u.projectRoot);o.push({leasePath:d,lease:u,managed:u.repositoryId===t&&yi(u),live:i.has(p)||mi(p),busy:Vt(u)})}let a=[];for(let l of Ut(w(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let u=w(e,"locks",l),p=Kt(u),y=p!==void 0&&F(p),f=d[1];a.push({generationId:f,path:u,live:y})}let s=[],c=[];for(let l of Ut(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:fi(y),live:Number.isSafeInteger(f)&&F(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let u=w(e,"generations",l),p;try{p=Je(u)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||s.push({generationId:l,path:u,size:fi(u),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function yi(r){if(r.ownershipChecksum!==jr(r)||U(r.localCacheDir)!==U(Nr(r.projectRoot)))return!1;let e=U(ht()),t=U(w(e,"projects")),n=U(r.localCacheDir);if(!n.startsWith(`${t}${pi}`))return!1;try{let i=Je(e),o=Je(t),a=Je(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=ui(t);return ui(n).startsWith(`${s}${pi}`)}catch{return!1}}function Vt(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=Kt(w(r.localCacheDir,n));if(i!==void 0&&F(i))return!0}let t=Kt(J(r.localCacheDir).lockPath);return t!==void 0&&F(t)}function Vs(r){try{let e=JSON.parse(Yt(r,"utf8"));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 Kt(r){try{let e=JSON.parse(Yt(r,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function Ks(r){try{let e=JSON.parse(Yt(r,"utf8"));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 Ut(r){try{return hi(r)}catch{return[]}}function fi(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of hi(n,{withFileTypes:!0})){let o=w(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Ws(o).size)}}return e}var Xe=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=Ot(e)}initializeAfterOwnershipAcquired(){let e=Hn(this.root),t=Un(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:e,prunedHistory:t}}observeLegacyRequest(e,t){$n(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=Gn(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(Ys(n)),!0}catch(i){throw Ke(this.root,n),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),i}}completeActive(){return this.active?(Bn(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(Ke(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=Ot(this.root)}};function Ys(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 Xs=1e3,Qs=250,Zs=10;function ea(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function ta(r,e,t={}){let n=ri(r,e),i=n.projectRoot,o=Q(i);o.watch={...o.watch,...t};let a=Le(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=z(i,o),c=J(s.cacheDir),l=D(P.pid),d=si(c.lockPath,i,{readProcessIdentity:b=>b===P.pid?l:D(b)});if(!d.acquired)return;let u=new Xe(c.refreshRequestsPath,{retryDelayMs:Math.max(1e3,a.cooldownMs)});u.initializeAfterOwnershipAcquired();let p=Date.now(),y=T(),f=p,h=y,m={state:"idle"},g,R,M,k=Pe(s.dbPath),j=!1,L=!1,N=0,I=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY,zt=Number.NEGATIVE_INFINITY,me,he,Qe=Zr(s.cacheDir),Ze=$r(s.cacheDir);_t(Qe),Lt(Ze);let et=new Be({openDb:()=>on(i)}),tt=new He({projectRoot:i,currentGeneration:()=>Br(s.dbPath)}),_=(b=!1)=>{if(!L)return;let Se=Date.now(),be=T();!b&&be-I<Xs||(I=be,ii(c.statePath,{version:1,protocolVersion:bt,pid:P.pid,...l?{processIdentity:l}:{},projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(p).toISOString(),heartbeatAt:new Date(Se).toISOString(),lastActivityAt:new Date(f).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(f+a.idleTimeoutMs).toISOString()},watcher:m,...m.state==="idle"&&g?{indexGeneration:g}:{},...R?{lastRefresh:R}:{},...M?{lastError:M}:{},reindexActivity:k,refreshRequests:u.status(),typescriptSemantic:{...et.status(Nn(Qe)),...me===void 0?{}:{busyUntil:new Date(me).toISOString()}},typescriptIndex:{...tt.status(jn(Ze)),...he===void 0?{}:{busyUntil:new Date(he).toISOString()}}}))},V=()=>{f=Date.now(),h=T()},ge=new je({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(b){m=b,b.state!=="idle"&&(g=void 0),b.state!=="idle"&&V(),_(!0)},onReindexComplete(){V();let b=vt(i,o,s);return R=b.lastRefresh,g=b.state==="fresh"?xt(s.dbPath)??void 0:void 0,k=Pe(s.dbPath),u.completeActive(),M=void 0,_(!0),b.state==="fresh"},onReindexError(){u.failActive()},onRefreshSuppressed(b){Ar(s.dbPath,b),k=Pe(s.dbPath)},onError(b){V(),g=void 0,M={at:new Date().toISOString(),message:b.message},_(!0)}}),ye=()=>{j=!0};P.once("SIGINT",ye),P.once("SIGTERM",ye);let rt=!1,nt,ie;try{ge.start();let b=vt(i,o,s);R=b.lastRefresh,g=b.state==="fresh"?xt(s.dbPath)??void 0:void 0;let Se=ea(b.state);for(Se&&ge.requestRefresh(Se,{immediate:!0}),V(),L=!0,_(!0);!j;){let be=Ln(Ze,tt,{beforeRequest(E){he=E+5e3,_(!0)},afterRequest(){he=void 0,_(!0)}}),bi=An(Qe,et,{beforeRequest(E){me=E+5e3,_(!0)},afterRequest(){me=void 0,_(!0)}}),oe=T();if(oe-zt>=6e4&&(zt=oe,gi(i,e)),oe-C>=Qs){C=oe;let E=oi(c.activityPath);E&&E.atMs>f&&(f=E.atMs,h=oe),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,vi=>{V(),ge.requestRefresh({kind:"watch-demand",detail:vi},{immediate:!0})})}if((bi>0||be>0)&&(V(),_(!0)),_(),di({watcher:m,lastActivityAtMs:h,nowMs:T(),idleTimeoutMs:a.idleTimeoutMs}))break;await ra(Zs)}}catch(b){rt=!0,nt=b}finally{P.off("SIGINT",ye),P.off("SIGTERM",ye),et.closeTypeScriptService(),tt.close();let b=await ge.stop();b.state==="stopped"?(Si(c.statePath,{force:!0}),Si(c.activityPath,{force:!0}),d.release()):(M={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${b.reasons.join("; ")}`},_(!0),ie=new Error(M.message))}if(rt&&ie)throw new AggregateError([nt,ie],"Watch service execution and shutdown both failed.");if(rt)throw nt;if(ie)throw ie}function ra(r){return new Promise(e=>setTimeout(e,r))}var na=P.argv[1]?Js(zs(P.argv[1])).href:null;if(na===import.meta.url){let r=P.argv[2],e=P.argv[3],t=ia(P.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),P.exitCode=1;else try{await ta(r,e,t)}catch(n){console.error(`watch-service: ${n instanceof Error?n.message:String(n)}`),P.exitCode=1}}function ia(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{ta as runWatchServiceServer,ea as startupRefreshTrigger};
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,9 +25,13 @@ 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
- Claude Code lifecycle hooks.
31
+ Claude Code lifecycle hooks. Non-interactive setup and ordinary reindex
32
+ diagnose missing global tools without installing them. Pass
33
+ `--install-missing` only after reviewing the pinned package identities and
34
+ granting that user-environment change for the current operation.
31
35
 
32
36
  Setup reports three change scopes. Repository records are shared project
33
37
  facts and history that must survive clones, so commit `.scipquery.json`,
@@ -36,8 +40,10 @@ For analyzer implementation work, follow [Regex Policy](REGEX_POLICY.md): regex
36
40
  gate run changes them. Checkout preferences configure only one clone, so do
37
41
  not commit `.codex/hooks.json` or `.claude/settings.local.json`; setup keeps
38
42
  them out of Git through `.git/info/exclude`. User-environment changes install
39
- skills or indexers for the current machine. Use `setup --guided` to answer
40
- each repository, checkout, or user-scope question separately.
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
45
+ `setup --install-missing` for an explicit non-interactive installation
46
+ grant.
41
47
 
42
48
  2. **Resolve blockers**
43
49
 
@@ -459,7 +465,24 @@ Numeric thresholds below are recommended starting points for review sessions; co
459
465
 
460
466
  ## Tips for AI Agents
461
467
 
462
- - **Check freshness before analysis**: run `scip-query status --capabilities`; if freshness is `stale`, `missing`, or `unknown`, run `scip-query reindex`.
468
+ - **Check freshness once before the first graph claim in a work session**:
469
+ run `scip-query status --capabilities`, then reuse that generation until
470
+ source changes. After edits, let an active watcher or pending hook refresh
471
+ finish. Run `scip-query reindex` only when freshness is `stale`, `missing`,
472
+ or `unknown` and no responsible watcher is available.
473
+ - **Retrieve complete output**: an incomplete page is not evidence. Before
474
+ making a conclusion, changing to another evidence command, or reporting
475
+ completion, run every emitted `Continue exactly:` command unchanged until
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
480
+ rendered output; a result cursor such as `refs --cursor` advances logical
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.
463
486
  - **Use `--json` on `health`** for programmatic consumption — parse the JSON to make decisions
464
487
  - **Run `change-surface` before every file modification** — it takes <1 second and prevents surprises
465
488
  - **Run `diff-impact --json` before committing** — catches unexpected blast radius across downstream consumers