scip-query 0.19.5 → 0.19.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (421) hide show
  1. package/CHANGELOG.md +85 -1
  2. package/README.md +259 -53
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/chunk-2465DLHK.js +3 -0
  5. package/dist/{chunk-7GXM52MI.js → chunk-24GTWJ3N.js} +2 -2
  6. package/dist/{chunk-NH5ALKPW.js → chunk-2SNGN6U4.js} +2 -2
  7. package/dist/{chunk-3SVWW4PN.js → chunk-2U3OLUNJ.js} +2 -2
  8. package/dist/{chunk-XLTP42QA.js → chunk-33KUO7CG.js} +2 -2
  9. package/dist/{chunk-54HA4ZXH.js → chunk-33XTHFKR.js} +2 -2
  10. package/dist/{chunk-ZGZUZ7XE.js → chunk-3EDFLQ6A.js} +2 -2
  11. package/dist/chunk-3ZSJ3PWF.js +16 -0
  12. package/dist/{chunk-F6O7AAC3.js → chunk-43KC6EQZ.js} +2 -2
  13. package/dist/{chunk-I5RJM53C.js → chunk-464PLI5O.js} +2 -2
  14. package/dist/chunk-46XGSFNI.js +2 -0
  15. package/dist/{chunk-M7AIS73L.js → chunk-47BU5Z4T.js} +2 -2
  16. package/dist/chunk-4BV4QAZJ.js +5 -0
  17. package/dist/chunk-4YTUWQ6M.js +18 -0
  18. package/dist/{chunk-RV2FQIX3.js → chunk-5ML2BNRH.js} +2 -2
  19. package/dist/{chunk-6NSFJYRC.js → chunk-5YLUDDAF.js} +2 -2
  20. package/dist/chunk-67QRR5YC.js +6 -0
  21. package/dist/{chunk-GPBBJ5Y4.js → chunk-6GXYN7YA.js} +3 -3
  22. package/dist/{chunk-4333ETTV.js → chunk-6M7RONVB.js} +2 -2
  23. package/dist/chunk-6YTSKJJ3.js +2 -0
  24. package/dist/{chunk-QDV6RDCP.js → chunk-7FT5Y65S.js} +2 -2
  25. package/dist/{chunk-XTX6QHOF.js → chunk-7KYNAMMH.js} +2 -2
  26. package/dist/{chunk-DZ74OMG6.js → chunk-7LSVMFX7.js} +2 -2
  27. package/dist/{chunk-VTKGCT3V.js → chunk-7QHY3H7P.js} +2 -2
  28. package/dist/{chunk-MITTUCEH.js → chunk-7RAG65VK.js} +2 -2
  29. package/dist/{chunk-25LPM4DG.js → chunk-7SWJEWJF.js} +2 -2
  30. package/dist/{chunk-52ZYCAEO.js → chunk-7VCOXZH3.js} +2 -2
  31. package/dist/chunk-A2TNXAXO.js +8 -0
  32. package/dist/{chunk-IUFDSKGG.js → chunk-A3QXWFBK.js} +2 -2
  33. package/dist/{chunk-4T3LTWUS.js → chunk-AA4UWRNL.js} +2 -2
  34. package/dist/{chunk-4SALD7RU.js → chunk-ACAM6O5R.js} +2 -2
  35. package/dist/chunk-APMMR5Y2.js +2 -0
  36. package/dist/chunk-AQOFWNQJ.js +1 -0
  37. package/dist/chunk-AZFUMCQB.js +2 -0
  38. package/dist/{chunk-M7MTH5NR.js → chunk-BDOIKGDI.js} +2 -2
  39. package/dist/{chunk-BTEE5NZQ.js → chunk-BNXICU42.js} +2 -2
  40. package/dist/chunk-C5Q44Q5D.js +3 -0
  41. package/dist/{chunk-EOOJGLDU.js → chunk-CTF2GDEX.js} +2 -2
  42. package/dist/chunk-DHEQMPLW.js +2 -0
  43. package/dist/{chunk-IZKFSVBV.js → chunk-DQBCO2UY.js} +2 -2
  44. package/dist/{chunk-7B3UPBVA.js → chunk-DQGSM7RZ.js} +2 -2
  45. package/dist/chunk-E2LAW7SL.js +30 -0
  46. package/dist/chunk-E3HYEQO7.js +2 -0
  47. package/dist/chunk-E4NFOAD4.js +6 -0
  48. package/dist/chunk-E5HNT4X2.js +3 -0
  49. package/dist/{chunk-J77UIT3I.js → chunk-ELLMY7XJ.js} +2 -2
  50. package/dist/chunk-FD3HFKXR.js +5 -0
  51. package/dist/{chunk-SOAT6NLA.js → chunk-FIJCV235.js} +2 -2
  52. package/dist/{chunk-H7UKLTWJ.js → chunk-FJ5UDTQF.js} +2 -2
  53. package/dist/{chunk-HEXVUYFQ.js → chunk-GHKEJTCE.js} +2 -2
  54. package/dist/{chunk-LBMJEAEW.js → chunk-GLZTVKAB.js} +3 -3
  55. package/dist/{chunk-FWUUZTIO.js → chunk-GNC4JVAN.js} +2 -2
  56. package/dist/chunk-HIB452NU.js +949 -0
  57. package/dist/{chunk-NRCXJDHL.js → chunk-HZYDQPNY.js} +2 -2
  58. package/dist/chunk-IF6FP6B2.js +66 -0
  59. package/dist/{chunk-4RSI5EMG.js → chunk-JAY7YWS3.js} +2 -2
  60. package/dist/{chunk-STOL2BTL.js → chunk-JHF3E4YM.js} +2 -2
  61. package/dist/chunk-JORHF5AL.js +108 -0
  62. package/dist/{chunk-A2EZV2UM.js → chunk-K2WO7XY7.js} +2 -2
  63. package/dist/chunk-KFZNKUNT.js +2 -0
  64. package/dist/{chunk-YVVCVR2L.js → chunk-KJ2IIBZN.js} +2 -2
  65. package/dist/{chunk-QGXBRIM5.js → chunk-KKME5ZAI.js} +2 -2
  66. package/dist/chunk-KSGTULOS.js +9 -0
  67. package/dist/{chunk-UOAV44HR.js → chunk-KXDJAG4N.js} +3 -3
  68. package/dist/{chunk-UKZBVX4U.js → chunk-L4S2A7BV.js} +2 -2
  69. package/dist/chunk-LP3ARJKF.js +8 -0
  70. package/dist/chunk-LSOR3LQG.js +3 -0
  71. package/dist/{chunk-Q4IIEGXJ.js → chunk-MLFZP76A.js} +2 -2
  72. package/dist/{chunk-WQTAC523.js → chunk-MNSTUIDD.js} +2 -2
  73. package/dist/{chunk-VXQNNXJE.js → chunk-MSBDMFER.js} +2 -2
  74. package/dist/{chunk-X6D5IC6I.js → chunk-MZZBAITE.js} +5 -5
  75. package/dist/{chunk-I5AWSI2G.js → chunk-NE3TZUCI.js} +2 -2
  76. package/dist/{chunk-6E7UTQY7.js → chunk-NTUMF2X3.js} +2 -2
  77. package/dist/{chunk-S44IULR6.js → chunk-O23I56NA.js} +2 -2
  78. package/dist/{chunk-CFMXJPHH.js → chunk-O3O4XXO6.js} +2 -2
  79. package/dist/{chunk-IG7N5ZIK.js → chunk-OUBAF226.js} +2 -2
  80. package/dist/chunk-P3UO3EH3.js +2 -0
  81. package/dist/{chunk-YNRNA5LK.js → chunk-QGGLL3UH.js} +2 -2
  82. package/dist/chunk-QIQ63BHW.js +16 -0
  83. package/dist/{chunk-VGRICIQI.js → chunk-QJIVBYEK.js} +2 -2
  84. package/dist/chunk-QOXBSI6G.js +20 -0
  85. package/dist/chunk-QXK6UUSM.js +2 -0
  86. package/dist/{chunk-XYADIZHU.js → chunk-RA3AYNWP.js} +2 -2
  87. package/dist/chunk-RJMDJR3A.js +2 -0
  88. package/dist/{chunk-NSS46APD.js → chunk-RLH5VUMG.js} +2 -2
  89. package/dist/{chunk-GBQ5NYPR.js → chunk-S4S2WOIX.js} +6 -6
  90. package/dist/{chunk-YIJ7ZAA4.js → chunk-SERUIGV5.js} +2 -2
  91. package/dist/{chunk-FECYOO5O.js → chunk-SMQWE25B.js} +2 -2
  92. package/dist/{chunk-R4FQGQ4X.js → chunk-TAVELHYR.js} +2 -2
  93. package/dist/{chunk-U6WNH5GC.js → chunk-TWMJ3Y3G.js} +2 -2
  94. package/dist/chunk-VAXNI5NE.js +146 -0
  95. package/dist/chunk-VVY2G5ET.js +2 -0
  96. package/dist/{chunk-WER3B7MI.js → chunk-W3DBTGL4.js} +2 -2
  97. package/dist/{chunk-CNKAGUPL.js → chunk-WANA4KAQ.js} +2 -2
  98. package/dist/chunk-WJL2L6MV.js +60 -0
  99. package/dist/chunk-WUW7YUAH.js +11 -0
  100. package/dist/{chunk-QVWS2VWZ.js → chunk-WWKWUPSU.js} +2 -2
  101. package/dist/{chunk-ABMYA4TN.js → chunk-WY45BHKQ.js} +2 -2
  102. package/dist/chunk-X4FR5BZF.js +9 -0
  103. package/dist/chunk-X6RKPDY7.js +2 -0
  104. package/dist/{chunk-ZXJYMGD3.js → chunk-YLFORA5G.js} +2 -2
  105. package/dist/{chunk-KP6XRY5Z.js → chunk-YTVWB7YJ.js} +2 -2
  106. package/dist/{chunk-4XTA5OMB.js → chunk-ZCEJ63SP.js} +2 -2
  107. package/dist/{chunk-HKEHS2AS.js → chunk-ZJ5CBXK3.js} +2 -2
  108. package/dist/chunk-ZL2OGDCD.js +2 -0
  109. package/dist/cli.js +8 -3
  110. package/dist/command-descriptors-ZW5J4ZEM.js +631 -0
  111. package/dist/{config-types-D20KuvvZ.d.ts → config-types-B6MEoRNy.d.ts} +8 -0
  112. package/dist/{db-G_II8yXU.d.ts → db-DYLKr9Wn.d.ts} +18 -1
  113. package/dist/direct-navigation-42YHQPOI.js +3 -0
  114. package/dist/{health-oblXYgkF.d.ts → health-DgxIDXJC.d.ts} +1 -1
  115. package/dist/index.d.ts +2 -2
  116. package/dist/index.js +1 -1
  117. package/dist/postinstall.js +1 -1
  118. package/dist/queries/affected.d.ts +2 -2
  119. package/dist/queries/affected.js +1 -1
  120. package/dist/queries/architecture.d.ts +2 -2
  121. package/dist/queries/architecture.js +1 -1
  122. package/dist/queries/bottlenecks.d.ts +2 -2
  123. package/dist/queries/bottlenecks.js +1 -1
  124. package/dist/queries/by-kind.d.ts +2 -2
  125. package/dist/queries/by-kind.js +1 -1
  126. package/dist/queries/call-graph.d.ts +2 -2
  127. package/dist/queries/call-graph.js +1 -1
  128. package/dist/queries/change-surface.d.ts +2 -2
  129. package/dist/queries/change-surface.js +1 -1
  130. package/dist/queries/cleanup-plan.d.ts +2 -2
  131. package/dist/queries/cleanup-plan.js +1 -1
  132. package/dist/queries/co-change.d.ts +2 -2
  133. package/dist/queries/co-change.js +1 -1
  134. package/dist/queries/code.d.ts +2 -2
  135. package/dist/queries/code.js +1 -1
  136. package/dist/queries/complexity-hotspots.d.ts +2 -2
  137. package/dist/queries/complexity-hotspots.js +1 -1
  138. package/dist/queries/complexity.d.ts +2 -2
  139. package/dist/queries/complexity.js +1 -1
  140. package/dist/queries/convergence.d.ts +2 -2
  141. package/dist/queries/convergence.js +1 -1
  142. package/dist/queries/coupling.d.ts +2 -2
  143. package/dist/queries/coupling.js +1 -1
  144. package/dist/queries/cycles.d.ts +2 -2
  145. package/dist/queries/cycles.js +1 -1
  146. package/dist/queries/dataflow.d.ts +2 -2
  147. package/dist/queries/dataflow.js +1 -1
  148. package/dist/queries/dead.d.ts +2 -2
  149. package/dist/queries/dead.js +1 -1
  150. package/dist/queries/decorative-checkers.d.ts +3 -3
  151. package/dist/queries/decorative-checkers.js +1 -1
  152. package/dist/queries/deep-chains.d.ts +2 -2
  153. package/dist/queries/deep-chains.js +1 -1
  154. package/dist/queries/deps.d.ts +2 -2
  155. package/dist/queries/deps.js +1 -1
  156. package/dist/queries/diff-gate.d.ts +30 -2
  157. package/dist/queries/diff-gate.js +1 -1
  158. package/dist/queries/diff-impact.d.ts +2 -2
  159. package/dist/queries/diff-impact.js +1 -1
  160. package/dist/queries/doc-drift.d.ts +2 -2
  161. package/dist/queries/doc-drift.js +1 -1
  162. package/dist/queries/drift.d.ts +2 -2
  163. package/dist/queries/drift.js +1 -1
  164. package/dist/queries/duplicate-bodies.d.ts +2 -2
  165. package/dist/queries/duplicate-bodies.js +1 -1
  166. package/dist/queries/extract-candidates.d.ts +2 -2
  167. package/dist/queries/extract-candidates.js +1 -1
  168. package/dist/queries/fan.d.ts +2 -2
  169. package/dist/queries/fan.js +1 -1
  170. package/dist/queries/files.d.ts +2 -2
  171. package/dist/queries/health.d.ts +3 -3
  172. package/dist/queries/health.js +1 -1
  173. package/dist/queries/hierarchy.d.ts +2 -2
  174. package/dist/queries/hierarchy.js +1 -1
  175. package/dist/queries/hotspots.d.ts +2 -2
  176. package/dist/queries/hotspots.js +1 -1
  177. package/dist/queries/imports.d.ts +2 -2
  178. package/dist/queries/imports.js +1 -1
  179. package/dist/queries/incomplete-migration.d.ts +2 -2
  180. package/dist/queries/incomplete-migration.js +1 -1
  181. package/dist/queries/index.d.ts +17 -3
  182. package/dist/queries/index.js +1 -1
  183. package/dist/queries/isolated.d.ts +2 -2
  184. package/dist/queries/isolated.js +1 -1
  185. package/dist/queries/locality-candidates.d.ts +2 -2
  186. package/dist/queries/locality-candidates.js +1 -1
  187. package/dist/queries/members.d.ts +2 -2
  188. package/dist/queries/members.js +1 -1
  189. package/dist/queries/methods.d.ts +2 -2
  190. package/dist/queries/methods.js +1 -1
  191. package/dist/queries/not-implemented.d.ts +3 -3
  192. package/dist/queries/not-implemented.js +1 -1
  193. package/dist/queries/outline.d.ts +2 -2
  194. package/dist/queries/outline.js +1 -1
  195. package/dist/queries/passthrough-candidates.d.ts +2 -2
  196. package/dist/queries/passthrough-candidates.js +1 -1
  197. package/dist/queries/plan-context.d.ts +2 -2
  198. package/dist/queries/plan-context.js +1 -1
  199. package/dist/queries/react-component-duplicates.d.ts +2 -2
  200. package/dist/queries/react-component-duplicates.js +1 -1
  201. package/dist/queries/react-hook-candidates.d.ts +2 -2
  202. package/dist/queries/react-hook-candidates.js +1 -1
  203. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  204. package/dist/queries/react-large-component-pressure.js +1 -1
  205. package/dist/queries/recent-duplicates.d.ts +2 -2
  206. package/dist/queries/recent-duplicates.js +1 -1
  207. package/dist/queries/redundant-reexports.d.ts +2 -2
  208. package/dist/queries/redundant-reexports.js +1 -1
  209. package/dist/queries/refs.d.ts +2 -2
  210. package/dist/queries/refs.js +1 -1
  211. package/dist/queries/self-audit.d.ts +2 -2
  212. package/dist/queries/self-audit.js +1 -1
  213. package/dist/queries/similar-chains.d.ts +2 -2
  214. package/dist/queries/similar-chains.js +1 -1
  215. package/dist/queries/similar-files.d.ts +2 -2
  216. package/dist/queries/similar-files.js +1 -1
  217. package/dist/queries/similar-signatures.d.ts +2 -2
  218. package/dist/queries/similar-signatures.js +1 -1
  219. package/dist/queries/similar.d.ts +2 -2
  220. package/dist/queries/similar.js +1 -1
  221. package/dist/queries/slice.d.ts +2 -2
  222. package/dist/queries/slice.js +1 -1
  223. package/dist/queries/stale-abstractions.d.ts +2 -2
  224. package/dist/queries/stale-abstractions.js +1 -1
  225. package/dist/queries/stats.d.ts +2 -2
  226. package/dist/queries/stats.js +1 -1
  227. package/dist/queries/surface.d.ts +2 -2
  228. package/dist/queries/surface.js +1 -1
  229. package/dist/queries/symbols.d.ts +2 -2
  230. package/dist/queries/symbols.js +1 -1
  231. package/dist/queries/system.d.ts +2 -2
  232. package/dist/queries/system.js +1 -1
  233. package/dist/queries/test-quality.d.ts +2 -2
  234. package/dist/queries/test-quality.js +1 -1
  235. package/dist/queries/trace.d.ts +2 -2
  236. package/dist/queries/trace.js +1 -1
  237. package/dist/queries/twin-ab.d.ts +3 -3
  238. package/dist/queries/twin-ab.js +1 -1
  239. package/dist/queries/twin-drift.d.ts +2 -2
  240. package/dist/queries/twin-drift.js +1 -1
  241. package/dist/queries/unused-imports.d.ts +2 -2
  242. package/dist/queries/unused-imports.js +1 -1
  243. package/dist/queries/unused-params.d.ts +2 -2
  244. package/dist/queries/unused-params.js +1 -1
  245. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  246. package/dist/queries/vue-component-duplicates.js +1 -1
  247. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  248. package/dist/queries/vue-composable-candidates.js +1 -1
  249. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  250. package/dist/queries/vue-large-view-pressure.js +1 -1
  251. package/dist/queries/wrapper-candidates.d.ts +2 -2
  252. package/dist/queries/wrapper-candidates.js +1 -1
  253. package/dist/reindex-worker.js +26 -26
  254. package/dist/reindex.d.ts +14 -4
  255. package/dist/reindex.js +34 -38
  256. package/dist/runtime.d.ts +167 -18
  257. package/dist/runtime.js +3 -2
  258. package/dist/rust-semantic-session-server.js +1 -1
  259. package/dist/rust-semantic-session-worker.js +1 -1
  260. package/dist/rust-semantic-worker.js +1 -1
  261. package/dist/{scip-cli-kRpaexVJ.d.ts → scip-cli-Cc6c00-a.d.ts} +6 -2
  262. package/dist/watch-server.js +5 -5
  263. package/docs/AGENT_GUIDE.md +20 -4
  264. package/docs/AI_FAILURE_MODES.md +17 -17
  265. package/docs/API_EVOLUTION.md +71 -0
  266. package/docs/CLI_JSON_OUTPUT.md +168 -0
  267. package/docs/COMMAND_REFERENCE.md +10 -6
  268. package/docs/COMMITTED_RECORD_COMPATIBILITY.md +117 -0
  269. package/docs/CONFIGURATION_WRITE_SAFETY.md +130 -0
  270. package/docs/DETECTOR_GUIDE.md +46 -46
  271. package/docs/DURABILITY.md +103 -0
  272. package/docs/INDEX_GENERATIONS.md +121 -0
  273. package/docs/LOCK_PROTOCOL.md +133 -0
  274. package/docs/MAILBOX_LIFECYCLE.md +197 -0
  275. package/docs/REINDEX_METADATA_COMPATIBILITY.md +84 -0
  276. package/docs/RUST_DURABLE_SESSION_PROTOCOL.md +126 -0
  277. package/docs/SECURITY_MODEL.md +129 -0
  278. package/docs/TELEMETRY_RETENTION.md +77 -0
  279. package/docs/TIME_SEMANTICS.md +77 -0
  280. package/docs/WATCH_REFRESH_REQUESTS.md +110 -0
  281. package/docs/WINDOWS_SIDECAR_RELEASE.md +298 -0
  282. package/docs/analyzer-validation-ledger.md +24 -23
  283. package/docs/schemas/cli-json-envelope.schema.json +53 -0
  284. package/docs/schemas/cli-output-page.schema.json +104 -0
  285. package/docs/schemas/npm-release-state.schema.json +146 -0
  286. package/docs/schemas/outcome-event-record.schema.json +39 -0
  287. package/docs/schemas/project-config.schema.json +247 -0
  288. package/docs/schemas/suppression-record.schema.json +31 -0
  289. package/docs/schemas/windows-sidecar-provenance.schema.json +137 -0
  290. package/package.json +21 -10
  291. package/scripts/build-scip-windows.mjs +180 -61
  292. package/scripts/scip-windows-provenance.mjs +364 -0
  293. package/scripts/verify-scip-windows.mjs +29 -0
  294. package/skills/_shared/SKILL.md +90 -229
  295. package/skills/_shared/agents/openai.yaml +1 -1
  296. package/skills/_shared/references/agent-contract-catalog.md +105 -0
  297. package/skills/_shared/references/command-catalog.md +118 -0
  298. package/skills/_shared/references/detector-precision-and-diffgate.md +59 -0
  299. package/skills/_shared/references/evidence-and-dead-code.md +25 -0
  300. package/skills/scip-audit/SKILL.md +77 -0
  301. package/skills/scip-audit/agents/openai.yaml +4 -0
  302. package/skills/scip-audit/references/claims.md +98 -0
  303. package/skills/scip-audit/references/cleanup.md +101 -0
  304. package/skills/scip-audit/references/directory.md +222 -0
  305. package/skills/scip-audit/references/frontend.md +130 -0
  306. package/skills/scip-audit/references/integrity.md +154 -0
  307. package/skills/scip-audit/references/maintainability.md +162 -0
  308. package/skills/scip-audit/references/twin-drift.md +104 -0
  309. package/skills/scip-diagnose/SKILL.md +52 -0
  310. package/skills/scip-diagnose/agents/openai.yaml +4 -0
  311. package/skills/scip-diagnose/references/debug.md +117 -0
  312. package/skills/{scip-probe-reachability/SKILL.md → scip-diagnose/references/probe-reachability.md} +11 -27
  313. package/skills/scip-diagnose/references/root-cause.md +145 -0
  314. package/skills/scip-diagnose/references/triage.md +119 -0
  315. package/skills/scip-explore/SKILL.md +54 -85
  316. package/skills/scip-explore/agents/openai.yaml +2 -2
  317. package/skills/scip-explore/references/diagrams.md +40 -0
  318. package/skills/scip-explore/references/language-playbook.md +49 -0
  319. package/skills/scip-improve/SKILL.md +56 -0
  320. package/skills/scip-improve/agents/openai.yaml +4 -0
  321. package/skills/scip-improve/references/cleanup-batches.md +53 -0
  322. package/skills/scip-improve/references/directory-moves.md +53 -0
  323. package/skills/scip-improve/references/doc-reconcile.md +30 -0
  324. package/skills/scip-improve/references/frontend-extraction.md +39 -0
  325. package/skills/scip-improve/references/maintainability-mechanism.md +43 -0
  326. package/skills/scip-improve/references/twin-drift.md +35 -0
  327. package/skills/scip-plan/SKILL.md +68 -0
  328. package/skills/scip-plan/agents/openai.yaml +4 -0
  329. package/skills/scip-plan/references/api-impact.md +19 -0
  330. package/skills/scip-plan/references/conductor.md +41 -0
  331. package/skills/scip-plan/references/high-assurance.md +43 -0
  332. package/skills/scip-plan/references/hyper-optimization.md +50 -0
  333. package/skills/scip-plan/references/tla-model.md +88 -0
  334. package/skills/scip-query/SKILL.md +53 -98
  335. package/skills/scip-query/agents/openai.yaml +2 -2
  336. package/skills/scip-setup/SKILL.md +69 -181
  337. package/skills/scip-setup/agents/openai.yaml +3 -3
  338. package/skills/scip-setup/references/bootstrap-workflow.md +120 -0
  339. package/skills/scip-setup/references/language-verification.md +61 -0
  340. package/skills/scip-setup/references/lifecycle-commands.md +119 -0
  341. package/skills/scip-setup/references/per-repo-triage.md +24 -0
  342. package/skills/scip-verify/SKILL.md +126 -84
  343. package/skills/scip-verify/agents/openai.yaml +2 -2
  344. package/skills/scip-verify/references/calibrate-detectors.md +170 -0
  345. package/dist/chunk-2CTX5CMX.js +0 -4
  346. package/dist/chunk-2Y373BDD.js +0 -2
  347. package/dist/chunk-2YU7I3QO.js +0 -2
  348. package/dist/chunk-3MJ5YA4Y.js +0 -16
  349. package/dist/chunk-64RFXJT5.js +0 -16
  350. package/dist/chunk-7UY7SD7D.js +0 -927
  351. package/dist/chunk-B5NLK2B3.js +0 -6
  352. package/dist/chunk-C2QSK7E7.js +0 -2
  353. package/dist/chunk-C7NIYIQ4.js +0 -67
  354. package/dist/chunk-D4U5Q3FT.js +0 -7
  355. package/dist/chunk-DGAGY7RJ.js +0 -60
  356. package/dist/chunk-DLWR3NUU.js +0 -5
  357. package/dist/chunk-K2ERX4UT.js +0 -3
  358. package/dist/chunk-KHE7J5ZN.js +0 -3
  359. package/dist/chunk-L7SPDE73.js +0 -84
  360. package/dist/chunk-LHMNRHGV.js +0 -3
  361. package/dist/chunk-LM72NQ7T.js +0 -3
  362. package/dist/chunk-MSWVMDAH.js +0 -122
  363. package/dist/chunk-NH7WNNQC.js +0 -20
  364. package/dist/chunk-NPKYOIFM.js +0 -18
  365. package/dist/chunk-NZL2DBT7.js +0 -2
  366. package/dist/chunk-OMPZHGHO.js +0 -2
  367. package/dist/chunk-P2PC2WGR.js +0 -2
  368. package/dist/chunk-Q3AFUTGB.js +0 -8
  369. package/dist/chunk-QRGV2F7L.js +0 -2
  370. package/dist/chunk-TW4OG5FC.js +0 -4
  371. package/dist/chunk-U7DSEKOM.js +0 -30
  372. package/dist/chunk-V27BEQJN.js +0 -7
  373. package/dist/chunk-XAGAZSFE.js +0 -6
  374. package/dist/chunk-XBN5VO53.js +0 -2
  375. package/dist/chunk-YGAGTIDK.js +0 -11
  376. package/dist/command-descriptors-N2TL4XM2.js +0 -613
  377. package/dist/direct-navigation-DUCZCTOE.js +0 -3
  378. package/skills/scip-api-impact/SKILL.md +0 -140
  379. package/skills/scip-api-impact/agents/openai.yaml +0 -4
  380. package/skills/scip-calibrate/SKILL.md +0 -131
  381. package/skills/scip-calibrate/agents/openai.yaml +0 -4
  382. package/skills/scip-claim-audit/SKILL.md +0 -107
  383. package/skills/scip-claim-audit/agents/openai.yaml +0 -4
  384. package/skills/scip-cleanup-audit/SKILL.md +0 -130
  385. package/skills/scip-cleanup-audit/agents/openai.yaml +0 -4
  386. package/skills/scip-cleanup-improve/SKILL.md +0 -85
  387. package/skills/scip-cleanup-improve/agents/openai.yaml +0 -4
  388. package/skills/scip-concrete-plan/HIGH_ASSURANCE.md +0 -317
  389. package/skills/scip-concrete-plan/SKILL.md +0 -105
  390. package/skills/scip-concrete-plan/agents/openai.yaml +0 -4
  391. package/skills/scip-conductor/SKILL.md +0 -133
  392. package/skills/scip-conductor/agents/openai.yaml +0 -4
  393. package/skills/scip-debug/SKILL.md +0 -130
  394. package/skills/scip-debug/agents/openai.yaml +0 -4
  395. package/skills/scip-diagram/SKILL.md +0 -110
  396. package/skills/scip-diagram/agents/openai.yaml +0 -4
  397. package/skills/scip-directory-architecture/SKILL.md +0 -266
  398. package/skills/scip-directory-architecture/agents/openai.yaml +0 -4
  399. package/skills/scip-doc-reconcile/SKILL.md +0 -89
  400. package/skills/scip-doc-reconcile/agents/openai.yaml +0 -4
  401. package/skills/scip-hyper-optimization/SKILL.md +0 -156
  402. package/skills/scip-hyper-optimization/agents/openai.yaml +0 -4
  403. package/skills/scip-integrity-audit/SKILL.md +0 -152
  404. package/skills/scip-integrity-audit/agents/openai.yaml +0 -4
  405. package/skills/scip-language-playbook/SKILL.md +0 -106
  406. package/skills/scip-language-playbook/agents/openai.yaml +0 -4
  407. package/skills/scip-maintainability/SKILL.md +0 -158
  408. package/skills/scip-maintainability/agents/openai.yaml +0 -4
  409. package/skills/scip-probe-reachability/agents/openai.yaml +0 -4
  410. package/skills/scip-react-maintainability/SKILL.md +0 -101
  411. package/skills/scip-react-maintainability/agents/openai.yaml +0 -4
  412. package/skills/scip-root-cause/SKILL.md +0 -151
  413. package/skills/scip-root-cause/agents/openai.yaml +0 -4
  414. package/skills/scip-tla-model-system/SKILL.md +0 -148
  415. package/skills/scip-tla-model-system/agents/openai.yaml +0 -4
  416. package/skills/scip-triage-issue/SKILL.md +0 -133
  417. package/skills/scip-triage-issue/agents/openai.yaml +0 -4
  418. package/skills/scip-twin-drift/SKILL.md +0 -109
  419. package/skills/scip-twin-drift/agents/openai.yaml +0 -4
  420. package/skills/scip-vue-maintainability/SKILL.md +0 -107
  421. package/skills/scip-vue-maintainability/agents/openai.yaml +0 -4
@@ -1,4 +1,5 @@
1
- import{A as At,Aa as me,B as Lt,C as Nt,D as jt,E as le,F as de,G as _t,I as Ot,J as _e,K as Wt,L as $t,P as Oe,S as Gt,T as pe,U as We,V as qt,W as Ut,X as H,a as gt,b as yt,c as St,d as Ee,e as bt,f as Fe,g as vt,ga as Ht,h as xt,i as Rt,ja as $e,k as Ae,l as Le,m as Ct,n as Mt,p as wt,pa as Bt,r as kt,ra as Vt,s as Pt,sa as fe,t as Ne,ta as Kt,u as je,ua as zt,v as Tt,va as Yt,w as Dt,wa as Ge,x as Et,y as Q,ya as B,z as Ft,za as Jt}from"./chunk-MSWVMDAH.js";import{b as ft,c as mt,f as It,h as J,l as U,m as ue}from"./chunk-C7NIYIQ4.js";import{a as j,b as F}from"./chunk-KHE7J5ZN.js";import{a as ce,c as ht,d as De,e as N}from"./chunk-HGFDYOVB.js";import k from"process";import{rmSync as Zr}from"fs";import{resolve as ao}from"path";import{pathToFileURL as co}from"url";import{readFileSync as rn,writeFileSync as bo,existsSync as nn}from"fs";import{isAbsolute as xo,join as on,relative as Io,resolve as Ro}from"path";var qe=".scipquery.json",sn=250,an=0,cn=10*6e4,ln={enabled:!1,debounceMs:sn,cooldownMs:an,gitPollMs:2e3,idleTimeoutMs:cn,autoRefresh:!0,ignore:[]},dn=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var Co=new Set(dn);function V(r){let e=on(r,qe);if(!nn(e))return{};try{let t=rn(e,"utf-8");return JSON.parse(t)}catch(t){let n=t instanceof Error?t.message:String(t);throw t instanceof SyntaxError?new Error(`invalid ${qe} at ${e}: ${n}`,{cause:t}):new Error(`unable to read ${qe} at ${e}: ${n}`,{cause:t})}}function he(r){return{...ln,...r.watch}}import{existsSync as Qt,readFileSync as un}from"fs";function Ue(r,e,t){let n=new Date().toISOString();if(!Qt(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Qt(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=JSON.parse(un(t.metaPath,"utf-8")),o=e.languages??$t(r),a=pn(r,o,e),s=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(a)&&JSON.stringify(s)===JSON.stringify(a.languages),l=Ht(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",u=c&&!d;return{state:u?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:d?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:u?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 pn(r,e,t){return It(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{fork as fn}from"child_process";import{statSync as mn}from"fs";import{isAbsolute as hn,join as gn,relative as yn}from"path";import{watch as Sn}from"chokidar";import bn from"ignore";var ge=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onRefreshSuppressed;onError;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=he(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.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=ue(e.projectRoot),this.extraIgnore=bn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,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(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=Xt(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}startSourceWatcher(e=!1){let t=Sn(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||!vn(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")||t.endsWith(Oe)||t.endsWith(`${Oe}.previous`)||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=hn(e)?e:gn(this.projectRoot,e);return yn(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=Xt(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=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex(t).then(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now();let o=!1;try{o=this.onReindexComplete(i)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(o){let s=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(s),this.setStatus({state:"idle"});return}let a=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,n)=>{let i=Date.now(),o=V(this.projectRoot),a=Object.keys(o).length>0?o:this.config,s=H(this.projectRoot,a),c=a.indexer?.typescript,l=a.indexer?.clojure,d=fn(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:s.indexPath,SCIP_REINDEX_OUTPUT_DB:s.dbPath,SCIP_REINDEX_LANGUAGES:(a.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(a.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});d.on("exit",u=>{u===0?t(Date.now()-i):n(new Error(`Reindex worker exited with code ${u}`))}),d.on("error",n)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let 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=Ee(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=bt(this.projectRoot,e),n={head:Ee(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=mn(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Xt(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 vn(r){return r instanceof Error&&"code"in r&&r.code==="EMFILE"||String(r).includes("EMFILE: too many open files")}import{existsSync as ir,statSync as kn}from"fs";import{join as Pn}from"path";import{createHash as xn}from"crypto";import{readFileSync as In}from"fs";import{dirname as Rn,join as ye}from"path";var X=2,Cn="typescript-semantic";function er(r){let e=ye(r,Cn);return{rootDir:e,requestDir:ye(e,"requests"),responseDir:ye(e,"responses")}}function Z(r){try{let e=JSON.parse(In(ye(Rn(r),"meta.json"),"utf8"));return e.version!==2&&e.version!==3||typeof e.status!="string"||typeof e.updatedAt!="string"||e.fingerprint===void 0?null:xn("sha256").update(JSON.stringify({version:e.version,status:e.status,updatedAt:e.updatedAt,fingerprint:e.fingerprint,indexedLanguages:e.indexedLanguages})).digest("hex")}catch{return null}}function tr(r){let e=JSON.parse(r);if(e.protocolVersion!==X||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||e.profileEnvironment!==void 0&&!Mn(e.profileEnvironment)||!e.request||!wn(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function Mn(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&Object.values(r).every(e=>typeof e=="string"||e===null)}function wn(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 Tt(e.files)!==null;case"references":return Zt(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Zt(e.definitions);case"signature":return rr(e.definition);default:return!1}}function Zt(r){return Array.isArray(r)&&r.every(rr)}function rr(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 Tn(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var nr;function Dn(r=Tn(),e=void 0){if(e===void 0&&nr?.projectRoot===r)return nr;let t=V(r),n=H(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(ir(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=Pn(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:En(o,n.dbPath),gitContext:e}}function or(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=Dn(r);if(!ir(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:$e(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=ue(r);return new Rt(c,l)}function En(r,e){let t="unknown time";try{t=kn(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{mkdirSync as Fr,readFileSync as Ar,readdirSync as Di,rmSync as Ei}from"fs";import{resolve as Re}from"path";import{resolve as Er}from"path";import{performance as y}from"perf_hooks";function Se(r){return{forFile(e,t){return sr(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,sr(r,i,t));return n}}}function sr(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=Dt(r,e)),t.lines&&(n.lines=Et(r,e)),t.ast&&(n.ast=Ft(r,e)),t.imports&&(n.imports=jt(r,e)),t.reexports&&(n.reexports=Nt(r,e)),i){let o=At(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 Fn={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function be(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=An(i);return{scheme:t,manager:n,packageName:o,version:a,descriptors:c,raw:r}}function K(r){let e=be(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 An(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||ar(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&&!ar(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=Fn[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function ar(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function _(r){let e=be(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 O(r){let e=be(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function cr(r){let e=O(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 Ln(r,e={}){if(K(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 lr(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!Ln(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 Nn=J("file-definitions",{clearGroups:["definition-catalog"]}),Rs=J("file-function-like-definitions",{clearGroups:["definition-catalog"]});function W(r,e,t={}){return t.includeClassMemberFallbacks?dr(r,e,void 0,{includeClassMemberFallbacks:!0}):Nn.get(r,e,()=>{let n=jn(r,e);if(n)return n;let i=dr(r,e),o=Le(r),a=Se(r).forFile(e,{text:!0}).text;return o&&a&&pr.write(r,e,Ae(r,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var pr=Mt({kind:"file-definitions",invalidation:wt("file-definitions"),serialize:_n,deserialize:On});function jn(r,e){let t=Le(r);if(!t)return null;let n=Se(r).forFile(e,{text:!0}).text;if(!n)return null;let i=pr.read(r,e,Ae(r,e,n));return i?Wn(i,t,e):null}function _n(r){return JSON.stringify(r)}function On(r){try{let e=JSON.parse(r);return!je(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function Wn(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=$n(i,t);if(!o)return null;n.push(o)}return n}function $n(r,e){return!je(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 dr(r,e,t,n={}){let i=lr(Gn(r,e),qn(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(Un);return t&&(i=i.filter(t)),Bn(r,e,i)}function Gn(r,e){return r.all(`SELECT
1
+ import{B as Mr,Ba as Vr,C as Tr,Ca as Ne,D as kr,Da as zr,E as ht,Ea as Jr,F as gt,Fa as Xr,G as Er,Ga as It,H as Dr,Ha as X,I as Fr,Ia as Qr,J as le,Ja as Le,K as Ar,L as _r,La as Zr,M as Nr,Ma as en,N as Lr,Na as tn,O as jr,P as we,Q as Pe,R as Or,T as Wr,U as yt,V as qr,Y as $r,a as ar,aa as Gr,c as Ie,da as Br,ea as Te,f as ot,g as lr,h as dr,i as K,k as st,l as fr,m as mr,n as hr,o as at,p as gr,q as ct,qa as Ur,r as br,s as vr,t as Rr,ta as St,u as Cr,w as ft,x as mt,y as wr,z as Pr,za as Hr}from"./chunk-VAXNI5NE.js";import{b as ce,f as J,g as Me}from"./chunk-IF6FP6B2.js";import{b as nr,c as ir,j as xr,m as ut,o as Ir}from"./chunk-C5Q44Q5D.js";import{A as Fe,B as Ae,C as xt,D as _e,a as or,b as ae,c as sr,g as ur,h as pr,i as F,j as A,k as lt,l as yr,m as dt,n as Sr,o as z,p as pt,q as Ce,s as bt,t as Yr,u as ke,v as vt,w as Kr,y as Ee,z as De}from"./chunk-X4FR5BZF.js";import{a as Re,c as cr,d as it,e as W}from"./chunk-HGFDYOVB.js";import{a as T}from"./chunk-APMMR5Y2.js";import{a as tr,g as rr,h as D}from"./chunk-46XGSFNI.js";import P from"process";import{rmSync as Ei}from"fs";import{resolve as na}from"path";import{pathToFileURL as ia}from"url";import{existsSync as Ai}from"fs";import{isAbsolute as xa,join as _i,relative as Ia,resolve as Ra}from"path";var $=1,Q=2,Fi="./node_modules/scip-query/docs/schemas/project-config.schema.json";function rn(r){let e=r;if(typeof r=="string")try{e=JSON.parse(r)}catch(a){return{kind:"malformed",reason:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}if(!or(e))return{kind:"malformed",reason:"project config must be a JSON object"};let t=e.schemaVersion;if(t!==void 0&&!Number.isInteger(t))return{kind:"malformed",reason:"schemaVersion must be an integer"};let n=t===void 0?$:t;if(n!==$&&n!==Q)return{kind:"unsupported",schemaVersion:n,direction:n<$?"older":"future"};let i=e.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=nn(e),s=n!==Q||typeof e.$schema!="string";return n===$?{kind:"legacy",sourceVersion:$,config:o,needsMigration:s}:{kind:"supported",sourceVersion:Q,config:o,needsMigration:s}}function nn(r){let e=r,{$schema:t,schemaVersion:n,...i}=e;return{$schema:typeof t=="string"&&t.trim()!==""?t:Fi,schemaVersion:Q,...i}}var je=".scipquery.json",Ni=250,Li=0,ji=10*6e4,Oi={enabled:!1,debounceMs:Ni,cooldownMs:Li,gitPollMs:2e3,idleTimeoutMs:ji,autoRefresh:!0,ignore:[]};var Ma=new Set(ar);function Z(r){let e=_i(r,je);if(!Ai(e))return{};let t;try{t=rr(e,{maxBytes:tr,inputKind:"scip-query project config"})}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`unable to read ${je} at ${e}: ${i}`,{cause:n})}return Wi(rn(t),e,"read").config}function Oe(r){return{...Oi,...r.watch}}function Wi(r,e,t){if(r.kind==="legacy"||r.kind==="supported")return r;if(r.kind==="malformed"){let i=t==="read"?`invalid ${je} at ${e}: ${r.reason}`:`Cannot update ${e}: the latest project config is ${r.reason}.`;throw new Error(`${i} The file was left untouched.`)}let n=t==="read"?`invalid ${je} at ${e}`:`Cannot update ${e}: the latest project config is invalid`;throw new Error(`${n} (unsupported ${r.direction} schemaVersion ${r.schemaVersion}; this scip-query reads legacy v${$} and current v${Q}). Upgrade scip-query before retrying; the file was left untouched.`)}import{existsSync as on}from"fs";function Rt(r,e,t){let n=new Date().toISOString();if(!on(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!on(t.metaPath))return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=Ie(D(t.metaPath,"reindex metadata"));if(i.kind==="unsupported")return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Reindex metadata version ${i.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(i.kind==="malformed")return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not decode reindex metadata: ${i.reason}`,remedy:"Run: scip-query reindex"};let o=i.metadata,s=e.languages??$r(r),a=qi(r,s,e),c=[...o.indexedLanguages??[]].sort(),l=i.capabilities.publishableGeneration&&JSON.stringify(o.fingerprint)===JSON.stringify(a)&&JSON.stringify(c)===JSON.stringify(a.languages),d=Ur(t.dbPath,t.metaPath),u=d.state==="invalid"||d.state==="drifted",p=l&&!u;return{state:p?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:o.updatedAt,lastRefresh:o.lastRefresh,reason:u?`SQLite generation requires repair: ${d.reason}`:l?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:p?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function qi(r,e,t){return Ir(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{statSync as $i}from"fs";import{basename as Gi,isAbsolute as Bi,join as Ui,relative as Hi}from"path";import{watch as Vi}from"chokidar";import Yi from"ignore";var We=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=Oe(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onReindexError=e.onReindexError??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.clock=e.clock??zi,this.reindexRunner=e.reindexRunner??to(),this.subscriptionFactory=e.subscriptionFactory??Ji,this.gitignoreFilter=Me(e.projectRoot),this.extraIgnore=Yi(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let e=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer();let t=this.activeOperation;return t&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"}),this.stopPromise=this.finishStop(e,t).finally(()=>{this.stopInProgress=!1}),this.stopPromise}requestRefresh(e,t={}){if(!this.stopped){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=an(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(e=!1){let t=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(n,i)=>this.isIgnoredWatchPath(n,i?.isDirectory()??!1),usePolling:e,...e?{interval:500,binaryInterval:1e3}:{}});t.on("all",(n,i)=>{this.stopped||this.handleFileChange(i)}),t.on("error",n=>this.handleSourceWatcherError(t,n,e)),this.fsWatchers.push(t)}handleSourceWatcherError(e,t,n){if(n||this.sourcePollingFallbackStarted||!ro(t)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==e),e.close();try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(e,t){let n=this.relativeWatchPath(e);if(!n)return!1;let i=t?`${n}/`:n;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||Gi(t).startsWith(Gr)||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=Bi(e)?e:Ui(this.projectRoot,e);return Hi(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=an(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let t=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let o=this.watchConfig.cooldownMs-e;this.dirty=!0;let s=this.wallNow()+o;this.setStatus({state:"cooldown",until:s,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},o);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=this.wallNow();this.setStatus({state:"indexing",startedAt:n});let i=this.reindexRunner.start(this.reindexRequest(t));this.activeOperation=i,i.completion.then(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let s=!1;try{s=this.onReindexComplete(o,t)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(s){let c=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(c),this.setStatus({state:"idle"});return}let a=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let s=o instanceof Error?o:new Error(String(o));this.onReindexError(s,t),this.onError(s),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===i&&(this.activeOperation=null)})}async finishStop(e,t){let n=[],i=t?t.cancel():null,o=await Promise.allSettled(e.map(s=>Promise.resolve().then(()=>s.close())));for(let s of o)s.status==="rejected"&&n.push(`watch subscription close failed: ${String(s.reason)}`);if(i)try{let s=await i;s.state==="degraded"&&n.push(s.reason)}catch(s){n.push(`reindex cancellation failed: ${s instanceof Error?s.message:String(s)}`)}return n.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:n.join("; ")}),{state:"degraded",reasons:n}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}reindexRequest(e){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:e}}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let n=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;n&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):n?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=at(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=gr(this.projectRoot,e),n={head:at(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=$i(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Ki(r){let{projectRoot:e,config:t,languages:n,pnpmWorkspaces:i,typescriptProjectMode:o,typescriptProjects:s,clojureConfigPath:a,indexerConcurrency:c,trigger:l}=r,d=Z(e),u=Object.keys(d).length>0?d:t,p=K(e,u),y=u.indexer?.typescript,f=u.indexer?.clojure;return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:e,SCIP_REINDEX_OUTPUT_SCIP:p.indexPath,SCIP_REINDEX_OUTPUT_DB:p.dbPath,SCIP_REINDEX_LANGUAGES:(u.languages??n)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(u.indexerConcurrency??c??""),SCIP_REINDEX_PNPM_WORKSPACES:y?.pnpmWorkspaces??i?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:y?.projectMode??o,projects:y?.projects??s??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:f?.configPath??a??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1"}}}var zi={now:T,wallNow:()=>Date.now(),setTimeout:(r,e)=>setTimeout(r,e),clearTimeout:r=>clearTimeout(r),setInterval:(r,e)=>setInterval(r,e),clearInterval:r=>clearInterval(r)},Ji=(r,e)=>Vi(r,e),Xi=15*6e4,Qi=1e3,Zi=64*1024;function eo(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function sn(r,e){let t=r instanceof Error?r.message:String(r),n=e.stderrTail.trim()||e.stdoutTail.trim();return n?`${t}
2
+ ${n}`:t}function to(r={}){let e=r.timeoutMs??Xi,t=r.terminationGraceMs??Qi,n=r.maxOutputBytes??Zi,i=r.resolveLaunch??Ki;return{start(o){let s=i(o),a=new AbortController,c=eo(),l=!1,d=en({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:e,terminationGraceMs:t,maxStdoutBytes:n,maxStderrBytes:n,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(u=>{if(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0)throw new Error(sn(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c));return u.durationMs}).catch(u=>{throw u instanceof Zr&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(sn(u,c),{cause:u})}).finally(()=>{l=!0});return{completion:d,async cancel(){l||a.abort();try{await d}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function an(r,e){return r?r.kind===e.kind?r.detail===e.detail?r:{kind:r.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${r.kind}, ${e.kind}`}:e}function ro(r){return r instanceof Error&&"code"in r&&r.code==="EMFILE"||String(r).includes("EMFILE: too many open files")}import{existsSync as fn,statSync as ao}from"fs";import{join as co}from"path";import{join as no}from"path";var ee=3,io=2,oo="typescript-semantic";function ln(r){let e=no(r,oo),t=Yr(e);return{...t,requestDir:t.legacyRequestDir}}function Ct(r){return Rr(r)}function dn(r){let e=JSON.parse(r),t=e.protocolVersion,n=t===io;if(!n&&t!==ee||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||!Number.isFinite(e.deadlineAtMs)||e.profileEnvironment!==void 0&&!sr(e.profileEnvironment)||!e.request||!so(e.request)||!n&&(e.mailboxVersion!==bt||typeof e.operationKey!="string"||!/^[a-f0-9]{64}$/.test(e.operationKey)||e.id!==Kr(e.operationKey)||typeof e.clientId!="string"||!e.clientId||typeof e.enqueuedAtMs!="number"||!Number.isFinite(e.enqueuedAtMs)||e.deadlineAtMs<e.enqueuedAtMs))throw new Error("TypeScript semantic service received an invalid mailbox request.");if(!n){let o=e,s=vt("typescript-semantic-v3",{generation:o.generation,profileEnvironment:o.profileEnvironment,request:o.request});if(o.operationKey!==s)throw new Error("TypeScript semantic service received a mismatched mailbox operation identity.");return o}let i=vt("typescript-semantic-v2",{id:e.id,generation:e.generation,request:e.request});return{protocolVersion:ee,mailboxVersion:bt,id:e.id,operationKey:i,clientId:"legacy-v2",enqueuedAtMs:e.deadlineAtMs,deadlineAtMs:e.deadlineAtMs,generation:e.generation,...e.profileEnvironment?{profileEnvironment:e.profileEnvironment}:{},request:e.request}}function so(r){if(!r||typeof r!="object"||!("kind"in r))return!1;let e=r;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return Er(e.files)!==null;case"references":return cn(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return cn(e.definitions);case"signature":return un(e.definition);default:return!1}}function cn(r){return Array.isArray(r)&&r.every(un)}function un(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}function lo(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var pn;function uo(r=lo(),e=void 0){if(e===void 0&&pn?.projectRoot===r)return pn;let t=Z(r),n=K(r,t),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:r,config:t,paths:n,dbPath:i,dbPathSource:"env",gitContext:e};if(fn(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=co(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:po(o,n.dbPath),gitContext:e}}function mn(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=uo(r);if(!fn(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:r,sharedEvidenceDbPath:St(r,t,a),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,architecture:t.architecture,coverageContracts:t.coverageContracts,docs:t.docs},l=Me(r);return new Cr(c,l)}function po(r,e){let t="unknown time";try{t=ao(r).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${r}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{randomUUID as ps}from"crypto";import{resolve as Bn}from"path";import{performance as S}from"perf_hooks";function qe(r){return{forFile(e,t){return hn(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,hn(r,i,t));return n}}}function hn(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=Dr(r,e)),t.lines&&(n.lines=Fr(r,e)),t.ast&&(n.ast=Ar(r,e)),t.imports&&(n.imports=jr(r,e)),t.reexports&&(n.reexports=Lr(r,e)),i){let o=_r(r,e),s=o.facts;t.facts&&(n.facts=s),o.unavailable&&(n.sourceFactsUnavailable=o.unavailable),t.identifiers&&s&&(n.identifiers=s.fileIdentifiers,n.identifierLineMap=s.identifierLineMap)}return n}var fo={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function $e(r){if(r.startsWith("local "))return{kind:"local",id:r.slice(6),raw:r};let e=r.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:r};let t=e[0],n=e[1],i=r.slice(t.length+1+n.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let c=mo(i);return{scheme:t,manager:n,packageName:o,version:s,descriptors:c,raw:r}}function te(r){let e=$e(r);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let n=e.descriptors[t];if(n?.suffix==="type")return n.name}return null}function mo(r){let e=[],t=0;for(;t<r.length;){if(r[t]==="["){let o=r.indexOf("]",t+1);if(o===-1){e.push({name:r.slice(t+1),suffix:"type-param"});break}e.push({name:r.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(r[t]==="("&&(e.length===0||t===0||gn(r[t-1]))){let o=r.indexOf(")",t+1);if(o!==-1&&r[o+1]!=="."){e.push({name:r.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let n;if(r[t]==="`"){let o=r.indexOf("`",t+1);if(o===-1){n=r.slice(t+1),e.push({name:n,suffix:"term"});break}n=r.slice(t+1,o),t=o+1}else{let o=t;for(;t<r.length&&!gn(r[t]);)t++;n=r.slice(o,t)}if(t>=r.length){n&&e.push({name:n,suffix:"term"});break}let i=r[t];if(i==="("){let o=r.indexOf(")",t+1);o!==-1&&r[o+1]==="."?(e.push({name:n,suffix:"method"}),t=o+2):o!==-1?(e.push({name:n,suffix:"method"}),t=o+1):(e.push({name:n,suffix:"term"}),t++)}else{let o=fo[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function gn(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function G(r){let e=$e(r);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function B(r){let e=$e(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function yn(r){let e=B(r);return e==="method"?!0:e!=="term"?!1:r.endsWith("().")?!0:r.startsWith("rust-analyzer ")&&r.includes("#")?!1:r.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(r):!0}function ho(r,e={}){if(te(r.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(r.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function Sn(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!ho(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||n.set(o.id,o);for(let o of r)n.set(o.id,o);let i=[...n.values()];return t.sort?i.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):i}var go=ce("file-definitions",{clearGroups:["definition-catalog"]}),Ec=ce("file-function-like-definitions",{clearGroups:["definition-catalog"]});function U(r,e,t={}){return t.includeClassMemberFallbacks?bn(r,e,void 0,{includeClassMemberFallbacks:!0}):go.get(r,e,()=>{let n=yo(r,e);if(n)return n;let i=bn(r,e),o=mt(r),s=qe(r).forFile(e,{text:!0}).text;return o&&s&&xn.write(r,e,ft(r,e,s),{projectFingerprint:o,definitions:i.map(a=>({...a}))}),i})}var xn=Pr({kind:"file-definitions",invalidation:Mr("file-definitions"),serialize:So,deserialize:bo});function yo(r,e){let t=mt(r);if(!t)return null;let n=qe(r).forFile(e,{text:!0}).text;if(!n)return null;let i=xn.read(r,e,ft(r,e,n));return i?vo(i,t,e):null}function So(r){return JSON.stringify(r)}function bo(r){try{let e=JSON.parse(r);return!gt(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function vo(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=xo(i,t);if(!o)return null;n.push(o)}return n}function xo(r,e){return!gt(r)||typeof r.symbolId!="number"||typeof r.symbol!="string"||typeof r.documentId!="number"||typeof r.startLine!="number"||typeof r.startChar!="number"&&r.startChar!==void 0||typeof r.endLine!="number"||typeof r.endChar!="number"&&r.endChar!==void 0||r.relativePath!==e||typeof r.leaf!="string"||typeof r.parentTypeName!="string"&&r.parentTypeName!==null||typeof r.isFunctionLike!="boolean"||typeof r.isTypeLike!="boolean"||typeof r.kind!="number"&&r.kind!==null||typeof r.documentation!="string"&&r.documentation!==null||typeof r.enclosingSymbol!="string"&&r.enclosingSymbol!==null?null:{symbolId:r.symbolId,symbol:r.symbol,documentId:r.documentId,startLine:r.startLine,startChar:r.startChar,endLine:r.endLine,endChar:r.endChar,relativePath:r.relativePath,leaf:r.leaf,parentTypeName:r.parentTypeName,isFunctionLike:r.isFunctionLike,isTypeLike:r.isTypeLike,kind:r.kind,documentation:r.documentation,enclosingSymbol:r.enclosingSymbol}}function bn(r,e,t,n={}){let i=Sn(Io(r,e),Ro(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(Co);return t&&(i=i.filter(t)),Po(r,e,i)}function Io(r,e){return r.all(`SELECT
2
3
  gs.id,
3
4
  gs.symbol,
4
5
  der.document_id,
@@ -16,7 +17,7 @@ import{A as At,Aa as me,B as Lt,C as Nt,D as jt,E as le,F as de,G as _t,I as Ot,
16
17
  JOIN documents d ON der.document_id = d.id
17
18
  WHERE d.relative_path = ?
18
19
  ${r.symbolNoiseFor("gs")}
19
- ORDER BY der.start_line, der.end_line`,e)}function qn(r,e){return r.all(`SELECT
20
+ ORDER BY der.start_line, der.end_line`,e)}function Ro(r,e){return r.all(`SELECT
20
21
  gs.id,
21
22
  gs.symbol,
22
23
  c.document_id,
@@ -37,7 +38,6 @@ import{A as At,Aa as me,B as Lt,C as Nt,D as jt,E as le,F as de,G as _t,I as Ot,
37
38
  AND m.role = 1
38
39
  ${r.symbolNoiseFor("gs")}
39
40
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
40
- ORDER BY start_line, end_line`,e)}function Un(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:_(r.symbol),parentTypeName:K(r.symbol),isFunctionLike:cr(r.symbol),isTypeLike:O(r.symbol)==="type",kind:r.kind??null,documentation:r.documentation??null,enclosingSymbol:r.enclosing_symbol??null}}function fr(r,e={}){return Hn(r,e.scope)}function Hn(r,e){return U(r,{scope:e,includeIgnored:!1}).flatMap(t=>W(r,t)).filter(t=>!r.isIgnored(t.relativePath))}function Bn(r,e,t){let n=Se(r).forFile(e,{text:!0}).text,i=Lt(r,e);return i?Qn(t,i,n):n?Vn(t,n):t}function Vn(r,e){let t=e.split(/\r?\n/),n=Kn(r,t),i=zn(r,n),o=Yn(i,t);return Jn(r,o)}function Kn(r,e){let t=r.some(i=>ve(i.symbol))?ii(e):null,n=new Map;for(let i of r)n.set(i.symbolId,ni(e,t,i));return n}function zn(r,e){return r.filter(t=>ve(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 Yn(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:oi(e,i.definition,i.startLine,a)})}return t}function Jn(r,e){return r.map(t=>{let n=e.get(t.symbolId);return n?{...t,startLine:n.startLine,endLine:n.endLine}:t})}function Qn(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(!ri(i)||!i.leaf)return ur(i,t);let o=n.get(i.leaf);if(!o||o.length===0)return ur(i,t);let a=t?Xn(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 Xn(r,e,t){let n=Zn(r.symbol);if(!n)return null;let i=t.split(/\r?\n/),o=new RegExp(`\\b${Q(n)}\\b`);for(let a of e){let s=ei(i,a.startLine);if(s&&o.test(s))return a}return null}function Zn(r){return r.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function ei(r,e){for(let t=e;t>=0;t-=1){let n=r[t]?.trim()??"";if(n){if(/^impl\b/.test(n))return ti(r,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(n))return null}}return null}function ti(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 ri(r){return ve(r.symbol)?!0:O(r.symbol)==="term"&&K(r.symbol)===null}function ur(r,e){if(!e||!r.leaf||O(r.symbol)!=="term"||K(r.symbol)!==null)return r;let t=Q(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 ni(r,e,t){if(!ve(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 ii(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 oi(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=si(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 si(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 ve(r){return r.includes("().")}function w(r,e,t){if(r.has(e))return r.get(e);let n=t();return r.set(e,n),n}import mr from"path";function ai(r,e){return r.getReferences().map(t=>{let n=t.getNode();return xe(n,e)})}function ci(r){let e=r;return typeof e.findReferences=="function"?e.findReferences():[]}function hr(r,e,t,n){let i=[];for(let o of ci(r))for(let a of ai(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 z(i)}function gr(r,e,t,n){let i=[],o=t?.getStart();for(let a of r.getReferences()){let s=a.getNode();Y(n,s.getSourceFile().getFilePath())===e&&(o!==void 0&&s.getStart()===o||i.push({location:xe(s,n),node:s}))}return i}function xe(r,e){let t=r.getSourceFile(),n=t.getLineAndColumnAtPos(r.getStart());return{file:Y(e,t.getFilePath())??t.getBaseName(),line:n.line-1,column:n.column-1}}function yr(r,e,t){let n=r.getSourceFile(),i=Be(n,r),o=r.getText(),a=new RegExp(`\\b${Q(o)}\\b`,"g"),s=n.getFullText().split(`
41
- `),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 z(c.filter(l=>Y(t,mr.join(t,l.file))===e))}function He(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 Be(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function z(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 Y(r,e){let t=mr.relative(r||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function Sr(r,e,t,n){let i=li(e,n);return i.size===0?new Map:di(r,t,i)}function li(r,e){let t=new Map;for(let n of W(r,e)){let i=_(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function di(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of ui(r,o)){let s=t.get(a);if(!s)continue;let c=Be(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 ui(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 pi=J("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function br(r,e,t,n){let i=ze(r,e),o=Ve(i.get(n)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||_(c.symbol)||"").includes(n)||c.symbol.includes(n))&&a.push(c);return Ve(a,t)}function Ke(r,e,t,n){return Ve(ze(r,e).get(n)??[],t)}function vr(r,e){let t=new Map;for(let[n,i]of ze(r,e)){let o=i[0];o&&t.set(n,o)}return t}function ze(r,e){return pi.get(r,e,()=>{let t=new Map;for(let n of W(r,e)){let i=n.leaf||_(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 Ve(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 Ye from"path";function xr(r,e){let t=new Map,n=null,i=null,o=()=>(i??=U(r,{extensions:le}),i),a=()=>(n??=N("typescript.source-file-index",()=>fi(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),s=c=>de(c)?w(t,c,()=>{let l=ee(Ye.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(ee(p.getFilePath()),p)),p)return{project:d,sourceFile:p}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function fi(r,e,t){let n=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[ee(o.getFilePath()),o]))}));for(let i of t){let o=ee(Ye.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(ee(s.getFilePath()),s);break}}}return n}function ee(r){return Ye.resolve(r)}function Je(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function Ir(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as te,readFileSync as mi}from"fs";import x from"path";var Qe=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Xe(r,e){let n=e?x.dirname(x.join(r,e)):r,i=x.resolve(r);for(;n.startsWith(i);){for(let a of Qe){let s=x.join(n,a);if(te(s))return s}let o=x.dirname(n);if(o===n)break;n=o}for(let o of Qe){let a=x.join(r,o);if(te(a))return a}return null}function Rr(r){let e=r.config.projectRoot,t=new Set(hi(e,r.config.semantic?.typescript?.tsconfigs)),n=U(r,{includeIgnored:!1,extensions:le});for(let i of n){let o=Xe(e,i);o&&t.add(x.resolve(o))}if(t.size===0){let i=Xe(e);i&&t.add(x.resolve(i))}return[...t].filter(i=>!Cr(e,i)).sort((i,o)=>i.localeCompare(o))}function hi(r,e=[]){let t=new Set;for(let n of e){let i=x.isAbsolute(n)?n:x.join(r,n);te(i)&&t.add(x.resolve(i))}for(let n of gi(r))for(let i of Qe){let o=x.join(n,i);te(o)&&t.add(x.resolve(o))}if(t.size===0){let n=Xe(r);n&&t.add(x.resolve(n))}return[...t].filter(n=>!Cr(r,n)).sort((n,i)=>n.localeCompare(i))}function gi(r){let e=x.join(r,"package.json");if(!te(e))return[];let t;try{t=JSON.parse(mi(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>Pt(r,i))}function Cr(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 yi=32;function Dr(r,e,t,n={}){return N("typescript.provider.construct",()=>new et(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var et=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=kt(e.config.projectRoot),this.sourceFiles=xr(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 w(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=bi();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return w(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=ce(),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=>!wr(d));if(s.length>=yi){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=>wr(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=kr();N("typescript.references-map.file",()=>{let g=this.definitionNodesForFile(d);for(let f of u){i&&(p.cacheMisses+=1);let m=g.get(f.symbolId)??null;i&&(m?p.nodeHits+=1:p.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,m,i?p:void 0);this.referencesCache.set(f.symbolId,h),n.set(f.symbolId,h)}catch{p.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:u.length,...Pr(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=fr(this.db).filter(o=>de(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return Wt(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=ce(),i=kr(),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 N("typescript.references-map.inverted-scan",()=>{let c=n?y.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let h of e){let S=l.get(h.symbolId)??[];if(S.length>0){let M=o.get(h.symbolId)??[];M.push(...S),o.set(h.symbolId,M)}n&&(i.packageReferenceCount+=S.length)}n&&(i.packageRefsMs+=y.now()-c);let d=new Map,u=new Map,p=this.hierarchyTargetsForDefinitions(e),g=new Set(e.map(h=>h.leaf).filter(Boolean)),f=n?y.now():0;for(let h of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let S=this.sourceFiles.sourceFile(h);S&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(S,h,a,s,p,g,d,u,o,n?i:void 0))}n&&(i.scanMs+=y.now()-f);let m=n?y.now():0;this.addHierarchyMemberReferences(e,o,n?i:void 0),n&&(i.hierarchyMs+=y.now()-m);for(let[h,S]of o){let M=z(S);o.set(h,M),n&&(i.referenceCount+=M.length)}},()=>({definitions:e.length,...Pr(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,a,s,c,l,d){let u=this.compilerCheckerForSourceFile(e),p=e.compilerNode,g=Ii(e),f=m=>{if(this.tsMorph.ts.isIdentifier(m)){if(d&&(d.identifiers+=1),!a.has(m.text)&&!g.has(m.text)){this.tsMorph.ts.forEachChild(m,f);return}let h=this.compilerReferenceSymbol(u,m,d);if(h){let S;s.has(h)?S=s.get(h)??null:(S=this.referenceDefinitionFromCompilerSymbol(h),s.set(h,S)),d&&(S?d.targetHits+=1:d.targetMisses+=1);let M=w(c,h,()=>this.compilerSymbolKeys(h)),A=null,P=null,L=S&&n.has(S.symbolId)?i.get(S.symbolId):void 0;if(L&&(A=Ze(p,m),!Mr(L,t,A))){let D=p.getLineAndCharacterOfPosition(m.getStart(p));P={file:t,line:D.line,column:D.character};let C=l.get(L.symbolId)??[];C.push(P),l.set(L.symbolId,C),d&&(d.requestedHits+=1)}for(let D of M)for(let C of o.get(D)?.values()??[]){if(A??=Ze(p,m),Mr(C,t,A))continue;if(!P){let I=p.getLineAndCharacterOfPosition(m.getStart(p));P={file:t,line:I.line,column:I.character}}let b=l.get(C.symbolId)??[];b.push(P),l.set(C.symbolId,b),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(m,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)),g={definition:o,location:{file:o.relativePath,line:p.line,column:p.character}},f=t.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,d))if(h!==d)for(let S of this.compilerSymbolLocations(h))f.push(S),n&&(n.hierarchyReferences+=1);t.set(o.symbolId,f);let m=this.hierarchyRootMemberSymbols(l,c,d);for(let h of m){let S=i.get(h)??new Map;S.set(o.symbolId,g),i.set(h,S)}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=Y(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 w(this.calleesCache,e.symbolId,()=>w(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?y.now():0,o=this.packageImportReferencesForDefinition(e);if(n&&(n.packageRefsMs+=y.now()-i,n.packageReferenceCount+=o.length),!t)return o;let a=n?y.now():0,s=hr(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=y.now()-a,n.referenceCount+=s.length),s}signatureFor(e){return w(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 Tr(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${Tr(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let a of t.getImportDeclarations()){n.declarations+=1;let s=Ne(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of tt(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||vi(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:xe(a,this.db.config.projectRoot),node:a}),n.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?Si(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 gr(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=>!He(c.node)),a=i.some(c=>He(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=Je(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,z(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,z(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=Je(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of tt(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=yr(s.identifier,n,this.db.config.projectRoot);l.length>0&&wi(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 Ir(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?Ne(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,g=this.indexedDefinitionByLeaf(c,u);if(!g)continue;let f=n.get(p);f||(f=new Set,n.set(p,f)),f.add(g.symbolId)}}}indexedDefinitionByLeaf(e,t){return w(this.indexedDefinitionLeafCache,e,()=>vr(this.db,e)).get(t)??null}nodeForDefinition(e){return w(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return w(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?Sr(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?y.now():0,a=e.declarations??[];t&&(t.declarationsMs+=y.now()-o,t.declarationChecks+=a.length);for(let s of a){let c=t?y.now():0,l=s.getSourceFile(),d=Y(this.db.config.projectRoot,l.fileName),u=l.getLineAndCharacterOfPosition(s.getStart(l)).line;if(t&&(t.declarationLocationMs+=y.now()-c),!d||this.db.isIgnored(d))continue;let p=t?y.now():0,g=this.compilerDeclarationName(s),f=n?Ke(this.db,d,u,i)??(g&&g!==i?Ke(this.db,d,u,g):null):br(this.db,d,u,i);if(t&&(t.indexedLookupMs+=y.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=ce(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,u=0,p=n?Ci():void 0;return N("typescript.callee-map.file",()=>{let g=n?y.now():0,f=this.sourceFiles.sourceFile(e);if(n&&(c=Math.round(y.now()-g)),!f)return new Map;let m=n?y.now():0,h=W(this.db,e).sort((b,I)=>b.startLine-I.startLine||I.endLine-b.endLine);if(n&&(l=Math.round(y.now()-m)),i=h.length,h.length===0)return new Map;let S=new Map,M=n?y.now():0,A=this.compilerCheckerForSourceFile(f),P=f.compilerNode;n&&(d=Math.round(y.now()-M));let L=new Map,D=b=>{if(this.tsMorph.ts.isCallExpression(b)||this.tsMorph.ts.isNewExpression(b)){n&&(o+=1);let I=this.semanticCalleeForCallNode(A,P,h,b,L,t,p);I&&(n&&(a+=1),xi(S,I.callerId,I.target))}this.tsMorph.ts.forEachChild(b,D)},C=n?y.now():0;D(P),n&&(u=Math.round(y.now()-C));for(let[b,I]of S)S.set(b,ki(I));return s=S.size,S},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:u,...p?Mi(p):{}}))}semanticCalleeForCallNode(e,t,n,i,o,a,s){let c=s?y.now():0,l=Ri(n,Ze(t,i));if(s&&(s.callerLookupMs+=y.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 g=s?y.now():0;p=this.definitionFromCompilerSymbol(u,s),s&&(s.targetLookupMs+=y.now()-g),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?y.now():0,o=e.getSymbolAtLocation(t);if(n&&(n.expressionSymbolMs+=y.now()-i),o)return o;n&&(n.typeFallbacks+=1);let a=n?y.now():0,s=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=y.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 tt(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 Si(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 bi(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function vi(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function xi(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function Ii(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of tt(t))n.localName&&e.add(n.localName);return e}function Ri(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 Ze(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function Mr(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function wr(r){return r.symbol.includes("#")?O(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function Ci(){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 Mi(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 kr(){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 Pr(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function wi(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function ki(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 Tr(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ie=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??_t,this.discoverTsconfigs=t.discoverTsconfigs??Rr,this.createProjects=t.createProjects??Ot,this.createProvider=t.createProvider??((n,i,o)=>Dr(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=Pi(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"&&(Ti(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=_e("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=_e("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 Pi(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=rt(r.changes,"added"),n=rt(r.changes,"modified"),i=rt(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function rt(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function Ti(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(Er(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(Er(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var Ce=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 Ie(t)),this.generationIdentity=e.generationIdentity??Z,this.readSnapshot=e.readSnapshot??Li,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[...Fi(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[...Ai(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return ji(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(){let e=this.host?.snapshotStats();return{protocolVersion:X,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:e?.sessionsCreated??0,sessionsReused:e?.sessionsReused??0,sessionsRefreshed:e?.sessionsRefreshed??0,sessionsReplaced:e?.sessionsReplaced??0,projectsCreated:e?.projectsCreated??0}}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.config.dbPath);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.config.dbPath);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,Ni(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function nt(r){Fr(r.requestDir,{recursive:!0}),Fr(r.responseDir,{recursive:!0})}function Lr(r,e,t={}){nt(r);let n=0;for(let i of Di(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Re(r.requestDir,i),a=i.slice(0,-5),s=null;try{let c=tr(Ar(o,"utf8"));if(a=c.id,c.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript semantic request expired before processing.");s=ht(),De(c.profileEnvironment??{}),t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.generation,c.request);F(Re(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:X,id:a,generation:c.generation,response:l})}catch(c){F(Re(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:X,id:a,error:c instanceof Error?c.message:String(c)})}finally{s&&De(s),t.afterRequest?.(),Ei(o,{force:!0}),n+=1}}return n}function Fi(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function Ai(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function Li(r){try{let e=JSON.parse(Ar(Re(r,"..","meta.json"),"utf8"));return ft(e.fingerprint)}catch{return null}}function Ni(r,e){return e?mt(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function ji(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}import{mkdirSync as Nr,readFileSync as _i,readdirSync as Oi,rmSync as Wi}from"fs";import{resolve as Me}from"path";var we=class{projectRoot;currentGeneration;createEmitter;now;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=Me(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Vt,this.now=e.now??Date.now}handle(e,t){let n=this.now();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.now()-n;return this.requests+=1,this.lastRequestAtMs=this.now(),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(){let e=this.active?.emitter.snapshotStats();return{protocolVersion:fe,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:e?.initializations??0,programUpdates:e?.programUpdates??0,documentsEmitted:e?.documentsEmitted??0,documentsRemoved:e?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{}}}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 it(r){Nr(r.requestDir,{recursive:!0}),Nr(r.responseDir,{recursive:!0})}function jr(r,e,t={}){it(r);let n=0;for(let i of Oi(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Me(r.requestDir,i),a=i.slice(0,-5);try{let s=zt(_i(o,"utf8"));if(a=s.id,s.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(s.deadlineAtMs);let c=e.handle(s.baseGeneration,s.request);F(Me(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:fe,id:a,baseGeneration:s.baseGeneration,response:c})}catch(s){F(Me(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:fe,id:a,error:s instanceof Error?s.message:String(s)})}finally{t.afterRequest?.(),Wi(o,{force:!0}),n+=1}}return n}import{spawn as $i}from"child_process";import{closeSync as Gi,existsSync as qi,mkdirSync as Ui,openSync as Hi,readFileSync as Wr,rmSync as re,writeFileSync as Bi}from"fs";import{dirname as Vi,resolve as at}from"path";import{fileURLToPath as Na}from"url";var Ki=2e3,zi=10;function $r(r,e,t){let n=Fe(at(r));if(t&&Fe(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=yt(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 Gr(r){let e=r.runtime??Qi,t=B(r.cacheDir),n=Jt(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=Yi("stop",i);if(o.kind==="signal-stop")return _r(o.state.pid,r,e),ot(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return ot(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let a=ne(t.lockPath);return o.kind==="already-stopped"&&a&&e.isProcessAlive(a.pid)?(_r(a.pid,r,e),ot(t,a.pid,e),{disposition:"stopped",pid:a.pid}):{disposition:"already-stopped"}}function qr(r,e){F(r,e)}function Ur(r){try{let e=JSON.parse(Wr(r,"utf8"));return e.version!==1||!me(e.at)||e.refreshRequestedAt!==void 0&&!me(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 Hr(r,e,t={}){let n=t.pid??process.pid,i=t.isProcessAlive??j,o=()=>{},a=ne(r);if(a&&i(a.pid))return{acquired:!1,lockPath:r,message:Or(r,e,a),release:o};a&&re(r,{force:!0}),Ui(Vi(r),{recursive:!0});let s;try{s=Hi(r,"wx")}catch(d){if(Ji(d)==="EEXIST")return{acquired:!1,lockPath:r,message:Or(r,e,ne(r)),release:o};throw d}let c={version:1,pid:n,projectRoot:at(e),startedAt:(t.now??(()=>new Date))().toISOString()};Bi(s,`${JSON.stringify(c)}
42
- `);let l=!1;return{acquired:!0,lockPath:r,message:"",release:()=>{if(l)return;l=!0,Gi(s);let d=ne(r);d?.pid===c.pid&&d.startedAt===c.startedAt&&re(r,{force:!0})}}}function ne(r){try{let e=JSON.parse(Wr(r,"utf-8"));return e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!me(e.startedAt)?null:e}catch{return null}}function Yi(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:"replace",state:e.state}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return st(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 st(e)}default:return st(r)}}function Br(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function _r(r,e,t){if(!t.isProcessAlive(r))return;t.signalProcess(r);let n=e.stopTimeoutMs??Ki,i=t.now()+n;for(;t.now()<=i;){if(!t.isProcessAlive(r))return;t.sleep(zi)}throw new Error(`scip-query watch service pid ${r} did not stop within ${n}ms.`)}function ot(r,e,t){re(r.statePath,{force:!0}),re(r.activityPath,{force:!0}),ne(r.lockPath)?.pid===e&&!t.isProcessAlive(e)&&re(r.lockPath,{force:!0})}function Or(r,e,t){return`error: scip-query watch is already running for ${at(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}function Ji(r){return typeof r=="object"&&r&&"code"in r?r.code:void 0}var Qi={now:Date.now,isProcessAlive:j,spawnServer(r,e,t,n){if(!qi(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);$i(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 st(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as Yr,lstatSync as ke,readFileSync as ut,readdirSync as Jr,realpathSync as Vr,rmSync as ie,statSync as Xi}from"fs";import{join as R,resolve as $,sep as Kr}from"path";var Zi=3600*1e3,eo=2*1024*1024*1024,to=300*1e3;function ro(r){let e=r.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=no(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 no(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 Qr(r,e,t={}){if(!Ut())return{kind:"disabled"};let n=gt(r);if(!n)return{kind:"unavailable"};let i=R(We(),"repositories",n.repositoryId);if(!Yr(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=R(i,"gc-state.json"),s=so(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<to)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=vt(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=io(r,i,n.repositoryId,s?.unreferencedSince??{}),d=ro({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??Zi,budgetBytes:t.policy?.budgetBytes??eo}}),u=0,p=0;for(let m of d.deleteWorktrees){if(!Xr(m.lease))continue;let h=xt(R(m.lease.localCacheDir,"cache-lifecycle.lock"));if(h)try{if(lt(m.lease,!0))continue;try{Gr({projectRoot:m.lease.projectRoot,cacheDir:m.lease.localCacheDir,cliVersion:e})}catch{continue}if(lt(m.lease,!0))continue;ie(m.lease.localCacheDir,{recursive:!0,force:!0}),ie(m.leasePath,{force:!0}),p+=1}finally{h.release()}}for(let m of d.deleteLocks)ie(m.path,{force:!0});for(let m of d.deleteTemporaries)ie(m.path,{recursive:!0,force:!0});for(let m of d.deleteGenerations)ie(m.path,{recursive:!0,force:!0}),u+=m.size;Ct(R(i,"evidence.db"));let g={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:p,deletedGenerations:d.deleteGenerations.length,deletedBytes:u,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:g.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:g};return F(a,f,{spacing:2,trailingNewline:!0}),g}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function io(r,e,t,n){let i=new Set(St(r).map(l=>$(l.path))),o=[];for(let l of ct(R(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=R(e,"worktrees",l),u=oo(d);if(!u)continue;let p=$(u.projectRoot);o.push({leasePath:d,lease:u,managed:u.repositoryId===t&&Xr(u),live:i.has(p)||Yr(p),busy:lt(u)})}let a=[];for(let l of ct(R(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let u=R(e,"locks",l),p=dt(u),g=p!==void 0&&j(p),f=d[1];a.push({generationId:f,path:u,live:g})}let s=[],c=[];for(let l of ct(R(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let g=R(e,"generations",l),f=Number(d[1]);try{c.push({path:g,size:zr(g),live:Number.isSafeInteger(f)&&j(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let u=R(e,"generations",l),p;try{p=ke(u)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||s.push({generationId:l,path:u,size:zr(u),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function Xr(r){if(r.ownershipChecksum!==Bt(r)||$(r.localCacheDir)!==$(qt(r.projectRoot)))return!1;let e=$(We()),t=$(R(e,"projects")),n=$(r.localCacheDir);if(!n.startsWith(`${t}${Kr}`))return!1;try{let i=ke(e),o=ke(t),a=ke(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=Vr(t);return Vr(n).startsWith(`${s}${Kr}`)}catch{return!1}}function lt(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=dt(R(r.localCacheDir,n));if(i!==void 0&&j(i))return!0}let t=dt(B(r.localCacheDir).lockPath);return t!==void 0&&j(t)}function oo(r){try{let e=JSON.parse(ut(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 dt(r){try{let e=JSON.parse(ut(r,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function so(r){try{let e=JSON.parse(ut(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 ct(r){try{return Jr(r)}catch{return[]}}function zr(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of Jr(n,{withFileTypes:!0})){let o=R(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Xi(o).size)}}return e}var lo=1e3,uo=250,po=10;function fo(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function mo(r,e,t={}){let n=$r(r,e),i=n.projectRoot,o=V(i);o.watch={...o.watch,...t};let a=he(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=H(i,o),c=B(s.cacheDir),l=Hr(c.lockPath,i);if(!l.acquired)return;let d=Date.now(),u=d,p={state:"idle"},g,f,m,h=pe(s.dbPath),S=!1,M=!1,A=0,P=0,L=0,D=0,C,b,I=er(s.cacheDir),pt=Kt(s.cacheDir);nt(I),it(pt);let Pe=new Ce({openDb:()=>or(i)}),Te=new we({projectRoot:i,currentGeneration:()=>Yt(s.dbPath)}),E=(v=!1)=>{if(!M)return;let q=Date.now();!v&&q-P<lo||(P=q,qr(c.statePath,{version:1,protocolVersion:Ge,pid:k.pid,projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(d).toISOString(),heartbeatAt:new Date(q).toISOString(),lastActivityAt:new Date(u).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(u+a.idleTimeoutMs).toISOString()},watcher:p,...p.state==="idle"&&g?{indexGeneration:g}:{},...f?{lastRefresh:f}:{},...m?{lastError:m}:{},reindexActivity:h,typescriptSemantic:{...Pe.status(),...C===void 0?{}:{busyUntil:new Date(C).toISOString()}},typescriptIndex:{...Te.status(),...b===void 0?{}:{busyUntil:new Date(b).toISOString()}}}))},G=()=>{u=Date.now()},oe=new ge({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(v){p=v,v.state!=="idle"&&(g=void 0),v.state!=="idle"&&G(),E(!0)},onReindexComplete(){G();let v=Ue(i,o,s);return f=v.lastRefresh,g=v.state==="fresh"?Z(s.dbPath)??void 0:void 0,h=pe(s.dbPath),m=void 0,E(!0),v.state==="fresh"},onRefreshSuppressed(v){Gt(s.dbPath,v),h=pe(s.dbPath)},onError(v){G(),g=void 0,m={at:new Date().toISOString(),message:v.message},E(!0)}}),se=()=>{S=!0};k.once("SIGINT",se),k.once("SIGTERM",se);try{oe.start();let v=Ue(i,o,s);f=v.lastRefresh,g=v.state==="fresh"?Z(s.dbPath)??void 0:void 0;let q=fo(v.state);for(q&&oe.requestRefresh(q,{immediate:!0}),G(),M=!0,E(!0);!S;){let en=jr(pt,Te,{beforeRequest(T){b=T+5e3,E(!0)},afterRequest(){b=void 0,E(!0)}}),tn=Lr(I,Pe,{beforeRequest(T){C=T+5e3,E(!0)},afterRequest(){C=void 0,E(!0)}}),ae=Date.now();if(ae-D>=6e4&&(D=ae,Qr(i,e)),ae-L>=uo){L=ae;let T=Ur(c.activityPath);T&&T.atMs>u&&(u=T.atMs),T?.refreshRequestedAtMs!==void 0&&T.refreshRequestedAtMs>A&&(A=T.refreshRequestedAtMs,G(),oe.requestRefresh({kind:"watch-demand",detail:T.refreshDetail??"stale index observed by a command"},{immediate:!0}))}if((tn>0||en>0)&&(G(),E(!0)),E(),Br({watcher:p,lastActivityAtMs:u,nowMs:Date.now(),idleTimeoutMs:a.idleTimeoutMs}))break;await ho(po)}}finally{k.off("SIGINT",se),k.off("SIGTERM",se),Pe.closeTypeScriptService(),Te.close(),oe.stop(),Zr(c.statePath,{force:!0}),Zr(c.activityPath,{force:!0}),l.release()}}function ho(r){return new Promise(e=>setTimeout(e,r))}var go=k.argv[1]?co(ao(k.argv[1])).href:null;if(go===import.meta.url){let r=k.argv[2],e=k.argv[3],t=yo(k.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),k.exitCode=1;else try{await mo(r,e,t)}catch(n){console.error(`watch-service: ${n instanceof Error?n.message:String(n)}`),k.exitCode=1}}function yo(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{mo as runWatchServiceServer,fo as startupRefreshTrigger};
41
+ ORDER BY start_line, end_line`,e)}function Co(r){return{symbolId:r.id,symbol:r.symbol,documentId:r.document_id,startLine:r.start_line,startChar:r.start_char??0,endLine:r.end_line,endChar:r.end_char??0,relativePath:r.relative_path,leaf:G(r.symbol),parentTypeName:te(r.symbol),isFunctionLike:yn(r.symbol),isTypeLike:B(r.symbol)==="type",kind:r.kind??null,documentation:r.documentation??null,enclosingSymbol:r.enclosing_symbol??null}}function In(r,e={}){return wo(r,e.scope)}function wo(r,e){return J(r,{scope:e,includeIgnored:!1}).flatMap(t=>U(r,t)).filter(t=>!r.isIgnored(t.relativePath))}function Po(r,e,t){let n=qe(r).forFile(e,{text:!0}).text,i=Nr(r,e);return i?Fo(t,i,n):n?Mo(t,n):t}function Mo(r,e){let t=e.split(/\r?\n/),n=To(r,t),i=ko(r,n),o=Eo(i,t);return Do(r,o)}function To(r,e){let t=r.some(i=>Ge(i.symbol))?Wo(e):null,n=new Map;for(let i of r)n.set(i.symbolId,Oo(e,t,i));return n}function ko(r,e){return r.filter(t=>Ge(t.symbol)).map(t=>({definition:t,startLine:e.get(t.symbolId)??t.startLine})).sort((t,n)=>t.startLine-n.startLine||t.definition.startLine-n.definition.startLine||t.definition.symbol.localeCompare(n.definition.symbol))}function Eo(r,e){let t=new Map;for(let n=0;n<r.length;n+=1){let i=r[n],o=r[n+1],s=o?Math.max(i.startLine,o.startLine-1):e.length-1;t.set(i.definition.symbolId,{startLine:i.startLine,endLine:qo(e,i.definition,i.startLine,s)})}return t}function Do(r,e){return r.map(t=>{let n=e.get(t.symbolId);return n?{...t,startLine:n.startLine,endLine:n.endLine}:t})}function Fo(r,e,t=null){let n=new Map;for(let i of e){let o=n.get(i.name);o?o.push(i):n.set(i.name,[i])}return r.map(i=>{if(!jo(i)||!i.leaf)return vn(i,t);let o=n.get(i.leaf);if(!o||o.length===0)return vn(i,t);let s=t?Ao(i,o,t):null;if(s)return{...i,startLine:s.startLine,endLine:s.endLine};let a=o[0],c=Math.abs(a.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let d=o[l],u=Math.abs(d.startLine-i.startLine);u<c&&(a=d,c=u)}return{...i,startLine:a.startLine,endLine:a.endLine}})}function Ao(r,e,t){let n=_o(r.symbol);if(!n)return null;let i=t.split(/\r?\n/),o=new RegExp(`\\b${le(n)}\\b`);for(let s of e){let a=No(i,s.startLine);if(a&&o.test(a))return s}return null}function _o(r){return r.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function No(r,e){for(let t=e;t>=0;t-=1){let n=r[t]?.trim()??"";if(n){if(/^impl\b/.test(n))return Lo(r,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(n))return null}}return null}function Lo(r,e,t){let n=[];for(let i=e;i<=t;i+=1){let o=r[i]??"";if(n.push(o),o.includes("{"))break}return n.join(" ")}function jo(r){return Ge(r.symbol)?!0:B(r.symbol)==="term"&&te(r.symbol)===null}function vn(r,e){if(!e||!r.leaf||B(r.symbol)!=="term"||te(r.symbol)!==null)return r;let t=le(r.leaf),n=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${t}\\b`),o=e.split(/\r?\n/).findIndex(s=>n.test(s));return o>=0?{...r,startLine:o,endLine:o}:r}function Oo(r,e,t){if(!Ge(t.symbol))return t.startLine;let n=Math.max(0,Math.min(t.startLine,r.length-1));if(!e)return n;let i=e.get(t.leaf);if(!i||i.length===0)return n;let o=null;for(let s of i){let a=Math.abs(s-t.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??n}function Wo(r){let e=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,t=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,n=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\b([A-Za-z_$][\w$]*)\s*\(/g,o=new Map,s=(a,c)=>{let l=o.get(a);if(!l){o.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let a=0;a<r.length;a+=1){let c=r[a]??"";for(let d of c.matchAll(e))d[1]&&s(d[1],a);for(let d of c.matchAll(t))d[1]&&s(d[1],a);let l=c.match(n);l?.[1]&&s(l[1],a);for(let d of c.matchAll(i))d[1]&&s(d[1],a)}return o}function qo(r,e,t,n){let i=Math.max(t,Math.min(r.length-1,n)),o=Math.max(t,Math.min(i,e.endLine)),s=0,a=0,c=!1;for(let l=t;l<=i;l+=1){let d=$o(r[l]??"");for(let u of d)u==="{"?(s+=1,c=!0):u==="}"?s=Math.max(0,s-1):u==="("?a+=1:u===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function $o(r){let e="",t=null,n=!1;for(let i=0;i<r.length;i+=1){let o=r[i],s=r[i+1];if(!t&&o==="/"&&s==="/"){e+=" ".repeat(r.length-i);break}if(t){if(n){n=!1,e+=" ";continue}if(o==="\\"){n=!0,e+=" ";continue}o===t&&(t=null),e+=" ";continue}if(o==='"'||o==="'"||o==="`"){t=o,e+=" ";continue}e+=o}return e}function Ge(r){return r.includes("().")}function _(r,e,t){if(r.has(e))return r.get(e);let n=t();return r.set(e,n),n}import wn from"path";import{realpathSync as Rn}from"fs";function Go(r,e){return r.getReferences().map(t=>{let n=t.getNode();return Be(n,e)})}function Bo(r){let e=r;return typeof e.findReferences=="function"?e.findReferences():[]}function Pn(r,e,t,n){let i=[];for(let o of Bo(r))for(let s of Go(o,n))s.file===e.relativePath&&s.line>=e.startLine&&s.line<=e.endLine||i.push(s);for(let o of t)i.push(o);return re(i)}function Mn(r,e,t,n){let i=[],o=t?.getStart();for(let s of r.getReferences()){let a=s.getNode();ne(n,a.getSourceFile().getFilePath())===e&&(o!==void 0&&a.getStart()===o||i.push({location:Be(a,n),node:a}))}return i}function Be(r,e){let t=r.getSourceFile(),n=t.getLineAndColumnAtPos(r.getStart());return{file:ne(e,t.getFilePath())??t.getBaseName(),line:n.line-1,column:n.column-1}}function Tn(r,e,t){let n=r.getSourceFile(),i=Pt(n,r),o=r.getText(),s=new RegExp(`\\b${le(o)}\\b`,"g"),a=n.getFullText().split(`
42
+ `),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let d=a[l]??"";s.lastIndex=0;let u;for(;(u=s.exec(d))!==null;)c.push({file:e,line:l,column:u.index})}return re(c.filter(l=>ne(t,wn.join(t,l.file))===e))}function wt(r){for(let e=r;e;e=e.getParent()){let t=e.getKindName();if(t.includes("Type")||t==="InterfaceDeclaration"||t==="TypeAliasDeclaration")return!0;if(t==="CallExpression"||t==="NewExpression"||t==="ExpressionStatement")return!1}return!1}function Pt(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function re(r){let e=new Set,t=[];for(let n of r){let i=`${n.file}:${n.line}:${n.column}`;e.has(i)||(e.add(i),t.push(n))}return t}function ne(r,e){let t=r||process.cwd(),n=Cn(t,e);if(n)return n;try{return Cn(Rn(t),Rn(e))}catch{return null}}function Cn(r,e){let t=wn.relative(r,e).replace(/\\/g,"/");return!t||t===".."||t.startsWith("../")?null:t}function kn(r,e,t,n){let i=Uo(e,n);return i.size===0?new Map:Ho(r,t,i)}function Uo(r,e){let t=new Map;for(let n of U(r,e)){let i=G(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function Ho(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let s of Vo(r,o)){let a=t.get(s);if(!a)continue;let c=Pt(e,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),u=i.get(l.symbolId);u!==void 0&&u<=d||(i.set(l.symbolId,d),n.set(l.symbolId,o))}}}),n}function Vo(r,e){let t=[],n=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();n(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();n(i)}return r.Node.isIdentifier(e)&&n(e.getText()),t}var Yo=ce("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function En(r,e,t,n){let i=kt(r,e),o=Mt(i.get(n)??[],t);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||G(c.symbol)||"").includes(n)||c.symbol.includes(n))&&s.push(c);return Mt(s,t)}function Tt(r,e,t,n){return Mt(kt(r,e).get(n)??[],t)}function Dn(r,e){let t=new Map;for(let[n,i]of kt(r,e)){let o=i[0];o&&t.set(n,o)}return t}function kt(r,e){return Yo.get(r,e,()=>{let t=new Map;for(let n of U(r,e)){let i=n.leaf||G(n.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...n,leaf:i})}for(let n of t.values())n.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function Mt(r,e){let t=null,n=Number.POSITIVE_INFINITY;for(let i of r){let o=Math.abs(i.startLine-e);(o<n||o===n&&t&&i.startLine<t.startLine)&&(t=i,n=o)}return t}import Ko from"path";import{realpathSync as zo}from"fs";function Fn(r,e){let t=new Map,n=null,i=null,o=()=>(i??=J(r,{extensions:we}),i),s=()=>(n??=W("typescript.source-file-index",()=>Jo(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),a=c=>Pe(c)?_(t,c,()=>{let l=An(r.config.projectRoot,c);if(!l)return null;for(let{project:d,sourceFiles:u}of s()){let p=u.get(l)??null;if(p||(p=d.addSourceFileAtPathIfExists(l)??null,p&&Et(u,p)),p)return{project:d,sourceFile:p}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function Jo(r,e,t){let n=e.map(({project:i})=>{let o=new Map;for(let s of i.getSourceFiles())Et(o,s);return{project:i,sourceFiles:o}});for(let i of t){let o=An(r,i);if(o)for(let s of n){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){Et(s.sourceFiles,a);break}}}return n}function Et(r,e){let t=Dt(e.getFilePath());r.set(t,e);try{r.set(Dt(zo(t)),e)}catch(n){if(!ut(n))throw n}}function An(r,e){try{return Dt(xr(r,e,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(t){if(!ut(t))throw t;return null}}function Dt(r){return Ko.resolve(r)}function Ft(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function _n(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as de}from"fs";import x from"path";var At=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function _t(r,e){let n=e?x.dirname(x.join(r,e)):r,i=x.resolve(r);for(;n.startsWith(i);){for(let s of At){let a=x.join(n,s);if(de(a))return a}let o=x.dirname(n);if(o===n)break;n=o}for(let o of At){let s=x.join(r,o);if(de(s))return s}return null}function Nn(r){let e=r.config.projectRoot,t=new Set(Xo(e,r.config.semantic?.typescript?.tsconfigs)),n=J(r,{includeIgnored:!1,extensions:we});for(let i of n){let o=_t(e,i);o&&t.add(x.resolve(o))}if(t.size===0){let i=_t(e);i&&t.add(x.resolve(i))}return[...t].filter(i=>!Ln(e,i)).sort((i,o)=>i.localeCompare(o))}function Xo(r,e=[]){let t=new Set;for(let n of e){let i=x.isAbsolute(n)?n:x.join(r,n);de(i)&&t.add(x.resolve(i))}for(let n of Qo(r))for(let i of At){let o=x.join(n,i);de(o)&&t.add(x.resolve(o))}if(t.size===0){let n=_t(r);n&&t.add(x.resolve(n))}return[...t].filter(n=>!Ln(r,n)).sort((n,i)=>n.localeCompare(i))}function Qo(r){let e=x.join(r,"package.json");if(!de(e))return[];let t;try{t=JSON.parse(D(e,"project package manifest"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>kr(r,i))}function Ln(r,e){let t=x.relative(r,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var Zo=32;function Gn(r,e,t,n={}){return W("typescript.provider.construct",()=>new Lt(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var Lt=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=Tr(e.config.projectRoot),this.sourceFiles=Fn(e,n)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(e=>e.tsconfigPath)}}importUsage(e){return _(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=ts();return W("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return _(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=Re(),o=[];for(let d of e){let u=this.referencesCache.get(d.symbolId);u?n.set(d.symbolId,u):o.push(d)}if(o.length===0)return n;let s=o,a=t.exact?[]:o.filter(d=>!On(d));if(a.length>=Zo){let d=this.referencesForDefinitionsBySymbolScan(a);for(let u of a){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}if(s=o.filter(u=>On(u)),s.length===0)return n}let c=new Map;for(let d of s){let u=c.get(d.relativePath);u?u.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,u]of c){let p=Wn();W("typescript.references-map.file",()=>{let y=this.definitionNodesForFile(d);for(let f of u){i&&(p.cacheMisses+=1);let h=y.get(f.symbolId)??null;i&&(h?p.nodeHits+=1:p.nodeMisses+=1);try{let m=this.referencesForDefinitionNode(f,h,i?p:void 0);this.referencesCache.set(f.symbolId,m),n.set(f.symbolId,m)}catch{p.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:u.length,...qn(p)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let u of l){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}}return n}referenceFragmentsForFiles(e){let t=In(this.db).filter(o=>Pe(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return qr(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=Re(),i=Wn(),o=new Map,s=new Set(e.map(c=>c.symbolId)),a=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return W("typescript.references-map.inverted-scan",()=>{let c=n?S.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let m of e){let g=l.get(m.symbolId)??[];if(g.length>0){let R=o.get(m.symbolId)??[];R.push(...g),o.set(m.symbolId,R)}n&&(i.packageReferenceCount+=g.length)}n&&(i.packageRefsMs+=S.now()-c);let d=new Map,u=new Map,p=this.hierarchyTargetsForDefinitions(e),y=new Set(e.map(m=>m.leaf).filter(Boolean)),f=n?S.now():0;for(let m of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(m))continue;let g=this.sourceFiles.sourceFile(m);g&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(g,m,s,a,p,y,d,u,o,n?i:void 0))}n&&(i.scanMs+=S.now()-f);let h=n?S.now():0;this.addHierarchyMemberReferences(e,o,n?i:void 0),n&&(i.hierarchyMs+=S.now()-h);for(let[m,g]of o){let R=re(g);o.set(m,R),n&&(i.referenceCount+=R.length)}},()=>({definitions:e.length,...qn(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,s,a,c,l,d){let u=this.compilerCheckerForSourceFile(e),p=e.compilerNode,y=is(e),f=h=>{if(this.tsMorph.ts.isIdentifier(h)){if(d&&(d.identifiers+=1),!s.has(h.text)&&!y.has(h.text)){this.tsMorph.ts.forEachChild(h,f);return}let m=this.compilerReferenceSymbol(u,h,d);if(m){let g;a.has(m)?g=a.get(m)??null:(g=this.referenceDefinitionFromCompilerSymbol(m),a.set(m,g)),d&&(g?d.targetHits+=1:d.targetMisses+=1);let R=_(c,m,()=>this.compilerSymbolKeys(m)),M=null,k=null,O=g&&n.has(g.symbolId)?i.get(g.symbolId):void 0;if(O&&(M=Nt(p,h),!jn(O,t,M))){let j=p.getLineAndCharacterOfPosition(h.getStart(p));k={file:t,line:j.line,column:j.character};let N=l.get(O.symbolId)??[];N.push(k),l.set(O.symbolId,N),d&&(d.requestedHits+=1)}for(let j of R)for(let N of o.get(j)?.values()??[]){if(M??=Nt(p,h),jn(N,t,M))continue;if(!k){let C=p.getLineAndCharacterOfPosition(h.getStart(p));k={file:t,line:C.line,column:C.character}}let I=l.get(N.symbolId)??[];I.push(k),l.set(N.symbolId,I),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(h,f)};f(p)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let n of e){let i=this.nodeForDefinition(n),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let d of this.compilerSymbolKeys(l)){let u=t.get(d)??new Map;u.set(n.symbolId,n),t.set(d,u)}}return t}hierarchyMemberSymbols(e,t,n){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let d of l){let u=d.getProperty(n.name);u&&s(d,u,this.hierarchyAncestorTypesForType(e,d))}}};return s(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,n){let i=new Map;for(let o of e){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),d=l.getSymbolAtLocation(a.name);if(!d)continue;let u=a.getSourceFile(),p=u.getLineAndCharacterOfPosition(a.name.getStart(u)),y={definition:o,location:{file:o.relativePath,line:p.line,column:p.character}},f=t.get(o.symbolId)??[];for(let m of this.hierarchyMemberSymbols(l,c,d))if(m!==d)for(let g of this.compilerSymbolLocations(m))f.push(g),n&&(n.hierarchyReferences+=1);t.set(o.symbolId,f);let h=this.hierarchyRootMemberSymbols(l,c,d);for(let m of h){let g=i.get(m)??new Map;g.set(o.symbolId,y),i.set(m,g)}n&&(n.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){n&&(n.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=t.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),n&&(n.hierarchyReferences+=1));t.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(e,t,n){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let d=!1;for(let u of l){let p=u.getProperty(n.name);p&&(d=!0,s(u,p,this.hierarchyAncestorTypesForType(e,u)))}if(!d)for(let u of this.compilerSymbolKeys(c))i.add(u)};return s(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let n=t.getSourceFile();return`${n.fileName}\0${t.getStart(n)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let n of e.declarations??[]){let i=n.getSourceFile(),o=ne(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=n.name,a=i.getLineAndCharacterOfPosition((s??n).getStart(i));t.push({file:o,line:a.line,column:a.character})}return t}baseTypes(e,t){try{return e.getBaseTypes(t)??[]}catch{return[]}}hierarchyAncestorTypes(e,t){let n=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)n.add(e.getTypeAtLocation(o));return[...n]}hierarchyAncestorTypesForType(e,t){let n=new Set(this.baseTypes(e,t));for(let i of t.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let s of o.types)n.add(e.getTypeAtLocation(s));return[...n]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,t,n){n&&(n.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return n&&(n.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return _(this.calleesCache,e.symbolId,()=>_(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,n=new Map;for(let i of e){let o=n.get(i.relativePath);o?o.push(i):n.set(i.relativePath,[i])}for(let[i,o]of n){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),t.set(l.symbolId,d)}}return t}referencesForDefinitionNode(e,t,n){let i=n?S.now():0,o=this.packageImportReferencesForDefinition(e);if(n&&(n.packageRefsMs+=S.now()-i,n.packageReferenceCount+=o.length),!t)return o;let s=n?S.now():0,a=Pn(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=S.now()-s,n.referenceCount+=a.length),a}signatureFor(e){return _(this.signatureCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);if(!t||!this.tsMorph.Node.isFunctionDeclaration(t)&&!this.tsMorph.Node.isMethodDeclaration(t)&&!this.tsMorph.Node.isArrowFunction(t)&&!this.tsMorph.Node.isFunctionExpression(t)&&!this.tsMorph.Node.isConstructorDeclaration(t))return null;let n=t.getType().getCallSignatures()[0];if(!n)return null;let i=n.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return $n(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${$n(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let s of t.getImportDeclarations()){n.declarations+=1;let a=ht(this.db,e,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of jt(s)){n.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?n.bindingSymbols+=1:n.missingBindingSymbols+=1);let u={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(u),c||!l.localName||!d)continue;let p=o.get(l.localName);p?p.push(u):o.set(l.localName,[u])}}return o.size>0&&t.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||rs(s))return;n.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(n.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:Be(s,this.db.config.projectRoot),node:s}),n.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?es(e,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(n.fallbackEntries+=1,this.valueImportUsageForEntry(e,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(e,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(e,t,n){let i=n.identifier?n.identifier.findReferences():[],o=[];for(let s of i)for(let a of Mn(s,e,n.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(e,t,n,o)}valueImportUsageFromLocations(e,t,n,i){let o=i.some(c=>!wt(c.node)),s=i.some(c=>wt(c.node)),a=n.isTypeOnly;return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let t=new Map,n=new Set;for(let o of e){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=Ft(this.workspacePackages,a.getModuleSpecifierValue());c&&n.add(c)}}if(n.size===0)return t;let i=this.packageExportsForNames(n);for(let o of e)this.addPackageImportReferencesForDocument(t,i,o);for(let[o,s]of t)t.set(o,re(s));return t}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,t=this.packageExports();for(let n of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,n);for(let[n,i]of e)e.set(n,re(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,n){if(this.db.isIgnored(n))return;let i=this.sourceFiles.sourceFileMatch(n);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,n,o)}addPackageImportReferencesForDeclaration(e,t,n,i){let o=Ft(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=t.get(o);if(s)for(let a of jt(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Tn(a.identifier,n,this.db.config.projectRoot);l.length>0&&cs(e,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let t=new Map;for(let n of this.workspacePackages){if(!e.has(n.name))continue;let i=new Map;for(let o of _n(n))this.collectPackageExports(n,o,i,new Set);i.size>0&&t.set(n.name,i)}return t}collectPackageExports(e,t,n,i){if(i.has(t))return;i.add(t);let o=this.sourceFiles.sourceFile(t);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?ht(this.db,t,a):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(e,c,n,i);continue}for(let d of l){let u=d.getNameNode().getText(),p=d.getAliasNode()?.getText()??u,y=this.indexedDefinitionByLeaf(c,u);if(!y)continue;let f=n.get(p);f||(f=new Set,n.set(p,f)),f.add(y.symbolId)}}}indexedDefinitionByLeaf(e,t){return _(this.indexedDefinitionLeafCache,e,()=>Dn(this.db,e)).get(t)??null}nodeForDefinition(e){return _(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return _(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?kn(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,n=!1){let i=e.name,o=t?S.now():0,s=e.declarations??[];t&&(t.declarationsMs+=S.now()-o,t.declarationChecks+=s.length);for(let a of s){let c=t?S.now():0,l=a.getSourceFile(),d=ne(this.db.config.projectRoot,l.fileName),u=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(t&&(t.declarationLocationMs+=S.now()-c),!d||this.db.isIgnored(d))continue;let p=t?S.now():0,y=this.compilerDeclarationName(a),f=n?Tt(this.db,d,u,i)??(y&&y!==i?Tt(this.db,d,u,y):null):En(this.db,d,u,i);if(t&&(t.indexedLookupMs+=S.now()-p),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(e){let t=e.name;return t&&this.tsMorph.ts.isIdentifier(t)?t.text:null}calleeMapForFile(e,t){let n=Re(),i=0,o=0,s=0,a=0,c=0,l=0,d=0,u=0,p=n?ss():void 0;return W("typescript.callee-map.file",()=>{let y=n?S.now():0,f=this.sourceFiles.sourceFile(e);if(n&&(c=Math.round(S.now()-y)),!f)return new Map;let h=n?S.now():0,m=U(this.db,e).sort((I,C)=>I.startLine-C.startLine||C.endLine-I.endLine);if(n&&(l=Math.round(S.now()-h)),i=m.length,m.length===0)return new Map;let g=new Map,R=n?S.now():0,M=this.compilerCheckerForSourceFile(f),k=f.compilerNode;n&&(d=Math.round(S.now()-R));let O=new Map,j=I=>{if(this.tsMorph.ts.isCallExpression(I)||this.tsMorph.ts.isNewExpression(I)){n&&(o+=1);let C=this.semanticCalleeForCallNode(M,k,m,I,O,t,p);C&&(n&&(s+=1),ns(g,C.callerId,C.target))}this.tsMorph.ts.forEachChild(I,j)},N=n?S.now():0;j(k),n&&(u=Math.round(S.now()-N));for(let[I,C]of g)g.set(I,ls(C));return a=g.size,g},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:u,...p?as(p):{}}))}semanticCalleeForCallNode(e,t,n,i,o,s,a){let c=a?S.now():0,l=os(n,Nt(t,i));if(a&&(a.callerLookupMs+=S.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let d=i.expression,u=this.compilerSymbolForExpression(e,d,a),p=null;if(u)if(a&&(a.targetSymbolHits+=1),o.has(u))a&&(a.compilerSymbolCacheHits+=1),p=o.get(u)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let y=a?S.now():0;p=this.definitionFromCompilerSymbol(u,a),a&&(a.targetLookupMs+=S.now()-y),o.set(u,p)}else a&&(a.targetMisses+=1);return p?{callerId:l.symbolId,target:{symbol:p.symbol,file:p.file,line:p.line}}:null}compilerSymbolForExpression(e,t,n){let i=n?S.now():0,o=e.getSymbolAtLocation(t);if(n&&(n.expressionSymbolMs+=S.now()-i),o)return o;n&&(n.typeFallbacks+=1);let s=n?S.now():0,a=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=S.now()-s),a}compilerCheckerForSourceFile(e){let t=e.getProject(),n=this.compilerCheckerCache.get(t);return n||(n=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,n)),n}};function jt(r){let e=[],t=r.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});let n=r.getNamespaceImport();n&&e.push({identifier:n,importedName:"*",localName:n.getText(),kind:"namespace",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});for(let i of r.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(r.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function es(r,e,t){return{importer:r,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function ts(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function rs(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function ns(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function is(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of jt(t))n.localName&&e.add(n.localName);return e}function os(r,e){let t=null;for(let n of r)e<n.startLine||e>n.endLine||(!t||n.startLine>=t.startLine)&&(t=n);return t}function Nt(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function jn(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function On(r){return r.symbol.includes("#")?B(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function ss(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function as(r){return{...r,callerLookupMs:Math.round(r.callerLookupMs),expressionSymbolMs:Math.round(r.expressionSymbolMs),typeSymbolMs:Math.round(r.typeSymbolMs),targetLookupMs:Math.round(r.targetLookupMs),declarationsMs:Math.round(r.declarationsMs),declarationLocationMs:Math.round(r.declarationLocationMs),indexedLookupMs:Math.round(r.indexedLookupMs)}}function Wn(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function qn(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function cs(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function ls(r){let e=new Set,t=[];for(let n of r){let i=`${n.symbol}|${n.file}|${n.line}`;e.has(i)||(e.add(i),t.push(n))}return t}function $n(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ue=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??Or,this.discoverTsconfigs=t.discoverTsconfigs??Nn,this.createProjects=t.createProjects??Wr,this.createProvider=t.createProvider??((n,i,o)=>Gn(n,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let n=ds(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?n.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,n):(n.mode==="refresh"&&(us(this.projects,e.config.projectRoot,n),this.stats.sessionsRefreshed+=1),n):n}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=yt("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=yt("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function ds(r){let e=new Set;r.projectIdentityChanged&&e.add("project-identity-changed");for(let o of r.uncertainty)e.add(o);for(let o of r.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=Ot(r.changes,"added"),n=Ot(r.changes,"modified"),i=Ot(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function Ot(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function us(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(Bn(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(Bn(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var He=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new Ue(t)),this.generationIdentity=e.generationIdentity?t=>e.generationIdentity(t.config.dbPath):t=>t.generation.identity,this.readSnapshot=e.readSnapshot?t=>e.readSnapshot(t.config.dbPath):hs,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let n=this.host.semanticProvider();switch(this.available=n.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return n.availability();case"import-usage":return n.importUsage(t.file);case"references":return[...fs(n,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!n.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...n.referenceFragmentsForFiles(t.files)];case"callees":return[...ms(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return ys(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(e){let t=this.host?.snapshotStats();return{protocolVersion:ee,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:t?.sessionsCreated??0,sessionsReused:t?.sessionsReused??0,sessionsRefreshed:t?.sessionsRefreshed??0,sessionsReplaced:t?.sessionsReplaced??0,projectsCreated:t?.projectsCreated??0,...e?{mailbox:e}:{}}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),n=this.generationIdentity(t);if(!n||n!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let i=this.readSnapshot(t);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,gs(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function Wt(r){ke(r)}function Hn(r,e,t={}){Wt(r);let n=t.nowMs??Date.now(),i=Ee(r,{ownerId:t.ownerId??Ss,nowMs:n,limits:t.limits,owner:bs,liveness:vs}),o=0;for(let s of i){let a=s.requestId,c=null;try{let l=dn(De(s,t.limits));if(a=l.id,a!==s.requestId)throw new Error("TypeScript semantic request identity does not match its mailbox path.");if(l.deadlineAtMs<n)throw new Error("TypeScript semantic request expired before processing.");c=cr(),it(l.profileEnvironment??{}),t.beforeRequest?.(l.deadlineAtMs);let d=e.handle(l.generation,l.request);Fe(r,s,{ok:!0,protocolVersion:ee,id:a,generation:l.generation,response:d},{nowMs:n,limits:t.limits})}catch(l){let d=l instanceof Error?l.message:String(l);Ae(r,s,{ok:!1,protocolVersion:ee,id:a,error:d},d,{nowMs:n,limits:t.limits})}finally{c&&it(c),t.afterRequest?.(),o+=1}}return o}function Vn(r){return _e(r)}function fs(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function ms(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function hs(r){if(!r.generation.metadataRaw)return null;let e=Ie(r.generation.metadataRaw);return e.kind!=="legacy"&&e.kind!=="supported"||!e.capabilities.usableForEvidenceCache?null:nr(e.metadata.fingerprint)}function gs(r,e){return e?ir(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function ys(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}var Ss=`typescript-semantic-${process.pid}-${ps()}`,Un=F(process.pid),bs={pid:process.pid,...Un?{processIdentity:Un}:{}},vs={isProcessAlive:A,readProcessIdentity:F};import{randomUUID as xs}from"crypto";import{resolve as Is}from"path";var Ve=class{projectRoot;currentGeneration;createEmitter;wallNow;monotonicNow;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=Is(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Vr,this.wallNow=e.wallNow??e.now??Date.now,this.monotonicNow=e.monotonicNow??e.now??T}handle(e,t){let n=this.monotonicNow();try{if(this.currentGeneration()!==e)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(t);if(i.emitter.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),s=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),a=this.monotonicNow()-n;return this.requests+=1,this.lastRequestAtMs=this.wallNow(),this.lastDurationMs=a,this.lastError=null,this.unavailable=!1,{producerIdentity:s.producerIdentity,cold:s.stats.initializations>o.initializations,durationMs:a,fragments:s.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(e){let t=this.active?.emitter.snapshotStats();return{protocolVersion:Ne,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:t?.initializations??0,programUpdates:t?.programUpdates??0,documentsEmitted:t?.documentsEmitted??0,documentsRemoved:t?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{},...e?{mailbox:e}:{}}}close(){this.active=null}emitterFor(e){let t=`${e.tsconfigPath}\0${e.projectArgument}`;if(this.active&&this.active.sessionKey===t&&this.active.projectIdentity===e.projectIdentity)return this.active;let n=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!n.available)throw this.unavailable=!0,new Error(n.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:n.emitter},this.sessionsCreated+=1,this.active}};function qt(r){ke(r)}function Kn(r,e,t={}){qt(r);let n=t.nowMs??Date.now(),i=Ee(r,{ownerId:t.ownerId??Rs,nowMs:n,limits:t.limits,owner:Cs,liveness:ws}),o=0;for(let s of i){let a=s.requestId;try{let c=Jr(De(s,t.limits));if(a=c.id,a!==s.requestId)throw new Error("TypeScript index request identity does not match its mailbox path.");if(c.deadlineAtMs<n)throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.baseGeneration,c.request);Fe(r,s,{ok:!0,protocolVersion:Ne,id:a,baseGeneration:c.baseGeneration,response:l},{nowMs:n,limits:t.limits})}catch(c){let l=c instanceof Error?c.message:String(c);Ae(r,s,{ok:!1,protocolVersion:Ne,id:a,error:l},l,{nowMs:n,limits:t.limits})}finally{t.afterRequest?.(),o+=1}}return o}function zn(r){return _e(r)}var Rs=`typescript-index-${process.pid}-${xs()}`,Yn=F(process.pid),Cs={pid:process.pid,...Yn?{processIdentity:Yn}:{}},ws={isProcessAlive:A,readProcessIdentity:F};import{spawn as Ws}from"child_process";import{existsSync as qs,rmSync as pi}from"fs";import{dirname as id,resolve as Kt}from"path";import{fileURLToPath as sd}from"url";import{createHash as Ps,randomUUID as $t}from"crypto";import{existsSync as Ms,linkSync as Ts,mkdirSync as Jn,readdirSync as ks,rmSync as ie}from"fs";import{basename as Es,dirname as Ds,join as v}from"path";var H=1,Fs=10*6e4,As=10080*6e4,Ke="requests",ue="claims",Ye="completions",Qn="staging";function Zn(r,e,t={}){let n=t.now?.()??new Date,i=Ns(t.ttlMs),o=Ls(t.idempotencyKey),s=o?`key-${Ps("sha256").update(o).digest("hex")}`:`request-${(t.randomId??$t)()}`,a={version:H,requestId:s,...o?{idempotencyKey:o}:{},createdAt:n.toISOString(),deadlineAt:new Date(n.getTime()+i).toISOString(),detail:e.trim().slice(0,2048)||"stale index observed by a command"},c=li(r,s);if(Ut(r,c,a,t.onStage))return{disposition:"accepted",request:a};let d=Bt(c);if(!d)throw new Error(`Watch refresh request identity ${s} exists but is malformed.`);return{disposition:"duplicate",request:d}}function ei(r,e={}){let t=e.now?.()??new Date,n=`claim-${(e.randomId??$t)()}`,i=Math.max(1,Math.floor(e.limit??64)),o=si(r).sort(js),s=[];for(let a of o){if(s.length>=i)break;if(Xn(r,a.requestId))continue;if(Date.parse(a.deadlineAt)<=t.getTime()){oi(r,{version:H,requestId:a.requestId,outcome:"expired",completedAt:t.toISOString()});continue}let c={version:H,requestId:a.requestId,claimId:n,claimedAt:t.toISOString()};if(Ut(r,di(r,a.requestId),c)){if(Xn(r,a.requestId)){ai(r,a.requestId,n);continue}s.push(a)}}return{claimId:n,requests:s}}function ti(r,e,t=()=>new Date,n){let i=t().toISOString();for(let o of e.requests)oi(r,{version:H,requestId:o.requestId,claimId:e.claimId,outcome:"completed",completedAt:i});n?.("after-completion"),ze(r,e),n?.("after-claim-release")}function ze(r,e){for(let t of e.requests)ai(r,t.requestId,e.claimId)}function ri(r){let e=0;for(let t of V(v(r,ue)))ie(t,{force:!0}),e++;return e>0&&z(v(r,ue)),ci(r),e}function Gt(r){let e=si(r),t=new Map,n=_s(v(r,Ke),Bt);for(let c of V(v(r,Ye))){let l=Je(c);if(!l){n++;continue}t.set(l.requestId,l)}let i=new Set;for(let c of V(v(r,ue))){let l=ii(c);if(!l){n++;continue}i.add(l.requestId)}let o=e.filter(c=>!t.has(c.requestId)&&!i.has(c.requestId)),s=[...t.values()].filter(c=>c.outcome==="completed").length,a=[...t.values()].filter(c=>c.outcome==="expired").length;return{pending:o.length,claimed:e.filter(c=>!t.has(c.requestId)&&i.has(c.requestId)).length,completed:s,expired:a,invalid:n,...o.length>0?{oldestPendingAt:o.map(c=>c.createdAt).reduce((c,l)=>Os(c,l))}:{}}}function ni(r,e={}){let t=(e.now?.()??new Date).getTime(),n=Math.max(0,e.retentionMs??As),i=0;for(let o of V(v(r,Ye))){let s=Je(o);!s||t-Date.parse(s.completedAt)<n||(ie(o,{force:!0}),ie(li(r,s.requestId),{force:!0}),i++)}return i>0&&(z(v(r,Ye)),z(v(r,Ke))),ci(r),i}function Bt(r){return Ht(r,e=>{let t=e;return t.version===H&&pe(t.requestId)&&(t.idempotencyKey===void 0||typeof t.idempotencyKey=="string")&&ae(t.createdAt)&&ae(t.deadlineAt)&&Date.parse(t.deadlineAt)>=Date.parse(t.createdAt)&&typeof t.detail=="string"&&t.detail.length>0})}function ii(r){return Ht(r,e=>{let t=e;return t.version===H&&pe(t.requestId)&&pe(t.claimId)&&ae(t.claimedAt)})}function Je(r){return Ht(r,e=>{let t=e;return t.version===H&&pe(t.requestId)&&(t.claimId===void 0||pe(t.claimId))&&(t.outcome==="completed"||t.outcome==="expired")&&ae(t.completedAt)})}function oi(r,e){let t=ui(r,e.requestId);if(Ut(r,t,e))return;let n=Je(t);if(!n||n.requestId!==e.requestId||n.outcome!==e.outcome)throw new Error(`Watch refresh completion ${e.requestId} conflicts with an existing record.`)}function Ut(r,e,t,n){let i=v(r,Qn),o=Ds(e);Jn(i,{recursive:!0}),Jn(o,{recursive:!0});let s=v(i,`${Es(e)}.${process.pid}.${$t()}.tmp`);try{Ce(s,t,{spacing:2,trailingNewline:!0}),n?.("after-staged");try{Ts(s,e)}catch(a){if(a.code==="EEXIST")return!1;throw a}return z(o),n?.("after-published"),!0}finally{ie(s,{force:!0})}}function si(r){let e=[];for(let t of V(v(r,Ke))){let n=Bt(t);n&&e.push(n)}return e}function ai(r,e,t){let n=di(r,e),i=ii(n);!i||i.claimId!==t||(ie(n,{force:!0}),z(v(r,ue)))}function ci(r){for(let e of V(v(r,Qn),".tmp"))ie(e,{force:!0})}function _s(r,e){return V(r).filter(t=>!e(t)).length}function V(r,e=".json"){return Ms(r)?ks(r,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(e)).map(t=>v(r,t.name)).sort():[]}function Ht(r,e){try{let t=JSON.parse(D(r,"watch refresh request record"));return e(t)?t:null}catch{return null}}function li(r,e){return v(r,Ke,`${e}.json`)}function di(r,e){return v(r,ue,`${e}.json`)}function ui(r,e){return v(r,Ye,`${e}.json`)}function Xn(r,e){return Je(ui(r,e))!==null}function Ns(r){if(r===void 0)return Fs;if(!Number.isFinite(r)||r<=0)throw new Error("Watch refresh request ttlMs must be positive.");return Math.floor(r)}function Ls(r){let e=r?.trim();return e?e.slice(0,512):void 0}function pe(r){return typeof r=="string"&&/^[a-z0-9][a-z0-9-]{0,127}$/i.test(r)}function js(r,e){return Date.parse(r.createdAt)-Date.parse(e.createdAt)||r.requestId.localeCompare(e.requestId)}function Os(r,e){return Date.parse(e)<Date.parse(r)?e:r}var $s=2e3,Gs=10;function mi(r,e,t){let n=ct(Kt(r));if(t&&ct(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=mr(n);if(i.kind==="error")throw new Error(`Could not establish Git worktree identity for ${n}: ${i.message}`);return i.kind==="non-git"?{projectRoot:n,worktreeKind:"non-git",cliVersion:e}:{projectRoot:n,worktreeKind:"git",worktreeId:i.identity.worktreeId,cliVersion:e}}function hi(r){let e=r.runtime??Hs,t=X(r.cacheDir),n=Qr(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=Bs("stop",i);if(o.kind==="signal-stop")return fi(o.state,r,e),Vt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return Vt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let s=bi(t.lockPath);return o.kind==="already-stopped"&&s&&e.isProcessAlive(s.pid)?(fi(s,r,e),Vt(t,s.pid,e),{disposition:"stopped",pid:s.pid}):{disposition:"already-stopped"}}function gi(r,e){Ce(r,e)}function yi(r){try{let e=JSON.parse(D(r,"watch activity record"));return e.version!==1||!Le(e.at)||e.refreshRequestedAt!==void 0&&!Le(e.refreshRequestedAt)||e.refreshDetail!==void 0&&typeof e.refreshDetail!="string"?null:{atMs:Date.parse(e.at),...e.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(e.refreshRequestedAt)},...e.refreshDetail===void 0?{}:{refreshDetail:e.refreshDetail}}}catch{return null}}function Si(r,e,t={}){let n=t.pid??process.pid,i=t.isProcessAlive??A,o=()=>{},s=t.readProcessIdentity??F,a=t.now??(()=>new Date),c={...lt,wallNow:()=>a().getTime(),isProcessAlive:i,readProcessIdentity:s},l=yr(r,{kind:"watch",pid:n,processIdentity:s(n),detail:{projectRoot:Kt(e)},parseLegacy:Xe,runtime:c});if(l.kind==="contended"){let d=vi(l.observation);return{acquired:!1,lockPath:r,message:Us(r,e,d),release:o}}return{acquired:!0,lockPath:r,message:"",release:()=>{l.lock.release()}}}function bi(r){return vi(dt(r,{parseLegacy:Xe}))}var Xe=r=>{let e=xi(r);return e?{pid:e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{}}:null};function vi(r){if(r.state==="valid"&&r.record?.kind==="watch"){let e=r.record.detail?.projectRoot;return typeof e!="string"?null:{version:1,pid:r.record.pid,...r.record.processIdentity?{processIdentity:r.record.processIdentity}:{},projectRoot:e,startedAt:r.record.startedAt}}return xi(r.parsed)}function xi(r){try{let e=r;if(e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!Le(e.startedAt))return null;let t=e.processIdentity===void 0?null:ur(e.processIdentity);return e.processIdentity!==void 0&&(!t||t.pid!==e.pid)?null:{version:1,pid:e.pid,...t?{processIdentity:t}:{},projectRoot:e.projectRoot,startedAt:e.startedAt}}catch{return null}}function Bs(r,e){switch(r){case"status":return{kind:"report",classification:e};case"ensure":switch(e.kind){case"stopped":return{kind:"start"};case"stale":return e.reason==="old-heartbeat"?{kind:"refuse-replace",state:e.state,reason:"old-heartbeat"}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return Yt(e)}case"stop":switch(e.kind){case"stopped":return{kind:"already-stopped"};case"stale":return e.reason==="old-heartbeat"?{kind:"signal-stop",state:e.state}:{kind:"clean-stale",state:e.state};case"live":case"incompatible":return{kind:"signal-stop",state:e.state};default:return Yt(e)}default:return Yt(r)}}function Ii(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function fi(r,e,t){let{pid:n}=r;if(!t.isProcessAlive(n))return;Vs(r,t),t.signalProcess(n);let i=e.stopTimeoutMs??$s,o=t.monotonicNow??T,s=o()+i;for(;o()<=s;){if(!t.isProcessAlive(n))return;t.sleep(Gs)}throw new Error(`scip-query watch service pid ${n} did not stop within ${i}ms.`)}function Vt(r,e,t){if(pi(r.statePath,{force:!0}),pi(r.activityPath,{force:!0}),bi(r.lockPath)?.pid===e&&!t.isProcessAlive(e)){let i={...lt,wallNow:t.now,isProcessAlive:t.isProcessAlive,readProcessIdentity:t.readProcessIdentity},o=dt(r.lockPath,{parseLegacy:Xe,runtime:i});Sr(r.lockPath,o,{parseLegacy:Xe,runtime:i})}}function Us(r,e,t){return`error: scip-query watch is already running for ${Kt(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}var Hs={now:Date.now,monotonicNow:T,isProcessAlive:A,readProcessIdentity:F,spawnServer(r,e,t,n){if(!qs(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);Ws(process.execPath,[r,e,t,JSON.stringify(n)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(r){process.kill(r,"SIGTERM")},sleep(r){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,r)}};function Vs(r,e){if(!r.processIdentity)throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its ownership record has no process identity.`);let t=e.readProcessIdentity(r.pid);if(!t)throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its process identity is unavailable.`);if(!pr(r.processIdentity,t))throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its process identity does not match the ownership record.`)}function Yt(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as Pi,lstatSync as Qe,readdirSync as Mi,realpathSync as Ri,rmSync as fe,statSync as Ys}from"fs";import{join as w,resolve as me,sep as Ci}from"path";var Ks=3600*1e3,zs=2*1024*1024*1024,Js=300*1e3;function Xs(r){let e=r.leases.filter(a=>a.managed&&!a.live&&!a.busy),t=Qs(r.leases,r.locks),n={};for(let a of r.generations)t.has(a.generationId)||(n[a.generationId]=a.unreferencedAt??r.nowMs);let i=r.generations.filter(a=>!t.has(a.generationId)).sort((a,c)=>n[a.generationId]-n[c.generationId]||a.generationId.localeCompare(c.generationId)),o=new Set;for(let a of i)r.nowMs-n[a.generationId]>=r.policy.generationTtlMs&&o.add(a.generationId);let s=r.generations.filter(a=>!o.has(a.generationId)).reduce((a,c)=>a+c.size,0);for(let a of i){if(s<=r.policy.budgetBytes)break;o.has(a.generationId)||(o.add(a.generationId),s-=a.size)}for(let a of o)delete n[a];return{deleteWorktrees:e,deleteGenerations:r.generations.filter(a=>o.has(a.generationId)),deleteLocks:r.locks.filter(a=>!a.live),deleteTemporaries:r.temporaries.filter(a=>!a.live),protectedGenerationIds:[...t].sort(),unreferencedSince:n}}function Qs(r,e){let t=new Set(r.filter(n=>n.managed&&(n.live||n.busy)).flatMap(n=>[n.lease.baseGenerationId,n.lease.activeGenerationId]).filter(n=>n!==void 0));for(let n of e)n.live&&t.add(n.generationId);return t}function Ti(r,e,t={}){if(!dr())return{kind:"disabled"};let n=fr(r);if(!n)return{kind:"unavailable"};let i=w(ot(),"repositories",n.repositoryId);if(!Pi(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),s=w(i,"gc-state.json"),a=ta(s);if(!t.force&&a&&o-Date.parse(a.lastSweepAt)<Js)return{kind:"throttled",sweptAt:a.lastSweepAt};let c=br(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=Zs(r,i,n.repositoryId,a?.unreferencedSince??{}),d=Xs({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??Ks,budgetBytes:t.policy?.budgetBytes??zs}}),u=0,p=0;for(let h of d.deleteWorktrees){if(!ki(h.lease))continue;let m=vr(w(h.lease.localCacheDir,"cache-lifecycle.lock"));if(m)try{if(Jt(h.lease,!0))continue;try{hi({projectRoot:h.lease.projectRoot,cacheDir:h.lease.localCacheDir,cliVersion:e})}catch{continue}if(Jt(h.lease,!0))continue;fe(h.lease.localCacheDir,{recursive:!0,force:!0}),fe(h.leasePath,{force:!0}),p+=1}finally{m.release()}}for(let h of d.deleteLocks)fe(h.path,{force:!0});for(let h of d.deleteTemporaries)fe(h.path,{recursive:!0,force:!0});for(let h of d.deleteGenerations)fe(h.path,{recursive:!0,force:!0}),u+=h.size;wr(w(i,"evidence.db"));let y={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:p,deletedGenerations:d.deleteGenerations.length,deletedBytes:u,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:y.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:y};return pt(s,f,{spacing:2,trailingNewline:!0}),y}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function Zs(r,e,t,n){let i=new Set(hr(r).map(l=>me(l.path))),o=[];for(let l of zt(w(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=w(e,"worktrees",l),u=ea(d);if(!u)continue;let p=me(u.projectRoot);o.push({leasePath:d,lease:u,managed:u.repositoryId===t&&ki(u),live:i.has(p)||Pi(p),busy:Jt(u)})}let s=[];for(let l of zt(w(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let u=w(e,"locks",l),p=Xt(u),y=p!==void 0&&A(p),f=d[1];s.push({generationId:f,path:u,live:y})}let a=[],c=[];for(let l of zt(w(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let y=w(e,"generations",l),f=Number(d[1]);try{c.push({path:y,size:wi(y),live:Number.isSafeInteger(f)&&A(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let u=w(e,"generations",l),p;try{p=Qe(u)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||a.push({generationId:l,path:u,size:wi(u),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:a,locks:s,temporaries:c}}function ki(r){if(r.ownershipChecksum!==Hr(r)||st(r.localCacheDir)!==st(lr(r.projectRoot)))return!1;let e=me(ot()),t=me(w(e,"projects")),n=me(r.localCacheDir);if(!n.startsWith(`${t}${Ci}`))return!1;try{let i=Qe(e),o=Qe(t),s=Qe(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!s.isDirectory()||s.isSymbolicLink())return!1;let a=Ri(t);return Ri(n).startsWith(`${a}${Ci}`)}catch{return!1}}function Jt(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=Xt(w(r.localCacheDir,n));if(i!==void 0&&A(i))return!0}let t=Xt(X(r.localCacheDir).lockPath);return t!==void 0&&A(t)}function ea(r){try{let e=JSON.parse(D(r,"worktree cache lease"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function Xt(r){try{let e=JSON.parse(D(r,"watch lock record"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function ta(r){try{let e=JSON.parse(D(r,"repository cache GC state"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function zt(r){try{return Mi(r)}catch{return[]}}function wi(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of Mi(n,{withFileTypes:!0})){let o=w(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Ys(o).size)}}return e}var Ze=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(e,t={}){this.root=e,this.now=t.now??Date.now,this.randomId=t.randomId,this.retryDelayMs=Math.max(1,Math.floor(t.retryDelayMs??1e3)),this.currentStatus=Gt(e)}initializeAfterOwnershipAcquired(){let e=ri(this.root),t=ni(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:e,prunedHistory:t}}observeLegacyRequest(e,t){Zn(this.root,t??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${e}`,now:()=>new Date(e)}),this.refreshStatus()}poll(e,t){if(this.active||e.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let n=ei(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),n.requests.length===0)return!1;this.active=n;try{return t(ra(n)),!0}catch(i){throw ze(this.root,n),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),i}}completeActive(){return this.active?(ti(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(ze(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=Gt(this.root)}};function ra(r){if(r.requests.length===1)return r.requests[0].detail;let t=[...new Set(r.requests.map(n=>n.detail))].slice(0,3).join("; ");return`${r.requests.length} coalesced refresh requests${t?`: ${t}`:""}`.slice(0,2048)}var oa=1e3,sa=250,aa=6e4,ca=10,la=50;function da(r){return r>0?ca:la}function ua(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function pa(r,e,t={}){let n=mi(r,e),i=n.projectRoot,o=Z(i);o.watch={...o.watch,...t};let s=Oe(o);if(!s.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let a=K(i,o),c=X(a.cacheDir),l=F(P.pid),d=Si(c.lockPath,i,{readProcessIdentity:b=>b===P.pid?l:F(b)});if(!d.acquired)return;let u=new Ze(c.refreshRequestsPath,{retryDelayMs:Math.max(1e3,s.cooldownMs)});u.initializeAfterOwnershipAcquired();let p=Date.now(),y=T(),f=p,h=y,m={state:"idle"},g,R,M,k=Te(a.dbPath),O=!1,j=!1,N=0,I=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY,Qt=Number.NEGATIVE_INFINITY,Zt=Number.NEGATIVE_INFINITY,he,ge,ye=ln(a.cacheDir),Se=zr(a.cacheDir);Wt(ye),qt(Se);let et=new He({openDb:()=>mn(i)}),tt=new Ve({projectRoot:i,currentGeneration:()=>Xr(a.dbPath)}),L=(b=!1)=>{if(!j)return;let xe=Date.now(),se=T();!b&&se-I<oa||(I=se,gi(c.statePath,{version:1,protocolVersion:It,pid:P.pid,...l?{processIdentity:l}:{},projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(p).toISOString(),heartbeatAt:new Date(xe).toISOString(),lastActivityAt:new Date(f).toISOString(),...s.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(f+s.idleTimeoutMs).toISOString()},watcher:m,...m.state==="idle"&&g?{indexGeneration:g}:{},...R?{lastRefresh:R}:{},...M?{lastError:M}:{},reindexActivity:k,refreshRequests:u.status(),typescriptSemantic:{...et.status(Vn(ye)),...he===void 0?{}:{busyUntil:new Date(he).toISOString()}},typescriptIndex:{...tt.status(zn(Se)),...ge===void 0?{}:{busyUntil:new Date(ge).toISOString()}}}))},Y=()=>{f=Date.now(),h=T()},be=new We({projectRoot:i,config:{...o,watch:s},languages:o.languages,onStatus(b){m=b,b.state!=="idle"&&(g=void 0),b.state!=="idle"&&Y(),L(!0)},onReindexComplete(){Y();let b=Rt(i,o,a);return R=b.lastRefresh,g=b.state==="fresh"?Ct(a.dbPath)??void 0:void 0,k=Te(a.dbPath),u.completeActive(),M=void 0,L(!0),b.state==="fresh"},onReindexError(){u.failActive()},onRefreshSuppressed(b){Br(a.dbPath,b),k=Te(a.dbPath)},onError(b){Y(),g=void 0,M={at:new Date().toISOString(),message:b.message},L(!0)}}),ve=()=>{O=!0};P.once("SIGINT",ve),P.once("SIGTERM",ve);let rt=!1,nt,oe;try{be.start();let b=Rt(i,o,a);R=b.lastRefresh,g=b.state==="fresh"?Ct(a.dbPath)??void 0:void 0;let xe=ua(b.state);for(xe&&be.requestRefresh(xe,{immediate:!0}),Y(),j=!0,L(!0);!O;){let se=Kn(Se,tt,{beforeRequest(E){ge=E+5e3,L(!0)},afterRequest(){ge=void 0,L(!0)}}),er=Hn(ye,et,{beforeRequest(E){he=E+5e3,L(!0)},afterRequest(){he=void 0,L(!0)}}),q=T();if(q-Zt>=aa&&(Zt=q,xt(Se),xt(ye)),q-Qt>=6e4&&(Qt=q,Ti(i,e)),q-C>=sa){C=q;let E=yi(c.activityPath);E&&E.atMs>f&&(f=E.atMs,h=q),E?.refreshRequestedAtMs!==void 0&&E.refreshRequestedAtMs>N&&(N=E.refreshRequestedAtMs,u.observeLegacyRequest(E.refreshRequestedAtMs,E.refreshDetail??"stale index observed by a legacy command")),u.poll(m,Di=>{Y(),be.requestRefresh({kind:"watch-demand",detail:Di},{immediate:!0})})}if((er>0||se>0)&&(Y(),L(!0)),L(),Ii({watcher:m,lastActivityAtMs:h,nowMs:T(),idleTimeoutMs:s.idleTimeoutMs}))break;await fa(da(er+se))}}catch(b){rt=!0,nt=b}finally{P.off("SIGINT",ve),P.off("SIGTERM",ve),et.closeTypeScriptService(),tt.close();let b=await be.stop();b.state==="stopped"?(Ei(c.statePath,{force:!0}),Ei(c.activityPath,{force:!0}),d.release()):(M={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${b.reasons.join("; ")}`},L(!0),oe=new Error(M.message))}if(rt&&oe)throw new AggregateError([nt,oe],"Watch service execution and shutdown both failed.");if(rt)throw nt;if(oe)throw oe}function fa(r){return new Promise(e=>setTimeout(e,r))}var ma=P.argv[1]?ia(na(P.argv[1])).href:null;if(ma===import.meta.url){let r=P.argv[2],e=P.argv[3],t=ha(P.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),P.exitCode=1;else try{await pa(r,e,t)}catch(n){console.error(`watch-service: ${tn(n instanceof Error?n.message:String(n))}`),P.exitCode=1}}function ha(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{pa as runWatchServiceServer,ua as startupRefreshTrigger,da as watchServiceLoopDelayMs};
43
43
  //# sourceMappingURL=watch-server.js.map
@@ -27,7 +27,10 @@ For analyzer implementation work, follow [Regex Policy](REGEX_POLICY.md): regex
27
27
  explicit `watch.enabled: false` is preserved. Use `scip-query setup --guided`
28
28
  for a recommended automatic-indexing choice, or
29
29
  `scip-query setup --no-hooks --json` when the repo should not write Codex or
30
- Claude Code lifecycle hooks.
30
+ Claude Code lifecycle hooks. Non-interactive setup and ordinary reindex
31
+ diagnose missing global tools without installing them. Pass
32
+ `--install-missing` only after reviewing the pinned package identities and
33
+ granting that user-environment change for the current operation.
31
34
 
32
35
  Setup reports three change scopes. Repository records are shared project
33
36
  facts and history that must survive clones, so commit `.scipquery.json`,
@@ -37,7 +40,9 @@ For analyzer implementation work, follow [Regex Policy](REGEX_POLICY.md): regex
37
40
  not commit `.codex/hooks.json` or `.claude/settings.local.json`; setup keeps
38
41
  them out of Git through `.git/info/exclude`. User-environment changes install
39
42
  skills or indexers for the current machine. Use `setup --guided` to answer
40
- each repository, checkout, or user-scope question separately.
43
+ each repository, checkout, or user-scope question separately; use
44
+ `setup --install-missing` for an explicit non-interactive installation
45
+ grant.
41
46
 
42
47
  2. **Resolve blockers**
43
48
 
@@ -54,7 +59,7 @@ For analyzer implementation work, follow [Regex Policy](REGEX_POLICY.md): regex
54
59
  scip-query health --json
55
60
  scip-query diff-gate --json
56
61
  ```
57
- Before cleanup, tell the user the health score, confirmed items, unavailable checks, and recommended first cleanup batch. Use `scip-cleanup-audit` for confirmation and `scip-cleanup-improve` when the user wants autonomous score improvement.
62
+ Before cleanup, tell the user the health score, confirmed items, unavailable checks, and recommended first cleanup batch. Use `scip-audit` for confirmation and `scip-improve` when the user wants autonomous score improvement.
58
63
 
59
64
  ### What you should know after this workflow
60
65
 
@@ -459,7 +464,18 @@ Numeric thresholds below are recommended starting points for review sessions; co
459
464
 
460
465
  ## Tips for AI Agents
461
466
 
462
- - **Check freshness before analysis**: run `scip-query status --capabilities`; if freshness is `stale`, `missing`, or `unknown`, run `scip-query reindex`.
467
+ - **Check freshness once before the first graph claim in a work session**:
468
+ run `scip-query status --capabilities`, then reuse that generation until
469
+ source changes. After edits, let an active watcher or pending hook refresh
470
+ finish. Run `scip-query reindex` only when freshness is `stale`, `missing`,
471
+ or `unknown` and no responsible watcher is available.
472
+ - **Retrieve complete output**: an incomplete page is not evidence. Before
473
+ making a conclusion, changing to another evidence command, or reporting
474
+ completion, run every emitted `Continue exactly:` command unchanged until
475
+ `complete: true`. Never pipe scip-query through `head`, `tail`, or a
476
+ line-range `sed`. The universal `--output-cursor` pages the
477
+ rendered output; a result cursor such as `refs --cursor` advances logical
478
+ query coverage and is a separate obligation.
463
479
  - **Use `--json` on `health`** for programmatic consumption — parse the JSON to make decisions
464
480
  - **Run `change-surface` before every file modification** — it takes <1 second and prevents surprises
465
481
  - **Run `diff-impact --json` before committing** — catches unexpected blast radius across downstream consumers