scip-query 0.19.8 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (366) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +158 -48
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/chunk-26QA6FAI.js +8 -0
  5. package/dist/{chunk-KJ2IIBZN.js → chunk-2HPVVXM5.js} +2 -2
  6. package/dist/chunk-2KAZEZ6M.js +2 -0
  7. package/dist/chunk-32LVLCLN.js +40 -0
  8. package/dist/{chunk-24GTWJ3N.js → chunk-3CLX5EOX.js} +2 -2
  9. package/dist/{chunk-QGGLL3UH.js → chunk-3G66UZBH.js} +2 -2
  10. package/dist/{chunk-AA4UWRNL.js → chunk-3ORVDL3H.js} +2 -2
  11. package/dist/chunk-4MAK2HOY.js +6 -0
  12. package/dist/{chunk-QIQ63BHW.js → chunk-4TURLRL5.js} +2 -2
  13. package/dist/chunk-4UQVNCQE.js +2 -0
  14. package/dist/chunk-55Q3WLZX.js +2 -0
  15. package/dist/{chunk-CTF2GDEX.js → chunk-5E4WNAVD.js} +2 -2
  16. package/dist/{chunk-ZCEJ63SP.js → chunk-5I5G2QOX.js} +2 -2
  17. package/dist/chunk-6LDJQXAH.js +2 -0
  18. package/dist/{chunk-3EDFLQ6A.js → chunk-6O5TICIZ.js} +2 -2
  19. package/dist/{chunk-ACAM6O5R.js → chunk-6SHPK5ZE.js} +2 -2
  20. package/dist/chunk-7BAVHKMJ.js +49 -0
  21. package/dist/chunk-7O5IKBTZ.js +16 -0
  22. package/dist/{chunk-WJL2L6MV.js → chunk-7PIO7NKH.js} +2 -2
  23. package/dist/chunk-7S5E7KWT.js +2 -0
  24. package/dist/{chunk-YLFORA5G.js → chunk-7SQQWSY3.js} +2 -2
  25. package/dist/chunk-7WPLAODU.js +5 -0
  26. package/dist/chunk-A73XVBCR.js +20 -0
  27. package/dist/chunk-AFHORGLH.js +42 -0
  28. package/dist/chunk-AIE7TFJW.js +9 -0
  29. package/dist/{chunk-TWMJ3Y3G.js → chunk-AZJQQKDD.js} +2 -2
  30. package/dist/{chunk-BDOIKGDI.js → chunk-B2PX5I6M.js} +2 -2
  31. package/dist/{chunk-DQBCO2UY.js → chunk-B7PBSLZN.js} +2 -2
  32. package/dist/chunk-BBW6JFHN.js +2 -0
  33. package/dist/{chunk-YTVWB7YJ.js → chunk-BDCC2NPY.js} +2 -2
  34. package/dist/{chunk-O23I56NA.js → chunk-BNXCIFVY.js} +2 -2
  35. package/dist/{chunk-MLFZP76A.js → chunk-BPAPWKP6.js} +2 -2
  36. package/dist/chunk-BS2NMXQZ.js +4 -0
  37. package/dist/chunk-C3KV2II6.js +2 -0
  38. package/dist/chunk-C43RDDP4.js +20 -0
  39. package/dist/{chunk-K2WO7XY7.js → chunk-CJST5ETY.js} +2 -2
  40. package/dist/chunk-DAFAHMNB.js +42 -0
  41. package/dist/{chunk-KKME5ZAI.js → chunk-DQGFVPUV.js} +2 -2
  42. package/dist/chunk-DQLPXMH6.js +8 -0
  43. package/dist/chunk-EKZTZXHZ.js +117 -0
  44. package/dist/{chunk-FJ5UDTQF.js → chunk-EN3O7VJA.js} +2 -2
  45. package/dist/{chunk-HZYDQPNY.js → chunk-EW2NTSFA.js} +2 -2
  46. package/dist/chunk-F3Z4OUDS.js +8 -0
  47. package/dist/chunk-FJH2NW7J.js +66 -0
  48. package/dist/{chunk-MSBDMFER.js → chunk-FKSELJQF.js} +2 -2
  49. package/dist/chunk-FTFP6O3L.js +11 -0
  50. package/dist/chunk-FYLK2DEJ.js +2 -0
  51. package/dist/{chunk-WUW7YUAH.js → chunk-GH74ASD6.js} +2 -2
  52. package/dist/{chunk-464PLI5O.js → chunk-GMXWZP2B.js} +2 -2
  53. package/dist/chunk-GOUBFH5O.js +3 -0
  54. package/dist/{chunk-FIJCV235.js → chunk-HLF2TX6R.js} +2 -2
  55. package/dist/{chunk-WWKWUPSU.js → chunk-HX4GQPZP.js} +2 -2
  56. package/dist/chunk-HX7M4BDI.js +30 -0
  57. package/dist/chunk-HZ72SESS.js +128 -0
  58. package/dist/{chunk-SERUIGV5.js → chunk-IB2N4FIY.js} +2 -2
  59. package/dist/chunk-ILMHV3KM.js +2 -0
  60. package/dist/chunk-IZYYAFN5.js +2 -0
  61. package/dist/{chunk-GNC4JVAN.js → chunk-JAYYFEQY.js} +2 -2
  62. package/dist/{chunk-QJIVBYEK.js → chunk-JDOEX4E6.js} +2 -2
  63. package/dist/chunk-JFGGXWQF.js +947 -0
  64. package/dist/chunk-JN4NMBEX.js +8 -0
  65. package/dist/{chunk-6M7RONVB.js → chunk-JVYA47YU.js} +2 -2
  66. package/dist/{chunk-7KYNAMMH.js → chunk-JW56N3KI.js} +2 -2
  67. package/dist/{chunk-OUBAF226.js → chunk-JZ2OXNWB.js} +2 -2
  68. package/dist/chunk-KMKTIO2G.js +8 -0
  69. package/dist/chunk-L5GJNV2T.js +8 -0
  70. package/dist/{chunk-MNSTUIDD.js → chunk-L7AW2QB5.js} +2 -2
  71. package/dist/chunk-L7JDSCDF.js +4 -0
  72. package/dist/chunk-LU47HG23.js +14 -0
  73. package/dist/chunk-LVY7NPF7.js +2 -0
  74. package/dist/chunk-LY4WC4AD.js +74 -0
  75. package/dist/{chunk-7FT5Y65S.js → chunk-MKCDWWGV.js} +2 -2
  76. package/dist/chunk-MNE7YG56.js +2 -0
  77. package/dist/{chunk-7QHY3H7P.js → chunk-MRXBEXSY.js} +2 -2
  78. package/dist/chunk-MV7OWDUX.js +2 -0
  79. package/dist/{chunk-ZJ5CBXK3.js → chunk-N5W4YZMK.js} +2 -2
  80. package/dist/chunk-NGEXCJJW.js +11 -0
  81. package/dist/{chunk-7SWJEWJF.js → chunk-NIW6JDC5.js} +2 -2
  82. package/dist/{chunk-O3O4XXO6.js → chunk-O64IZ6UX.js} +2 -2
  83. package/dist/{chunk-3ZSJ3PWF.js → chunk-PBUQFCNB.js} +2 -2
  84. package/dist/{chunk-7RAG65VK.js → chunk-POAVPHH7.js} +2 -2
  85. package/dist/{chunk-A3QXWFBK.js → chunk-PQCI4SQX.js} +2 -2
  86. package/dist/{chunk-4BV4QAZJ.js → chunk-PXY7F6Y4.js} +2 -2
  87. package/dist/chunk-RDO52JGY.js +2 -0
  88. package/dist/chunk-RJT3TUUZ.js +2 -0
  89. package/dist/{chunk-S4S2WOIX.js → chunk-RUJURYSV.js} +2 -2
  90. package/dist/{chunk-JAY7YWS3.js → chunk-RVLDN63O.js} +2 -2
  91. package/dist/chunk-RXOXSKY3.js +2 -0
  92. package/dist/chunk-S7OYBOCK.js +2 -0
  93. package/dist/chunk-SMNXQT5Z.js +3 -0
  94. package/dist/{chunk-NE3TZUCI.js → chunk-SRAFT254.js} +2 -2
  95. package/dist/{chunk-ELLMY7XJ.js → chunk-SXP2MBJH.js} +2 -2
  96. package/dist/chunk-T7YQSHPQ.js +3 -0
  97. package/dist/{chunk-WY45BHKQ.js → chunk-TFRAYKN6.js} +2 -2
  98. package/dist/{chunk-2SNGN6U4.js → chunk-UJCOIXDY.js} +2 -2
  99. package/dist/{chunk-MZZBAITE.js → chunk-UJPRPGCO.js} +2 -2
  100. package/dist/chunk-W4ETQAXM.js +2 -0
  101. package/dist/chunk-WCCFZ7V7.js +113 -0
  102. package/dist/chunk-WUPW3UN3.js +3 -0
  103. package/dist/{chunk-7LSVMFX7.js → chunk-WXZLAAWK.js} +2 -2
  104. package/dist/{chunk-5ML2BNRH.js → chunk-X54AGLVX.js} +2 -2
  105. package/dist/chunk-XKWKXZKW.js +20 -0
  106. package/dist/{chunk-5YLUDDAF.js → chunk-XSRF6Q77.js} +2 -2
  107. package/dist/chunk-Y2MVPNKY.js +5 -0
  108. package/dist/{chunk-JHF3E4YM.js → chunk-YKUU5AIC.js} +2 -2
  109. package/dist/{chunk-E3HYEQO7.js → chunk-YLCJLTPL.js} +2 -2
  110. package/dist/{chunk-7VCOXZH3.js → chunk-YTQVETEO.js} +2 -2
  111. package/dist/chunk-Z4N3MZYA.js +38 -0
  112. package/dist/chunk-ZHXX42OH.js +18 -0
  113. package/dist/chunk-ZJOOT3BG.js +2 -0
  114. package/dist/{chunk-P3UO3EH3.js → chunk-ZK26BAQL.js} +2 -2
  115. package/dist/{chunk-33KUO7CG.js → chunk-ZTETIQ35.js} +2 -2
  116. package/dist/cli.js +3 -8
  117. package/dist/command-descriptors-DSS46KXI.js +642 -0
  118. package/dist/{config-types-B6MEoRNy.d.ts → config-types-jVM3D7MA.d.ts} +68 -2
  119. package/dist/{db-DYLKr9Wn.d.ts → db-B5PM5yNk.d.ts} +20 -2
  120. package/dist/{diff-gate-types-C9BoYwYD.d.ts → diff-gate-types-B0QYpDv1.d.ts} +2 -1
  121. package/dist/direct-navigation-6YHV6IB5.js +3 -0
  122. package/dist/{health-DgxIDXJC.d.ts → health-Do5TKSJI.d.ts} +1 -1
  123. package/dist/index.d.ts +3 -3
  124. package/dist/index.js +1 -1
  125. package/dist/postinstall.js +1 -1
  126. package/dist/queries/affected.d.ts +2 -2
  127. package/dist/queries/affected.js +1 -1
  128. package/dist/queries/architecture.d.ts +2 -2
  129. package/dist/queries/architecture.js +1 -1
  130. package/dist/queries/bottlenecks.d.ts +2 -2
  131. package/dist/queries/bottlenecks.js +1 -1
  132. package/dist/queries/by-kind.d.ts +2 -2
  133. package/dist/queries/by-kind.js +1 -1
  134. package/dist/queries/call-graph.d.ts +2 -2
  135. package/dist/queries/call-graph.js +1 -1
  136. package/dist/queries/change-surface.d.ts +22 -3
  137. package/dist/queries/change-surface.js +1 -1
  138. package/dist/queries/cleanup-plan.d.ts +2 -2
  139. package/dist/queries/cleanup-plan.js +1 -1
  140. package/dist/queries/co-change.d.ts +2 -2
  141. package/dist/queries/co-change.js +1 -1
  142. package/dist/queries/code.d.ts +2 -2
  143. package/dist/queries/code.js +1 -1
  144. package/dist/queries/complexity-hotspots.d.ts +3 -3
  145. package/dist/queries/complexity-hotspots.js +1 -1
  146. package/dist/queries/complexity.d.ts +3 -3
  147. package/dist/queries/complexity.js +1 -1
  148. package/dist/queries/convergence.d.ts +2 -2
  149. package/dist/queries/convergence.js +1 -1
  150. package/dist/queries/coupling.d.ts +2 -2
  151. package/dist/queries/coupling.js +1 -1
  152. package/dist/queries/cycles.d.ts +2 -2
  153. package/dist/queries/cycles.js +1 -1
  154. package/dist/queries/dataflow.d.ts +2 -2
  155. package/dist/queries/dataflow.js +1 -1
  156. package/dist/queries/dead.d.ts +2 -2
  157. package/dist/queries/dead.js +1 -1
  158. package/dist/queries/decorative-checkers.d.ts +2 -2
  159. package/dist/queries/decorative-checkers.js +1 -1
  160. package/dist/queries/deep-chains.d.ts +2 -2
  161. package/dist/queries/deep-chains.js +1 -1
  162. package/dist/queries/deps.d.ts +2 -2
  163. package/dist/queries/deps.js +1 -1
  164. package/dist/queries/diff-gate.d.ts +40 -7
  165. package/dist/queries/diff-gate.js +1 -1
  166. package/dist/queries/diff-impact.d.ts +84 -6
  167. package/dist/queries/diff-impact.js +1 -1
  168. package/dist/queries/doc-drift.d.ts +3 -3
  169. package/dist/queries/doc-drift.js +1 -1
  170. package/dist/queries/drift.d.ts +2 -2
  171. package/dist/queries/drift.js +1 -1
  172. package/dist/queries/duplicate-bodies.d.ts +3 -3
  173. package/dist/queries/duplicate-bodies.js +1 -1
  174. package/dist/queries/extract-candidates.d.ts +2 -2
  175. package/dist/queries/extract-candidates.js +1 -1
  176. package/dist/queries/fan.d.ts +2 -2
  177. package/dist/queries/fan.js +1 -1
  178. package/dist/queries/files.d.ts +12 -3
  179. package/dist/queries/files.js +1 -1
  180. package/dist/queries/health.d.ts +3 -3
  181. package/dist/queries/health.js +1 -1
  182. package/dist/queries/hierarchy.d.ts +2 -2
  183. package/dist/queries/hierarchy.js +1 -1
  184. package/dist/queries/hotspots.d.ts +2 -2
  185. package/dist/queries/hotspots.js +1 -1
  186. package/dist/queries/imports.d.ts +2 -2
  187. package/dist/queries/imports.js +1 -1
  188. package/dist/queries/incomplete-migration.d.ts +8 -6
  189. package/dist/queries/incomplete-migration.js +1 -1
  190. package/dist/queries/index.d.ts +141 -10
  191. package/dist/queries/index.js +1 -1
  192. package/dist/queries/isolated.d.ts +2 -2
  193. package/dist/queries/isolated.js +1 -1
  194. package/dist/queries/locality-candidates.d.ts +2 -2
  195. package/dist/queries/locality-candidates.js +1 -1
  196. package/dist/queries/members.d.ts +2 -2
  197. package/dist/queries/members.js +1 -1
  198. package/dist/queries/methods.d.ts +34 -3
  199. package/dist/queries/methods.js +1 -1
  200. package/dist/queries/not-implemented.d.ts +2 -2
  201. package/dist/queries/not-implemented.js +1 -1
  202. package/dist/queries/outline.d.ts +2 -2
  203. package/dist/queries/outline.js +1 -1
  204. package/dist/queries/passthrough-candidates.d.ts +3 -3
  205. package/dist/queries/passthrough-candidates.js +1 -1
  206. package/dist/queries/plan-context.d.ts +3 -3
  207. package/dist/queries/plan-context.js +1 -1
  208. package/dist/queries/react-component-duplicates.d.ts +2 -2
  209. package/dist/queries/react-component-duplicates.js +1 -1
  210. package/dist/queries/react-hook-candidates.d.ts +2 -2
  211. package/dist/queries/react-hook-candidates.js +1 -1
  212. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  213. package/dist/queries/react-large-component-pressure.js +1 -1
  214. package/dist/queries/recent-duplicates.d.ts +2 -2
  215. package/dist/queries/recent-duplicates.js +1 -1
  216. package/dist/queries/redundant-reexports.d.ts +2 -2
  217. package/dist/queries/redundant-reexports.js +1 -1
  218. package/dist/queries/refs.d.ts +2 -2
  219. package/dist/queries/refs.js +1 -1
  220. package/dist/queries/self-audit.d.ts +2 -2
  221. package/dist/queries/self-audit.js +1 -1
  222. package/dist/queries/similar-chains.d.ts +2 -2
  223. package/dist/queries/similar-chains.js +1 -1
  224. package/dist/queries/similar-files.d.ts +2 -2
  225. package/dist/queries/similar-files.js +1 -1
  226. package/dist/queries/similar-signatures.d.ts +2 -2
  227. package/dist/queries/similar-signatures.js +1 -1
  228. package/dist/queries/similar.d.ts +2 -2
  229. package/dist/queries/similar.js +1 -1
  230. package/dist/queries/slice.d.ts +2 -2
  231. package/dist/queries/slice.js +1 -1
  232. package/dist/queries/stale-abstractions.d.ts +2 -2
  233. package/dist/queries/stale-abstractions.js +1 -1
  234. package/dist/queries/stats.d.ts +2 -2
  235. package/dist/queries/surface.d.ts +2 -2
  236. package/dist/queries/surface.js +1 -1
  237. package/dist/queries/symbols.d.ts +2 -2
  238. package/dist/queries/symbols.js +1 -1
  239. package/dist/queries/system.d.ts +2 -2
  240. package/dist/queries/system.js +1 -1
  241. package/dist/queries/test-quality.d.ts +2 -2
  242. package/dist/queries/test-quality.js +1 -1
  243. package/dist/queries/trace.d.ts +2 -2
  244. package/dist/queries/trace.js +1 -1
  245. package/dist/queries/twin-ab.d.ts +14 -3
  246. package/dist/queries/twin-ab.js +1 -1
  247. package/dist/queries/twin-drift.d.ts +2 -2
  248. package/dist/queries/twin-drift.js +1 -1
  249. package/dist/queries/unused-imports.d.ts +2 -2
  250. package/dist/queries/unused-imports.js +1 -1
  251. package/dist/queries/unused-params.d.ts +2 -2
  252. package/dist/queries/unused-params.js +1 -1
  253. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  254. package/dist/queries/vue-component-duplicates.js +1 -1
  255. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  256. package/dist/queries/vue-composable-candidates.js +1 -1
  257. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  258. package/dist/queries/vue-large-view-pressure.js +1 -1
  259. package/dist/queries/wrapper-candidates.d.ts +2 -2
  260. package/dist/queries/wrapper-candidates.js +1 -1
  261. package/dist/reindex-worker.js +21 -21
  262. package/dist/reindex.d.ts +3 -3
  263. package/dist/reindex.js +33 -33
  264. package/dist/runtime.d.ts +5 -3
  265. package/dist/runtime.js +3 -3
  266. package/dist/rust-semantic-session-server.js +1 -1
  267. package/dist/rust-semantic-session-worker.js +1 -1
  268. package/dist/rust-semantic-worker.js +1 -1
  269. package/dist/{scip-cli-Cc6c00-a.d.ts → scip-cli-BnEwZRLJ.d.ts} +1 -1
  270. package/dist/{symbol-types-BgWU6lhL.d.ts → symbol-types-BIQwfoAx.d.ts} +7 -1
  271. package/dist/typescript-mailbox-worker.js +2 -0
  272. package/dist/watch-server.js +2 -42
  273. package/docs/AGENT_GUIDE.md +13 -6
  274. package/docs/CLI_JSON_OUTPUT.md +110 -22
  275. package/docs/COMMAND_REFERENCE.md +88 -88
  276. package/docs/COMMITTED_RECORD_COMPATIBILITY.md +55 -18
  277. package/docs/DURABILITY.md +88 -38
  278. package/docs/INDEX_GENERATIONS.md +65 -19
  279. package/docs/MAILBOX_LIFECYCLE.md +28 -1
  280. package/docs/REINDEX_METADATA_COMPATIBILITY.md +18 -8
  281. package/docs/SECURITY_MODEL.md +31 -14
  282. package/docs/TELEMETRY_RETENTION.md +11 -4
  283. package/docs/WATCH_REFRESH_REQUESTS.md +34 -21
  284. package/docs/WINDOWS_SIDECAR_RELEASE.md +9 -4
  285. package/docs/analyzer-inventory.md +31 -22
  286. package/docs/analyzer-validation-ledger.md +8 -0
  287. package/docs/schemas/outcome-event-record.schema.json +57 -1
  288. package/docs/schemas/project-config.schema.json +82 -1
  289. package/docs/schemas/suppression-record.schema.json +84 -3
  290. package/package.json +5 -5
  291. package/skills/_shared/SKILL.md +2 -2
  292. package/skills/_shared/references/agent-contract-catalog.md +1 -1
  293. package/skills/_shared/references/detector-precision-and-diffgate.md +1 -1
  294. package/skills/scip-audit/SKILL.md +6 -6
  295. package/skills/scip-audit/references/claims.md +1 -1
  296. package/skills/scip-audit/references/cleanup.md +19 -20
  297. package/skills/scip-audit/references/directory.md +4 -4
  298. package/skills/scip-audit/references/frontend.md +10 -10
  299. package/skills/scip-audit/references/twin-drift.md +2 -2
  300. package/skills/scip-diagnose/references/debug.md +8 -8
  301. package/skills/scip-diagnose/references/root-cause.md +3 -3
  302. package/skills/scip-diagnose/references/triage.md +10 -10
  303. package/skills/scip-explore/SKILL.md +3 -3
  304. package/skills/scip-improve/SKILL.md +10 -10
  305. package/skills/scip-improve/references/cleanup-batches.md +3 -3
  306. package/skills/scip-improve/references/directory-moves.md +3 -3
  307. package/skills/scip-improve/references/doc-reconcile.md +1 -1
  308. package/skills/scip-improve/references/frontend-extraction.md +2 -2
  309. package/skills/scip-improve/references/twin-drift.md +3 -3
  310. package/skills/scip-plan/SKILL.md +2 -2
  311. package/skills/scip-plan/references/api-impact.md +5 -5
  312. package/skills/scip-plan/references/conductor.md +2 -2
  313. package/skills/scip-plan/references/hyper-optimization.md +1 -1
  314. package/skills/scip-query/SKILL.md +15 -5
  315. package/skills/scip-setup/references/bootstrap-workflow.md +7 -8
  316. package/skills/scip-setup/references/language-verification.md +2 -2
  317. package/skills/scip-setup/references/per-repo-triage.md +1 -1
  318. package/skills/scip-verify/SKILL.md +10 -10
  319. package/skills/scip-verify/references/calibrate-detectors.md +7 -7
  320. package/dist/chunk-2465DLHK.js +0 -3
  321. package/dist/chunk-2U3OLUNJ.js +0 -61
  322. package/dist/chunk-33XTHFKR.js +0 -2
  323. package/dist/chunk-43KC6EQZ.js +0 -2
  324. package/dist/chunk-47BU5Z4T.js +0 -8
  325. package/dist/chunk-4YTUWQ6M.js +0 -18
  326. package/dist/chunk-64MNV6AB.js +0 -8
  327. package/dist/chunk-67QRR5YC.js +0 -6
  328. package/dist/chunk-6GXYN7YA.js +0 -40
  329. package/dist/chunk-A2TNXAXO.js +0 -8
  330. package/dist/chunk-APMMR5Y2.js +0 -2
  331. package/dist/chunk-AZFUMCQB.js +0 -2
  332. package/dist/chunk-BNXICU42.js +0 -33
  333. package/dist/chunk-C5Q44Q5D.js +0 -3
  334. package/dist/chunk-DQGSM7RZ.js +0 -20
  335. package/dist/chunk-E2LAW7SL.js +0 -30
  336. package/dist/chunk-E4NFOAD4.js +0 -6
  337. package/dist/chunk-E5HNT4X2.js +0 -3
  338. package/dist/chunk-FD3HFKXR.js +0 -5
  339. package/dist/chunk-GHKEJTCE.js +0 -35
  340. package/dist/chunk-GLZTVKAB.js +0 -16
  341. package/dist/chunk-HIB452NU.js +0 -949
  342. package/dist/chunk-IF6FP6B2.js +0 -66
  343. package/dist/chunk-JORHF5AL.js +0 -108
  344. package/dist/chunk-KSGTULOS.js +0 -9
  345. package/dist/chunk-KXDJAG4N.js +0 -38
  346. package/dist/chunk-L4S2A7BV.js +0 -2
  347. package/dist/chunk-LP3ARJKF.js +0 -8
  348. package/dist/chunk-LSOR3LQG.js +0 -3
  349. package/dist/chunk-NTUMF2X3.js +0 -56
  350. package/dist/chunk-QOXBSI6G.js +0 -20
  351. package/dist/chunk-QXK6UUSM.js +0 -2
  352. package/dist/chunk-RA3AYNWP.js +0 -112
  353. package/dist/chunk-RJMDJR3A.js +0 -2
  354. package/dist/chunk-RLH5VUMG.js +0 -2
  355. package/dist/chunk-SMQWE25B.js +0 -3
  356. package/dist/chunk-TAVELHYR.js +0 -2
  357. package/dist/chunk-VAXNI5NE.js +0 -146
  358. package/dist/chunk-VVY2G5ET.js +0 -2
  359. package/dist/chunk-W3DBTGL4.js +0 -11
  360. package/dist/chunk-WANA4KAQ.js +0 -5
  361. package/dist/chunk-X4FR5BZF.js +0 -9
  362. package/dist/chunk-X6RKPDY7.js +0 -2
  363. package/dist/chunk-YCPASUCX.js +0 -2
  364. package/dist/chunk-ZL2OGDCD.js +0 -2
  365. package/dist/command-descriptors-ZW5J4ZEM.js +0 -631
  366. package/dist/direct-navigation-42YHQPOI.js +0 -3
@@ -1,631 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a as Kl,d as zl,e as Gi,f as Sr,g as Yl,h as Xl,i as Ql,k as Zl}from"./chunk-2465DLHK.js";import{a as St,b as x,c as Ke,d as we,e as Nt,f as p,g as Fl,h as Hi,i as Nl,j as E,k as C,l as k,m as me,n as fe,o as Ie,p as bn,q as Jl}from"./chunk-67QRR5YC.js";import{$ as zs,$a as ba,$b as Oi,$c as nl,$d as Ge,$e as I,A as Bs,Aa as Lt,Ab as Ba,Ac as Lc,Ad as bt,Ae as yr,B as Jn,Ba as W,Bb as qa,Bc as Dc,Bd as Me,Be as Dl,C as K,Ca as ca,Cb as Va,Cc as Oc,Ce as Ol,D as Z,Da as Ii,Db as Wa,Dc as Mc,Dd as pl,De as Ml,Eb as Ha,Ec as Fc,Ed as ml,Fa as la,Fb as Ga,Fc as Nc,Fd as fl,Ga as da,Gb as Ua,Gc as _c,Gd as gl,Ge as be,Ha as Ai,Hb as Ja,Hc as Bc,Hd as hl,He as te,Ia as ua,Ib as Ka,Ic as qc,Id as yl,Ie as _l,J as sn,Ja as ji,Jb as za,Jc as Vc,Jd as bl,Je as Bl,K as an,Ka as Li,Kb as Ya,Kc as Wc,Kd as Sl,Ke as ql,L as cn,La as pa,Lb as fn,Lc as he,Ld as vl,Le as it,M as qs,Ma as rr,Mb as Xa,Mc as Hc,Md as xl,Me as Vl,N as pt,Nb as Qa,Nc as gn,Nd as Rl,Ne as Ee,O as Kn,Ob as Za,Oc as Gc,Od as kl,Oe as Wl,P as Vs,Pa as ma,Pb as ec,Pc as Uc,Pd as wl,Pe as Se,Q as Ve,Qa as ir,Qb as tc,Qc as Jc,Qd as dr,Qe as br,R as Ws,Ra as Di,Rb as nc,Rc as Kc,Rd as $l,Re as Hl,S as zn,Sb as rc,Sc as zc,Se as O,T as Hs,Ta as fa,Tb as ic,Tc as Yc,Td as ur,Te as z,U as Ei,Ua as mt,Ub as oc,Uc as Xc,Ud as Cl,Ue as $,V as Gs,Vb as sc,Vc as Qc,Vd as Bi,Ve as Q,W as Us,Wb as ac,Wd as Pl,We as b,X as Js,Xa as pn,Xb as cc,Xc as Zc,Xd as qi,Xe as _t,Y as Ks,Ya as ga,Yb as lc,Yc as el,Ye as T,Z as Yn,Za as ha,Zb as dc,Zc as tl,Zd as re,Ze as F,_ as ne,_a as ya,_b as uc,_c as ye,_e as Gl,a as Hn,aa as Xn,ab as mn,ac as pc,ae as Ft,af as Ul,b as Ds,ba as Ys,bb as Sa,bc as mc,be as Tl,bf as X,c as Os,ca as Xs,cb as va,cc as fc,cd as He,d as Gn,da as Qn,db as or,dc as gc,dd as rl,de as ue,e as wi,eb as xa,ec as hc,ed as ft,fa as ln,fb as Ra,fc as yc,fd as Fi,fe as Ue,g as Ms,ga as Qs,gb as ka,gc as bc,gd as Ni,ge as Vi,h as nn,ha as Zs,hb as Dt,hc as Sc,hd as il,he as El,i as Et,ia as ea,ib as wa,ic as vc,id as cr,ie as pr,j as $i,ja as We,jb as $a,jc as xc,jd as gt,je as mr,k as Fs,ka as It,kc as Rc,kd as lr,ke as Il,l as Ci,la as Zn,lb as Ca,lc as kc,le as Wi,ma as er,mb as Pa,mc as wc,md as Ot,me as fr,na as At,nb as Ta,nc as $c,nd as _i,o as Un,oa as tr,ob as Ea,oc as Cc,od as ol,oe as gr,p as de,pa as dn,pb as Ia,pc as nt,pd as ht,pe as Al,q as xe,qa as ta,qb as Aa,qc as Pc,qd as ke,qe as Je,r as Re,ra as na,rb as ja,rc as Tc,rd as Mt,re as pe,s as Pi,sa as ra,sb as La,sc as Ec,sd as Oe,se as J,t as rn,ta as ia,tb as Da,tc as Ic,td as sl,te as hr,u as Ti,ua as oa,ub as Oa,uc as Ac,ud as al,ue as L,v as on,va as nr,vc as jc,vd as cl,ve as hn,w as U,wa as sa,wb as Ma,wc as rt,wd as yt,we as yn,x as V,xa as jt,xb as Fa,xc as Mi,xd as ll,xe as Fe,y as Ns,ya as aa,yb as Na,yc as sr,yd as dl,ye as jl,z as _s,za as un,zb as _a,zc as ar,zd as ul,ze as Ll}from"./chunk-HIB452NU.js";import{fileURLToPath as Kh}from"url";import{join as zh}from"path";import{createHash as Bh,randomUUID as qh}from"crypto";import{createHash as Lh}from"crypto";import{existsSync as kr,mkdirSync as Dh,readdirSync as Oh,rmSync as rd,writeFileSync as id}from"fs";import{join as ze}from"path";var Ui="scip-query-outcome-event",vr=1;function xr(e){return JSON.stringify([e.check,e.findingId,e.event,e.commit])}function td(e,t){if(t.trim()==="")throw new Error("outcome event writer requires a non-empty tool version");return{...e,kind:Ui,schemaVersion:vr,eventIdentity:xr(e),writer:{tool:"scip-query",version:t}}}function nd(e){if(!wi(e))return{state:"malformed",error:"not an outcome event object"};let t=e,n=t.schemaVersion;if(n===void 0){if(t.kind!==void 0||t.eventIdentity!==void 0||t.writer!==void 0)return{state:"malformed",error:"outcome event envelope metadata requires schemaVersion"};let o=ed(t);return o?{state:"legacy",event:o,record:o,schemaVersion:0}:{state:"malformed",error:"invalid legacy outcome event fields"}}if(!Number.isSafeInteger(n)||n<1)return Number.isSafeInteger(n)?{state:"unsupported-older",error:`unsupported schemaVersion ${String(n)}`}:{state:"malformed",error:"schemaVersion must be a positive safe integer"};if(n!==vr)return{state:n>vr?"unsupported-future":"unsupported-older",error:`unsupported schemaVersion ${String(n)}`};if(t.kind!==Ui)return{state:"malformed",error:`kind must be ${Ui}`};let r=ed(t);if(!r)return{state:"malformed",error:"invalid current outcome event fields"};if(t.eventIdentity!==xr(r))return{state:"malformed",error:"eventIdentity does not match the outcome event"};let i=t.writer;return!wi(i)||i.tool!=="scip-query"||typeof i.version!="string"||i.version.trim()===""?{state:"malformed",error:"missing valid writer metadata"}:{state:"current",event:r,record:t,schemaVersion:vr}}var jh=["caught","resolved","suppressed","reopened"];function ed(e){if(!(typeof e.ts!="number"||!Number.isFinite(e.ts)||typeof e.check!="string"||e.check.trim()===""||typeof e.findingId!="string"||e.findingId.trim()===""||!jh.includes(e.event)||e.commit!==null&&typeof e.commit!="string"||e.comparisonBaseCommit!==void 0&&typeof e.comparisonBaseCommit!="string"||e.verifiedAgainstCommit!==void 0&&(e.event!=="resolved"||typeof e.verifiedAgainstCommit!="string")||e.symbol!==void 0&&typeof e.symbol!="string"))return{ts:e.ts,check:e.check,findingId:e.findingId,event:e.event,commit:e.commit,...typeof e.comparisonBaseCommit=="string"?{comparisonBaseCommit:e.comparisonBaseCommit}:{},...typeof e.verifiedAgainstCommit=="string"?{verifiedAgainstCommit:e.verifiedAgainstCommit}:{},...typeof e.symbol=="string"?{symbol:e.symbol}:{}}}var Sn=ze(".scipquery","events"),od=ze(".scipquery","ledger"),Ji="events.jsonl";function sd(e){return ze(e,od)}function Ki(e){return ze(sd(e),Ji)}function ad(e,t,n){let r=Ki(e),i=kr(r),o=i?cd(r):_h(),s=[...o.events,...t];if(s.length>0){let a=ze(e,Sn);Dh(a,{recursive:!0});for(let c of s)Mh(a,c,n.toolVersion)}if(i&&o.compatibility.complete)Fh(e);else if(i)return{warning:`legacy outcome ledger preserved because ${o.compatibility.omitted} of ${o.compatibility.total} non-empty record(s) are incompatible: ${o.warnings.join("; ")}`};return{}}function Mh(e,t,n){let r=`${JSON.stringify(td(t,n),null,2)}
3
- `,i=Lh("sha256").update(r).digest("hex").slice(0,16).toUpperCase(),o=ze(e,`${t.ts}-${i}.json`);try{id(o,r,{flag:"wx"})}catch(s){if(s.code!=="EEXIST")throw s;if(V(o,"outcome event record")!==r)throw new Error(`outcome event filename collision: ${o}`,{cause:s})}}function Fh(e){rd(Ki(e));let t=ze(sd(e),".gitattributes");if(!kr(t))return;let n=V(t,"outcome event attributes").split(`
4
- `).filter(r=>r.trim()!==`${Ji} merge=union`).join(`
5
- `).replace(/^\n+|\n+$/g,"");n===""?rd(t):id(t,`${n}
6
- `)}function wr(e){let t=[],n=[],r=ze(e,Sn);if(kr(r))for(let o of Oh(r).sort()){if(!o.endsWith(".json"))continue;let s=`${Sn}/${o}`,a=ld(V(ze(r,o),"outcome event record"));n.push({path:s,state:a.state,..."error"in a?{reason:a.error}:{}}),"event"in a&&t.push(a.event)}let i=Ki(e);if(kr(i)){let o=cd(i);t.push(...o.events),n.push(...o.observations)}return zi(t,n)}function cd(e){let t=[],n=[],r=`${od}/${Ji}`;for(let[i,o]of _s(e,"legacy outcome-event ledger").split(`
7
- `).entries()){if(o.trim()==="")continue;let s=ld(o);n.push({path:`${r}:${i+1}`,state:s.state,..."error"in s?{reason:s.error}:{}}),"event"in s&&t.push(s.event)}return{...zi(t,n),observations:n}}function ld(e){if(e.trim()==="")return{state:"malformed",error:"empty record"};let t;try{t=JSON.parse(e)}catch{return{state:"malformed",error:"malformed JSON"}}return nd(t)}function Nh(e){let t=new Map;for(let n of e){let r=xr(n),i=t.get(r);(!i||Rr(n)>Rr(i)||Rr(n)===Rr(i)&&n.ts<i.ts)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.ts-r.ts)}function Rr(e){return+(e.comparisonBaseCommit!==void 0)+ +(e.verifiedAgainstCommit!==void 0)*2}function zi(e,t){let n=Cc(t);return{events:Nh(e),compatibility:n,warnings:n.issues.map(r=>`${r.path}: ${r.reason} \u2014 ignored`)}}function _h(){return{...zi([],[]),observations:[]}}function ud(e,t,n={}){let r=(n.now??Date.now)(),i=n.observationId??qh(),o=Uh(t),s=Jc(e),a=e.config.projectRoot,c=n.headCommit?n.headCommit(a):mt(a)?.headCommit??null,l=n.resolveCommit?n.resolveCommit(a,t.base):Gh(a,t.base),d=Vh({previous:s,observed:o,result:t,projectRoot:a,commit:c,comparisonBaseCommit:l,runtime:n}),u=Kc(e,d.ledgerObserved,d.checksRun,r,d.retainedKeys,i),m=u.current,g=u.status==="busy"?"finding outcome ledger not updated: evidence database remained busy":u.status==="unavailable"?"finding outcome ledger not updated: evidence database unavailable":u.status==="conflict"?`finding outcome ledger not updated: observation id ${i} names different evidence`:void 0;try{let f=new Map;for(let y of t.findings)y.symbol&&f.set(y.id,y.symbol);for(let y of t.suppressed)y.finding.symbol&&f.set(y.finding.id,y.finding.symbol);for(let[y,v]of d.replaySymbols)f.set(y,v);let h=Hc(u.previous,m,f,c,r,{...l?{comparisonBaseCommit:l}:{},verifiedAgainstByFinding:d.verifiedAgainstByFinding}),S;return n.appendEvents?n.appendEvents(a,h):S=ad(a,h,{toolVersion:ye}).warning,{ledger:m,observed:o,now:r,...dd(d.warning,g,S)}}catch(f){return{ledger:m,observed:o,now:r,...dd(d.warning,g,`outcome event ledger not updated: ${f instanceof Error?f.message:String(f)}`)}}}function dd(...e){let t=e.filter(n=>!!n).join("; ");return t?{warning:t}:{}}function Vh(e){let t=[...e.observed],n=new Set(e.result.checksRun),r=new Set,i=new Map,o=new Map,s=new Set(e.observed.map(R=>he(R.check,R.findingId))),a=new Set(e.result.checksRun),c=e.result.changedFiles.length===0&&!sr(e.result)&&e.commit!==null&&e.comparisonBaseCommit!==null,l=e.previous.filter(R=>R.outcome!=="resolved"&&(a.has(R.check)||c)&&!s.has(he(R.check,R.findingId)));if(vt(`primary base=${String(e.comparisonBaseCommit)} head=${String(e.commit)} checks=${e.result.checksRun.join(",")} missing=${l.length}`),l.length===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let d;try{d=(e.runtime.readEvents??wr)(e.projectRoot)}catch(R){for(let j of l)r.add(he(j.check,j.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${R instanceof Error?R.message:String(R)}`}}if(!d.compatibility.complete){for(let R of l)r.add(he(R.check,R.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${nt("committed outcome history",d.compatibility)}`}}let u=d.events,m=new Map;for(let R of u){let j=he(R.check,R.findingId),P=m.get(j)??[];P.push(R),m.set(j,P)}let g=new Map;for(let R of l){let j=he(R.check,R.findingId),P=gn(m.get(j)??[]),G=P?.comparisonBaseCommit??P?.commit;if(vt(`candidate ${j} anchor=${String(G)} current=${String(e.comparisonBaseCommit)}`),!P?.comparisonBaseCommit&&P?.commit&&P.commit===e.commit){n.add(R.check);continue}if(!G||!e.commit||!e.comparisonBaseCommit){r.add(j);continue}if(G===e.comparisonBaseCommit){n.add(R.check);continue}let A=g.get(G)??[];A.push(R),g.set(G,A)}if(g.size===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let f=e.runtime.worktreeIsClean?.(e.projectRoot)??mt(e.projectRoot)?.clean??!1;if(vt(`replay groups=${g.size} clean=${f} callback=${!!e.runtime.replayGate}`),!f||!e.runtime.replayGate){for(let R of g.values())for(let j of R)r.add(he(j.check,j.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o}}let h=[],S=Hh(g,e.commit,e.runtime.maxReplayBases),y=new Set(S.map(([R])=>R)),v=0,w=0;for(let[R,j]of g)if(!y.has(R)){v+=1,w+=j.length;for(let P of j)r.add(he(P.check,P.findingId))}v>0&&h.push(`cross-HEAD outcome verification bounded to ${S.length} of ${g.size} historical base(s); retained ${w} finding(s) across ${v} base(s) for later verification`);for(let[R,j]of S){let P;try{let M=[...new Set(j.map(_=>_.check))].filter(_=>rt.includes(_)).sort();P=e.runtime.replayGate(R,M),vt(`replay base=${R} checks=${P.checksRun.join(",")} findings=${P.findings.length} suppressed=${P.suppressed.length}`)}catch(M){for(let _ of j)r.add(he(_.check,_.findingId));h.push(`cross-HEAD outcome verification deferred for ${R.slice(0,12)}: ${M instanceof Error?M.message:String(M)}`);continue}let G=new Set(P.checksRun),A=Jh(P);for(let M of j){let _=he(M.check,M.findingId);if(!G.has(M.check)){r.add(_);continue}n.add(M.check);let N=A.find(ut=>ut.key===_);if(N){vt(`replay retained exact ${_}`),t.push(N.observed),N.symbol&&o.set(N.observed.findingId,N.symbol);continue}let H=gn(m.get(_)??[]),Pe=H?.symbol?A.find(ut=>ut.check===M.check&&ut.symbol===H.symbol):void 0;if(Pe){vt(`replay moved ${_} -> ${Pe.key}`),t.push(Pe.observed),Pe.symbol&&o.set(Pe.observed.findingId,Pe.symbol);continue}i.set(_,R),vt(`replay verified ${_} against ${R}`)}}return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,...h.length>0?{warning:h.join("; ")}:{}}}var Wh=1;function Hh(e,t,n){let r=[...e.entries()].sort(([c],[l])=>c.localeCompare(l));if(r.length<=1)return r;let i=n===void 0||!Number.isSafeInteger(n)||n<0?Wh:n,o=Math.min(r.length,i);if(o===0)return[];if(o>=r.length)return r;let a=Bh("sha256").update(t??"unresolved-head").digest().readUInt32BE(0)%r.length;return Array.from({length:o},(c,l)=>r[(a+l)%r.length])}function Gh(e,t){let n=pn(e,["rev-parse","--verify",`${t}^{commit}`]);return n&&/^[0-9a-f]{40}$/.test(n)?n:null}function vt(e){process.env.SCIP_QUERY_DEBUG&&console.error(`outcome-verification: ${e}`)}function Uh(e){return[...e.findings.map(t=>({check:t.check,findingId:t.id,suppressed:!1})),...e.suppressed.map(t=>({check:t.finding.check,findingId:t.finding.id,suppressed:!0}))]}function Jh(e){return[...e.findings.map(t=>({key:he(t.check,t.id),check:t.check,observed:{check:t.check,findingId:t.id,suppressed:!1},...t.symbol?{symbol:t.symbol}:{}})),...e.suppressed.map(t=>({key:he(t.finding.check,t.finding.id),check:t.finding.check,observed:{check:t.finding.check,findingId:t.finding.id,suppressed:!0},...t.finding.symbol?{symbol:t.finding.symbol}:{}}))]}var Rt="__diff-gate-run",xt="SCIP_QUERY_DIFF_GATE_REQUEST",Yh="SCIP_QUERY_DIFF_GATE_TIMEOUT_MS",Xh=6e4,Qh=18e4,Zh=6e5,Yi=class extends Error{constructor(n,r){let i=r.owner,o=r.record?.startedAt;super(`another diff-gate is already running${i?` (PID ${i.pid})`:""}${o?` since ${o}`:""}; wait for that gate to finish instead of starting a duplicate`);this.lockPath=n;this.observation=r;this.name="DiffGateBusyError"}lockPath;observation;code="SCIP_QUERY_DIFF_GATE_BUSY"};function md(e,t){let n=jl(e,"diff-gate",t.full,{quiet:!0}),r={base:t.base,minTogether:t.minTogether,maxEchoChecks:t.maxEchoChecks,maxHelpers:t.maxHelpers,includeBaseline:t.includeBaseline,scanLimit:n.scanLimit,semantic:n.semantic,historyMode:t.full?"full":"bounded",skip:t.skip},i=Mi(e,r),o=ud(e,i,{replayGate:(s,a)=>{let c=new Set(a);return Mi(e,{...r,base:s,includeBaseline:c.has("baseline"),skip:rt.filter(l=>!c.has(l))})}});return{result:i,outcomes:{observed:o.observed,now:o.now,...o.warning?{warning:o.warning}:{},...t.includeOutcomeLedger?{ledger:o.ledger}:{}},...n.analysisBudget?{analysisBudget:n.analysisBudget}:{}}}function fd(e){if(!e)throw new Error(`${xt} is required for ${Rt}.`);let t;try{t=JSON.parse(e)}catch(r){throw new Error(`${xt} is not valid JSON.`,{cause:r})}if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${xt} must contain an object.`);let n=t;if(n.base!==void 0&&typeof n.base!="string"||!ny(n.minTogether)||n.maxEchoChecks!==void 0&&!pd(n.maxEchoChecks)||n.maxHelpers!==void 0&&!pd(n.maxHelpers)||typeof n.includeBaseline!="boolean"||typeof n.includeOutcomeLedger!="boolean"||typeof n.full!="boolean"||!Array.isArray(n.skip)||n.skip.some(r=>!rt.includes(r)))throw new Error(`${xt} contains invalid diff-gate options.`);return{...n.base===void 0?{}:{base:n.base},minTogether:n.minTogether,...n.maxEchoChecks===void 0?{}:{maxEchoChecks:n.maxEchoChecks},...n.maxHelpers===void 0?{}:{maxHelpers:n.maxHelpers},includeBaseline:n.includeBaseline,includeOutcomeLedger:n.includeOutcomeLedger,full:n.full,skip:[...n.skip]}}function $r(e,t){let n=zh(t.cacheDir,"runtime","diff-gate.lock");return ey(n,t.projectRoot,()=>Al({cliPath:t.cliPath??process.argv[1]??Kh(import.meta.url),command:Rt,args:["--json"],env:{...t.env??process.env,SCIP_QUERY_PROJECT_ROOT:t.projectRoot,[xt]:JSON.stringify(e)},label:"diff-gate",timeoutMs:t.timeoutMs??ty(e.full,t.env??process.env),maxBuffer:50*1024*1024}))}function ey(e,t,n){let r=Ot(e,{kind:"diff-gate",detail:{projectRoot:t}});if(r.kind==="contended")throw new Yi(e,r.observation);try{return n()}finally{r.lock.release()}}function ty(e,t=process.env){let n=e?Qh:Xh,r=t[Yh];if(!r)return n;let i=Number(r);return!Number.isSafeInteger(i)||i<=0?n:Math.min(i,Zh)}function ny(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function pd(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}import{execFileSync as Yd,spawn as ob}from"child_process";import{createHash as sb}from"crypto";import{existsSync as wt,mkdirSync as ab,realpathSync as qd,rmSync as cb,writeFileSync as lb}from"fs";import{homedir as db}from"os";import{dirname as Xd,isAbsolute as ub,join as kn,resolve as pb}from"path";import{execFileSync as qy}from"child_process";import{readdirSync as ry}from"fs";import{isAbsolute as gd,join as iy,resolve as oy}from"path";var Cr="@sourcegraph/scip-typescript@0.4.0",hd="scip-python-plus@0.7.5",yd="github.com/sourcegraph/scip-go@v0.2.7",bd="scip-dotnet@0.2.14",sy="scip_dart@1.6.2",ay={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",identity:Cr,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Cr]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",identity:Cr,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Cr]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:At.language,indexerBinary:At.indexerBinary,checkCommand:`${At.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:At.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[],installUrl:At.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",identity:hd,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",hd]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",gd(r)?r:oy(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",identity:yd,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",yd]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Sd(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",identity:bd,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Sd(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",identity:bd,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",identity:sy,destination:"Dart pub global cache",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart","1.6.2"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({indexerBinary:e})=>gd(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function kt(e){return ay[e]}function Sd(e,t){let n;try{n=ry(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return iy(e,i);return null}import{createRequire as cy}from"module";var ly=cy(import.meta.url);function vd(e,t=[]){let n=dy(),r=va(e,t),i=r[0];return n?r.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r}:{available:!1,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r,reason:"ts-morph is not installed"}}function dy(){try{return ly.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Bt,spawnSync as uy}from"child_process";import{existsSync as Ae,mkdtempSync as wd,readdirSync as py,rmSync as $d,symlinkSync as my,writeFileSync as fy}from"fs";import{tmpdir as Cd}from"os";import{join as ge}from"path";var gy=3e5,hy=12;function Zi(e,t,n={}){let r=eo(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:Xi(e),batches:[]};let i=vy(t,r),o=n.timeoutMs??gy,s=$y(e,t),a=Xi(e),c=wd(ge(Cd(),"scip-cleanup-verify-")),l=[],d=new Map;try{Bt("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),Cy(e,c);for(let u of r)d.set(u.label,Rd(u,c,o).rawErrors);for(let u of t.batches){Td(c,u);let m=null;for(let g of r){let f=Rd(g,c,o),h=yy(f,d.get(g.label)??[],f.rawErrors);if(h.status==="failed"){let S=h.errors.length>0?h.errors:f.outputTail;m={depth:u.depth,status:"failed",reason:`${g.label}: ${h.reason}`,errors:S.slice(0,hy)};break}}if(!m)l.push({depth:u.depth,status:"verified"});else{l.push(m);break}}}finally{try{Bt("git",["-C",e,"worktree","remove","--force",c],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"})}catch{$d(c,{recursive:!0,force:!0})}}return{checkers:r.map(u=>u.label),uncoveredFiles:i,baselineErrors:[...d.values()].reduce((u,m)=>u+m.length,0),dirtyOverlap:s,dirtyWorkingTree:a,batches:l}}function yy(e,t,n){let r=by(t,n);return r.length>0?{status:"failed",reason:"checker reported new errors",errors:r}:e.ok?{status:"verified",reason:"checker passed",errors:[]}:{status:"failed",reason:`checker exited ${e.exitCode===null?"unknown":String(e.exitCode)} with unparsed output`,errors:[...e.outputTail??[]]}}function by(e,t){let n=Sy(e),r=new Map,i=[];for(let o of t){let s=Pd(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function Sy(e){let t=new Map;for(let n of e){let r=Pd(n);t.set(r,(t.get(r)??0)+1)}return t}function vy(e,t){let n=new Set(t.flatMap(i=>i.coversExtensions));return[...new Set(e.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>{let o=i.slice(i.lastIndexOf("."));return!n.has(o)}).sort()}function Pd(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var xd=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],xy=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function eo(e){let t=[];if(Ae(ge(e,"tsconfig.json"))){let n=ge(e,"node_modules",".bin","tsc");t.push(Ae(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:xd,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:xd,strength:"reference-aware"})}if(Ae(ge(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"],strength:"reference-aware"}),["pyproject.toml","setup.py","requirements.txt"].some(n=>Ae(ge(e,n)))){let n=Ry();n&&t.push(n)}if(xy.some(n=>Ae(ge(e,n)))){let n=ky(e);n&&t.push(n)}for(let n of wy(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--message-format","json","--manifest-path",n],coversExtensions:[".rs"],strength:"reference-aware",env:{...process.env,CARGO_TARGET_DIR:ge(e,n,"..","target")}});return t}function Ry(){return We("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--output-format","json","--select","E9,F821,F822","."],coversExtensions:[".py"],strength:"reference-aware"}:We("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function ky(e){let t=ge(e,"node_modules",".bin","clj-kondo");return Ae(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Jn],strength:"reference-aware"}:We("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Jn],strength:"reference-aware"}:We("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...Jn],strength:"reference-aware"}:null}function wy(e){let t=[];if(Ae(ge(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=py(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||Ae(ge(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function $y(e,t){let n=new Set(Xi(e));return[...new Set(t.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function Xi(e){let t;try{t=Bt("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",timeout:3e4,killSignal:"SIGKILL"})}catch{return[]}return t.split(`
8
- `).map(n=>n.slice(3).trim()).filter(n=>n!=="").sort()}function Cy(e,t){for(let n of["node_modules"]){let r=ge(e,n),i=ge(t,n);if(Ae(r)&&!Ae(i))try{my(r,i,"junction")}catch{}}}function Td(e,t){let n=new Map;for(let r of t.entries){let i=n.get(r.file)??[];i.push({start:r.startLine,end:r.endLine}),n.set(r.file,i)}for(let[r,i]of n){let o=ge(e,r);if(!Ae(o))continue;let s=U(o,{maxBytes:Re,inputKind:"cleanup verification source file"});fy(o,Py(s,i,{rust:r.endsWith(".rs")}))}}function to(e,t){for(let n of t)Td(e,n)}function Ed(e,t){let n=wd(ge(Cd(),"scip-cleanup-patch-"));try{return Bt("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),to(n,t),Bt("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024,timeout:3e4,killSignal:"SIGKILL"})}finally{try{Bt("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"})}catch{$d(n,{recursive:!0,force:!0})}}}function no(e,t={}){if(t.all)return[...e.batches];if(t.batch!==void 0){let n=e.batches.find(r=>r.depth===t.batch);return n?[n]:[]}return[...e.batches]}function ro(e,t,n={}){let r=[];e.checkers.length===0&&r.push("No project checker was detected, so no deletion patch is compiler-verified."),e.uncoveredFiles.length>0&&r.push(`No detected checker covers: ${e.uncoveredFiles.join(", ")}.`),!n.allowDirty&&e.dirtyOverlap.length>0&&r.push(`Plan files are dirty in the working tree: ${e.dirtyOverlap.join(", ")}.`);let i=new Set(e.batches.filter(o=>o.status==="verified").map(o=>o.depth));for(let o of t)i.has(o.depth)||r.push(`Batch ${o.depth} is not verified by the detected checker(s).`);return r}function Py(e,t,n={}){let r=e.split(`
9
- `),i=(n.rust===!0?Ty(e):Ws(e)).split(`
10
- `),o=new Set;for(let s of t){let a=Ey(r,s.start),c=Ay(i,a,Math.min(s.end,r.length-1));for(let l=a;l<=c&&l<r.length;l++)o.add(l)}return r.filter((s,a)=>!o.has(a)).join(`
11
- `)}function Ty(e){return e.replace(/\/\/.*$/gm,t=>t.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\r\n]/g," ")).replace(/"(?:\\.|[^"\\\r\n])*"/g,t=>t.replace(/[^\r\n]/g," "))}function Ey(e,t){let n=t;for(;n>0;){let r=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(r))n-=1;else break}return n}var Iy=200;function Ay(e,t,n){let r=0;for(let i=t;i<e.length;i++){for(let o of e[i]??"")o==="("||o==="["||o==="{"?r+=1:(o===")"||o==="]"||o==="}")&&(r-=1);if(i>=n&&r<=0)return i;if(i-n>Iy)break}return n}function Rd(e,t,n){let r=uy(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,killSignal:"SIGKILL",env:e.env??process.env,maxBuffer:33554432}),i=`${r.stdout??""}
12
- ${r.stderr??""}`;if(r.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:kd(i)};let o=jy(e.label,i),s=o.diagnostics.length>0?o.diagnostics:r.error?[{file:"",message:String(r.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:r.status,rawErrors:s.map(By),diagnostics:s,parseBasis:o.parseBasis,outputTail:kd(i)}}function jy(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:Ly(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:Dy(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=Oy(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:My(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:Fy(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:Ny(t),parseBasis:"clj-kondo-json"}:{diagnostics:_y(t),parseBasis:"heuristic"}}function Ly(e){let t=[],n=/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"tsc"});return t}function Dy(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),message:r[4]??"",parseBasis:"go"});return t}function Oy(e){let t=Id(e);if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let i=r,o=i.location,s=o&&typeof o=="object"?o:{},a=typeof i.filename=="string"?i.filename:"",c=typeof i.message=="string"?i.message:"";!a&&!c||n.push({file:a,line:typeof s.row=="number"?s.row:void 0,column:typeof s.column=="number"?s.column:void 0,code:typeof i.code=="string"?i.code:void 0,message:c,parseBasis:"ruff-json"})}return n}function My(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+([A-Z]\d{3})\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"ruff-text"});return t}function Fy(e){let t=[];for(let n of e.split(`
13
- `)){if(!n.trim().startsWith("{"))continue;let r=Qi(n);if(!r||typeof r!="object")continue;let i=r;if(i.reason!=="compiler-message")continue;let o=i.message;if(!o||typeof o!="object")continue;let s=o;if(s.level!=="error")continue;let l=(Array.isArray(s.spans)?s.spans:[]).find(u=>!!u&&typeof u=="object"&&u.is_primary===!0),d=s.code;t.push({file:typeof l?.file_name=="string"?l.file_name:"",line:typeof l?.line_start=="number"?l.line_start:void 0,column:typeof l?.column_start=="number"?l.column_start:void 0,code:d&&typeof d=="object"&&typeof d.code=="string"?String(d.code):void 0,message:typeof s.message=="string"?s.message:"",parseBasis:"cargo-json"})}return t}function Ny(e){let t=Id(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let r=[];for(let i of n){if(!i||typeof i!="object")continue;let o=i;o.level==="error"&&r.push({file:typeof o.filename=="string"?o.filename:"",line:typeof o.row=="number"?o.row:void 0,column:typeof o.col=="number"?o.col:void 0,code:typeof o.type=="string"?o.type:void 0,message:typeof o.message=="string"?o.message:"",parseBasis:"clj-kondo-json"})}return r}function _y(e){return e.split(`
14
- `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function By(e){let t=e.file.length>0?`${e.file}${e.line?`:${e.line}`:""}${e.column?`:${e.column}`:""}: `:"",n=e.code?`${e.code} `:"";return`${t}${n}${e.message}`.trim()}function Id(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return Qi(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?Qi(t.slice(n)):null}function Qi(e){try{return JSON.parse(e)}catch{return null}}function kd(e,t=10){return e.split(`
15
- `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Ld={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".vue"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]},Vy={typescript:"typescript",javascript:"javascript",java:"java",scala:"scala",kotlin:"kotlin",rust:"rust",python:"python",ruby:"ruby",cpp:"cpp",c:"c",csharp:"csharp",vb:"vb",php:"php",clojure:"clojure"},Wy={typescript:"javascript",javascript:"javascript",java:"jvm",scala:"jvm",kotlin:"jvm",rust:"rust",python:"python",ruby:"ruby",cpp:"c/cpp",c:"c/cpp",csharp:"dotnet",vb:"dotnet",dart:"dart",php:"php",clojure:"clojure"};function $e(e,t){let n=t.languages??yt(e),r=n.map(a=>{let c=nr(kt(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=Xy(e,n,t),o=io({semantics:i},"typescript"),s=eo(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:eb(e)}}function ot(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,r=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",i=r!=="unavailable",o=e.languages.map(c=>Ky(e,c,{hasIndexedGraph:zy(c,t),runtimeProbe:t.runtimeProbe})),s=o.map(c=>c.cleanupVerification.status),a=s.length===0||s.every(c=>c==="unavailable")?"unavailable":s.every(c=>c==="available")?"available":"partial";return{languages:e.languages,matrix:o,capabilities:[{id:"indexing",label:"SCIP indexing",status:r,evidence:"graph-fact",reason:r==="available"?"All detected/configured language indexers are runnable.":t.hasIndexedGraph?`An indexed graph is present; ${n}/${e.indexers.length} detected/configured language indexers are runnable for refresh.`:`${n}/${e.indexers.length} detected/configured language indexers are runnable.`},...Hy(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:i?"available":"unavailable",evidence:"heuristic",reason:i?"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index.":"Heuristic detectors need an indexed code graph."},{id:"cleanup-verification",label:"Project cleanup verification",status:a,evidence:"checker",reason:a!=="unavailable"?o.map(c=>`${c.language}: ${c.cleanupVerification.status} (${c.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&i?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-file gates.":"Git is unavailable or the project root is not a git worktree."}]}}function Hy(e){return Gy(e).map(t=>{let n=io(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${Uy(t)} semantic provider`,status:r,evidence:"semantic",reason:Jy(t,n)}})}function Gy(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of Od(e))t.add(n.language);return[...t].sort((n,r)=>Ad(n)-Ad(r))}function Ad(e){return e==="typescript"?0:1}function Uy(e){return e==="typescript"?"TypeScript":"Rust"}function Jy(e,t){return t?.available?e==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":t?t.reason??(e==="typescript"?"TypeScript semantic checks will fall back to SCIP/source evidence.":"Rust semantic checks will fall back to SCIP/source evidence."):e==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}function Ky(e,t,n){let r=e.indexers.find(d=>d.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=Yy(t,n.runtimeProbe),a=Qy(e,t),c=Zy(e,t),l=c.length===0?"unavailable":c.every(d=>d.strength!=="syntax-only")?"available":"partial";return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="available"?`${r?.binaryLabel??t} is runnable${r?.resolvedBinary?` at ${r.resolvedBinary}`:""}.`:i==="partial"?`An indexed ${t} graph is present, but ${r?.binaryLabel??t} is not currently runnable for refresh.`:r?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:o?s.status:"unavailable",evidence:"heuristic",reason:o?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above.":"Cleanup detectors need an indexed graph for this language."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:l,evidence:"checker",reason:c.length>0?c.map(d=>d.label).join(", "):`No detected checker covers ${Ld[t].join(", ")} files.`}}}function zy(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function Yy(e,t){if(e==="go")return{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."};if(e==="clojure")return(t?.(e)??jd(e))==="unavailable"?{status:"unavailable",reason:"Clojure built-in reader is not available in this environment; no source-fallback evidence can be produced."}:{status:"available",reason:"Clojure source fallback uses the built-in reader for namespace imports plus callable, callsite, and protocol/record member evidence for .clj, .cljs, and .cljc files."};let n=Dd(e);if(n==="regex-only")return{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`};if(!n)return{status:"unavailable",reason:`No source-fallback adapter is registered for ${e}.`};let r=t?.(e)??jd(e);return r==="unavailable"?{status:"partial",reason:"tree-sitter native module not loadable \u2014 regex/import-only evidence remains available where registered."}:r==="regex"?{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`}:r==="reader"?{status:"available",reason:`${e} source fallback is reader-backed.`}:{status:"available",reason:n==="ast-dispatch-with-regex-fallback"?`AST-dispatched source fallback covers ${e} imports.`:`AST/source fallback covers ${e} imports and source-backed evidence.`}}function jd(e){let t=Vy[e];return t?zn(t):Dd(e)==="regex-only"?"regex":"unavailable"}function Dd(e){let t=Wy[e],n=t?Ks(t):null;return n?.imports??n?.exports??n?.reExports??null}function Xy(e,t,n){let r=[];return t.includes("typescript")&&r.push({language:"typescript",...vd(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&r.push({language:"rust",...sa(e)}),r}function Od(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function io(e,t){return Od(e).find(n=>n.language===t)}function Qy(e,t){if(t!=="typescript"&&t!=="rust")return{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:`No semantic provider is registered for ${t}; commands use graph and source evidence instead.`};let n=io(e,t);return n?{id:"semantic",label:"Semantic provider",status:n.available?"available":n.dependencyAvailable?"partial":"unavailable",evidence:"semantic",reason:n.available?t==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":n.reason??`${t} semantic checks fall back to SCIP/source evidence.`}:{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:t==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}}function Zy(e,t){let n=new Set(Ld[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function eb(e){try{return qy("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{existsSync as oo}from"fs";import{join as vn}from"path";var Ye="<!-- scip-query:agent-setup:begin -->",qt="<!-- scip-query:agent-setup:end -->",Pr="# scip-query:agent-setup";function Vt(){if(process.stdin.isTTY)return"";try{return Bs(0,{maxBytes:xe,inputKind:"agent hook input"})}catch{return""}}function Tr(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function xn(e){let t=ar(e.findings),n=e.findings.length-t.length,r=e.rootCauseGroups?.length??e.findings.length,i=[`scip-query diff-gate found ${t.length} issue(s) in ${r} root-cause group(s) in this diff`+(n>0?` (+${n} advisory, non-blocking)`:"")+" \u2014 fix or knowingly accept them before finishing:"],o=e.rootCauseGroups?.filter(s=>s.count>1)??[];for(let s of o)i.push(`- group [${s.check}] ${s.count} finding(s): ${s.message}`),i.push(` -> ${s.remediation}`);for(let s of e.findings)i.push(`- [${s.check}]${s.advisory?" (advisory)":""} ${s.message}`),i.push(` -> ${s.remediation}`);return i.join(`
16
- `)}function Er(e,t={}){let n={written:[],unchanged:[],skipped:[]};return tb(e,n),t.gitHook&&rb(e,n),n}function _d(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Fd(e,"AGENTS.md",t,n),Fd(e,"CLAUDE.md",t,n),ib(e,t,n),n}function tb(e,t){let n=[Ye,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Use native search and file reads for literal text and source. Use scip-query when a claim depends on compiler-resolved identity, references, callers, dependencies, consumers, public surface, transitive impact, architecture, historical co-change, or a scip detector/gate.","- Unsure how to explore, plan, verify, or clean up here: invoke the `scip-query` skill \u2014 it routes to the right specialist skill.","- Each specialist skill carries its own command shortlist \u2014 prefer it over the full `_shared` catalog.","- Before the first SCIP graph claim in a work session, run `scip-query status --capabilities` once. Reuse that fresh generation until source changes. After edits, let an active watcher finish its refresh; if it is busy or a refresh request is pending, wait and recheck instead of starting a competing reindex. Run `scip-query reindex` only when freshness is stale, missing, or unknown and the watcher is disabled, unavailable, or failed to refresh.","- For a non-trivial change: establish the current entry-to-effect flow, the affected consumers, and the reuse options before editing (`scip-plan` skill, anchored by `scip-query plan-context <target>`).","- Before claiming a complete relationship set, inspect the command coverage. If it is bounded or unknown, use `--full`, a narrower scope, or command pagination before making the claim.","- After the change, run the postchecks matching what you actually edited \u2014 the table is in the `scip-verify` skill \u2014 then `scip-query diff-gate`. Fix findings or state why each is accepted.","- Incomplete output is not evidence. Before making a conclusion, changing to another evidence command, or reporting completion, run every emitted `Continue exactly:` command unchanged until the page reports `complete: true`. Never pipe scip-query through `head`, `tail`, or line-range `sed`. Every command supports `--output-page-size` plus `--output-cursor`; this transport cursor is separate from a command result cursor such as `refs --cursor`.","- Repository records: commit `.scipquery/suppressions/*.json` and `.scipquery/events/*.json` with the code or docs change that produced them; do not ignore or drop these shared records.","- Checkout preferences: `.codex/hooks.json` and `.claude/settings.local.json` are local agent-tool settings and must not be committed.",qt].join(`
17
- `);Md(e,"AGENTS.md",n,t);let r=[Ye,"@AGENTS.md",qt].join(`
18
- `);Md(e,"CLAUDE.md",r,t,i=>i.includes("@AGENTS.md")&&!i.includes(Ye))}function Md(e,t,n,r,i){let o=vn(e,t),s=!1,a=Ir(o,t,r,c=>{if(i?.(c.text))return s=!0,{kind:"unchanged"};let l=nb(c.text,n);return l===c.text?{kind:"unchanged"}:{kind:"write",text:l,...c.revision.exists?{}:{mode:420}}});a&&(!a.changed||s?r.unchanged.push(t):r.written.push(t))}function Fd(e,t,n,r){let i=vn(e,t);if(n.dryRun){if(!oo(i)){r.unchanged.push(t);return}try{let s=V(i,"agent instruction file");s.includes(Ye)?(Nd(s),r.removed.push(t)):r.unchanged.push(t)}catch(s){r.skipped.push({target:t,reason:s instanceof Error?s.message:String(s)})}return}let o=Ir(i,t,r,s=>{if(!s.revision.exists||!s.text.includes(Ye))return{kind:"unchanged"};let a=Nd(s.text);return a.length===0?{kind:"delete"}:{kind:"write",text:a}});o&&(o.changed?r.removed.push(t):r.unchanged.push(t))}function nb(e,t){if(Bd(e)==="present"){let r=new RegExp(`${Ye}[\\s\\S]*?${qt}`);return e.replace(r,t)}return e.length>0?`${e.replace(/\n*$/,`
19
-
20
- `)}${t}
21
- `:`${t}
22
- `}function Nd(e){Bd(e);let t=new RegExp(`${Ye}[\\s\\S]*?${qt}`),n=e.replace(t,"").replace(/\n{3,}/g,`
23
-
24
- `).trim();return n.length===0?"":`${n}
25
- `}function Bd(e){let t=e.split(Ye).length-1,n=e.split(qt).length-1;if(t===0&&n===0)return"absent";if(t===1&&n===1&&e.indexOf(Ye)<e.indexOf(qt))return"present";throw new Error("managed scip-query markers are incomplete, duplicated, or out of order")}function Ir(e,t,n,r){try{return ht(e,r,{maxRetries:0})}catch(i){n.skipped.push({target:t,reason:i instanceof Error?i.message:String(i)});return}}function rb(e,t){let n=vn(e,".git","hooks");if(!oo(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=vn(n,"pre-commit"),i=["#!/bin/sh",Pr,"scip-query diff-gate || {",' echo "scip-query diff-gate failed \u2014 fix findings or commit with --no-verify to knowingly accept." >&2'," exit 1","}",""].join(`
26
- `),o=!1,s=Ir(r,".git/hooks/pre-commit",t,a=>a.revision.exists&&!a.text.includes(Pr)?(o=!0,{kind:"unchanged"}):a.text===i?{kind:"unchanged"}:{kind:"write",text:i,mode:493});s&&(o?t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"}):s.changed?t.written.push(".git/hooks/pre-commit"):t.unchanged.push(".git/hooks/pre-commit"))}function ib(e,t,n){let r=vn(e,".git","hooks","pre-commit");if(t.dryRun){oo(r)?V(r,"pre-commit hook").includes(Pr)?n.removed.push(".git/hooks/pre-commit"):n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"}):n.unchanged.push(".git/hooks/pre-commit");return}let i=!1,o=Ir(r,".git/hooks/pre-commit",n,s=>s.revision.exists?s.text.includes(Pr)?{kind:"delete"}:(i=!0,{kind:"unchanged"}):{kind:"unchanged"});o&&(i?n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"}):o.changed?n.removed.push(".git/hooks/pre-commit"):n.unchanged.push(".git/hooks/pre-commit"))}var Qd="SCIP_QUERY_SKIP_HOOK_INSTALL",so="SCIP_QUERY_STOP_HOOK_MODE",mb="scip-query hook-",fb="scip-query diff-gate --hook",Vd="# scip-query:local-hooks:begin",Wd="# scip-query:local-hooks:end",Rn=[{relativePath:".codex/hooks.json",label:".codex/hooks.json"},{relativePath:".claude/settings.local.json",label:".claude/settings.local.json"}];function Wt(e,t={}){let n=Zd(),r=t.env??process.env;if(bb(r))return n.skipped.push({target:"project agent hooks",reason:`${Qd}=1`}),n;let i=t.commandPrefix??Cb(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),hb(e,n,t.dryRun),t.remove?(Gd(e,Rn[0],n,{dryRun:t.dryRun}),Gd(e,Rn[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(Hd(e,Rn[0],n,{provider:"codex",commandPrefix:i,force:t.force}),Hd(e,Rn[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&gb({homeDir:t.homeDir,result:n}),n)}function gb(e={}){let t=e.result??Zd(),n=e.homeDir??db();return ao({configPath:kn(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),ao({configPath:kn(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function Zd(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function Hd(e,t,n,r){if(co(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook setup will not modify it"});return}let i=kn(e,t.relativePath);Sb({provider:r.provider,rootDir:Xd(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function Gd(e,t,n,r){if(co(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}vb({configPath:kn(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function hb(e,t,n=!1){let r=yb(e);if(!r){t.warnings.push("Could not locate .git/info/exclude; local hook files may appear as untracked.");return}let i=Rn.filter(a=>!co(e,a.relativePath));if(i.length===0)return;let o=[Vd,...i.map(a=>`/${a.relativePath}`),Wd].join(`
27
- `),s=new RegExp(`${Ve(Vd)}[\\s\\S]*?${Ve(Wd)}\\n?`,"g");if(!n)try{ht(r,a=>{let c=a.text.replace(s,"").replace(/\n*$/,""),l=`${c}${c?`
28
-
29
- `:""}${o}
30
- `;return l===a.text?{kind:"unchanged"}:{kind:"write",text:l,...a.revision.exists?{}:{mode:420}}})}catch(a){t.warnings.push(a instanceof Error?a.message:String(a));return}t.gitExcluded.push(...i.map(a=>a.label))}function yb(e){try{let t=Yd("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).trim();return t?ub(t)?t:pb(e,t):null}catch{return null}}function co(e,t){try{return Yd("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),!0}catch{return!1}}function bb(e=process.env){let t=e[Qd];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function Ud(e=process.env){let t=e[so]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function Sb(e){if(!e.createRoot&&!wt(e.rootDir))return;let t=!1,n=eu(e.configPath,e.label,e.result,r=>{if(r.scipQueryHooks==="declined"&&!e.force)return t=!0,{kind:"unchanged"};let i=kb(r,e.provider,e.commandPrefix);return JSON.stringify(i)===JSON.stringify(r)?{kind:"unchanged"}:{kind:"write",text:tu(i)}});if(n){if(t){e.result.skipped.push({target:e.label,reason:"scip-query hooks were previously removed; rerun with --force"});return}if(!n.changed){e.result.unchanged.push(e.label);return}e.result[n.previous.revision.exists?"updated":"installed"].push(e.label)}}function ao(e){if(!wt(e.configPath)&&!e.writeDeclinedTombstone)return;let t=r=>{let i=xb(r,e.writeDeclinedTombstone);return JSON.stringify(i)===JSON.stringify(r)?{kind:"unchanged"}:Object.keys(i).length===0?{kind:"delete"}:{kind:"write",text:tu(i)}};if(e.dryRun){let r=nu(e.configPath,e.label,e.result);if(!r)return;t(r).kind!=="unchanged"&&e.result.removed.push(e.label);return}eu(e.configPath,e.label,e.result,t)?.changed&&e.result.removed.push(e.label)}function vb(e){let t=e.result.removed.length;ao(e),e.writeDeclinedTombstone&&e.result.removed.length===t&&nu(e.configPath,e.label,e.result)?.scipQueryHooks==="declined"&&e.result.removed.push(`${e.label} (declined)`)}function xb(e,t=!1){let n=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},r={...n};for(let o of["SessionStart","UserPromptSubmit","PostCompact","PreToolUse","Stop"]){if(!Array.isArray(n[o]))continue;let s=n[o],a=ru(s);a.length>0?r[o]=a:delete r[o]}let i={...e};return Object.keys(r).length>0?i.hooks=r:delete i.hooks,t&&(i.scipQueryHooks="declined"),i}function eu(e,t,n,r){try{return ht(e,i=>{let o=Rb(i);return r(o,i)})}catch(i){n.skipped.push({target:t,reason:i instanceof Error?i.message:String(i)});return}}function Rb(e){if(!e.revision.exists)return{};try{let t=JSON.parse(e.text);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("top-level value is not an object");return t}catch(t){throw new Error(`Cannot update ${e.path}: the latest hook config is invalid JSON (${t instanceof Error?t.message:String(t)}).`,{cause:t})}}function tu(e){return`${JSON.stringify(e,null,2)}
31
- `}function nu(e,t,n){if(!wt(e))return{};try{let r=JSON.parse(V(e,"agent hook settings"));if(!r||typeof r!="object"||Array.isArray(r)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return r}catch(r){n.skipped.push({target:t,reason:`could not parse existing hook config: ${r instanceof Error?r.message:String(r)}`});return}}function kb(e,t,n="scip-query"){let r=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},i={...e,hooks:{...r}};i.scipQueryHooks==="declined"&&delete i.scipQueryHooks;let o=t==="claude"?["SessionStart","UserPromptSubmit","PostCompact","PreToolUse","Stop"]:["SessionStart","UserPromptSubmit","Stop"];for(let s of o){let a=Array.isArray(r[s])?r[s]:[];i.hooks[s]=[...ru(a),$b(t,s,n)]}return i}function ru(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!wb(n)):[]})).filter(t=>t.hooks.length>0)}function wb(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(mb)||t===fb||/(?:^|\s)hook-(?:context|pretool|stop)$/.test(t))}function $b(e,t,n){return t==="SessionStart"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Refreshing scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Checking scip-query freshness"}]}:t==="PostCompact"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:10,statusMessage:"Resetting scip-query context reminder"}]}:t==="PreToolUse"?{matcher:"Bash|Grep|Glob",hooks:[{type:"command",command:`${n} hook-pretool`,timeout:10,statusMessage:"Checking scip-query evidence integrity"}]}:{hooks:[{type:"command",command:`${n} hook-stop`,timeout:30,statusMessage:"Running scip-query diff gate"}]}}function Cb(e){let t=qd(e),n=[er("scip-query"),process.argv[1]].filter(r=>!!r);for(let r of n){if(!wt(r))continue;let i=qd(r);if(de(t,i))continue;let o=Zn(i,[]);return[o.binary,...o.args].map(Pb).join(" ")}throw new Error("Cannot install persistent hooks without a scip-query CLI identity outside the target checkout. Install scip-query globally and rerun setup-hooks.")}function Pb(e){return process.platform==="win32"?`"${e.replaceAll("%","%%").replaceAll('"','\\"')}"`:`'${e.replaceAll("'",`'"'"'`)}'`}async function iu(){let e=await Ob(Vt());e&&fr(JSON.stringify(e))}function ou(){let e=uo(Vt()),t=po(e);if(!t||!wt(t.paths.dbPath))return;let n=su(t.paths.cacheDir,e),r=Tb(e,n?wt(n):!0);if(r.kind==="allow")return;r.kind==="reconsider"&&n&&(ab(Xd(n),{recursive:!0}),lb(n,`shown
32
- `));let i={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:r.reason}};fr(JSON.stringify(i))}function Tb(e,t){let n=typeof e.tool_name=="string"?e.tool_name:"",r=e.tool_input&&typeof e.tool_input=="object"?e.tool_input:{},i=n==="Bash"&&typeof r.command=="string"?r.command:"";return i&&Eb(i)?{kind:"deny",reason:"Do not pipe scip-query output through head, tail, or a line-range sed selector: that discards evidence without a resumable position. Re-run the exact emitted paging command and follow each --output-cursor continuation until complete; command-level coverage such as refs --cursor remains a separate step."}:!(n==="Grep"||n==="Glob"||n==="Bash"&&/(?:^|[;&|]\s*)(?:rg|grep)(?:\s|$)/.test(i))||t?{kind:"allow"}:{kind:"reconsider",reason:"Pause once before native search in this indexed repository. If you need compiler-resolved identity or a complete set of definitions, references, callers, consumers, dependencies, or affected units, use scip-query. If you only need literal text, filenames, or local source, retry the same search unchanged; it will be allowed for the rest of this context window."}}function Eb(e){return/(?:^|[;&(]\s*|\s)(?:\S*\/)?scip-query\s+[A-Za-z][A-Za-z0-9-]*(?:\s|$)/.test(e)?/\|\s*(?:head|tail)(?:\s|$)/.test(e)||/\|\s*sed\s+(?:-[A-Za-z]+\s+)*(?:['"])?\d+\s*,\s*\d+\s*p/.test(e):!1}function su(e,t){let n=typeof t.session_id=="string"?t.session_id:null;if(!n)return null;let r=sb("sha256").update(n).digest("hex").slice(0,24);return kn(e,"agent-hooks",`native-search-${r}`)}function Ib(e,t){let n=su(e.paths.cacheDir,t);n&&cb(n,{force:!0})}function au(){let e=Vt(),t;try{t=Ab(e)}catch(n){let r=n instanceof Error?n.message:String(n);Jd(jb(r,Ud()));return}!t||t.findings.length===0&&!lo(t)||Jd(Lb(t,Ud()))}function Jd(e){fr(JSON.stringify(e))}function Ab(e){if(Tr(e))return;let t=uo(e),n=po(t);if(!(!n||!wt(n.paths.dbPath)))return $r({minTogether:6,includeBaseline:!1,includeOutcomeLedger:!1,full:!1,skip:[]},{projectRoot:n.projectRoot,cacheDir:n.paths.cacheDir}).result}function jb(e,t="feedback"){let n=`Diff gate could not complete and therefore cannot certify this turn: ${e}`;return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${n}
33
-
34
- Wait for an existing gate or investigate the timeout before declaring the work complete.`}}:{systemMessage:`${n}
35
-
36
- Stop-hook warn mode allowed the turn to finish, but the diff was not certified.`}}function Lb(e,t="feedback"){let n=lo(e),r=e.findings.length>0?xn(e):void 0,i=[n,r].filter(s=>!!s).join(`
37
-
38
- `),o=Db(e);return t==="block"&&e.findings.length>0?{decision:"block",reason:i}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${o}
39
-
40
- This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${o}
41
-
42
- Stop hook allowed this turn to finish. Review these findings when relevant. Set ${so}=feedback to ask the agent to continue without a hook error, or ${so}=block to enforce the gate.`}}function Db(e){let t=e.findings.length>0?xn(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:"):void 0;return[lo(e),t].filter(n=>!!n).join(`
43
-
44
- `)}function lo(e){return e.recordCompatibility?nt("Committed suppression",e.recordCompatibility.suppressions):void 0}async function Ob(e){let t=uo(e),n=Wb(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit"&&n!=="PostCompact")return;let r=po(t);if(!r||((n==="SessionStart"||n==="PostCompact")&&Ib(r,t),n==="PostCompact"))return;let i=await Fb(r,n),o=n==="SessionStart"?_b(r.projectRoot,r.config,r.paths):Bb(String(t.prompt??""),r.config),s=[i,o].filter(a=>!!a?.trim()).join(`
45
- `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}var Mb={prepare:Tl,ensureService:zl,freshness:Me,requestRefresh:Xl,startOneShot(e){ob("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function Fb(e,t,n=Mb){let r=Oe(e.config);if(r.autoRefresh===!1)return;n.prepare?.(e.projectRoot,e.config,e.paths);let i=n.freshness(e.projectRoot,e.config,e.paths);if(r.enabled){let o=n.ensureService({commandName:`agent-${t}`,projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:ye,config:e.config});return o.kind==="failed"?`scip-query watch service did not start: ${o.message}. Run 'scip-query watch --daemon' to repair it.`:o.kind==="skipped"?i.state==="fresh"?void 0:`scip-query index is ${i.state}; automatic watch service wake was skipped (${o.reason}).`:(Nb(o,i.state,e.paths.cacheDir,n),i.state!=="fresh"?`scip-query index is ${i.state}; ${o.kind==="started"?"started":"woke"} the watch service and requested refresh.`:o.kind==="started"?"scip-query watch service started for this project.":void 0)}if(i.state!=="fresh"){if(t==="UserPromptSubmit")return`scip-query index is ${i.state}; evidence commands will note staleness. Run 'scip-query reindex' to refresh.`;try{return n.startOneShot(e.projectRoot),`scip-query index is ${i.state}; started background refresh with auto-install disabled.`}catch(o){let s=o instanceof Error?o.message:String(o);return`scip-query auto-refresh skipped: index is ${i.state}, but background refresh failed to start: ${s}`}}}function Nb(e,t,n,r){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||r.requestRefresh(ir(n).activityPath,`agent hook observed ${t} index while service was idle`)}function _b(e,t,n){let r=Me(e,t,n),i=$e(e,t),s=ot(i).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=i.languages.length>0?i.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${r.state} (${r.reason})`,r.lastRefresh?`Last refresh: ${r.lastRefresh.result} by ${r.lastRefresh.trigger.kind} at ${r.lastRefresh.completedAt}.`:void 0,`Detected languages: ${a}.`,s.length>0?`Unavailable or partial capabilities: ${s.join(", ")}.`:"Core capabilities are available.","Use the scip-query router skill when exploring, planning, verifying, debugging, diagramming, or cleaning up code.","Before a non-trivial edit, establish the current entry-to-effect flow, affected consumers, and reuse options with scip-plan; then verify the finished diff with scip-verify."].filter(c=>c!==void 0).join(`
46
- `)}function Bb(e,t={},n=process.env){if(Vb(t,n)==="off")return"";let r=qb(e);return r?`scip-query routing reminder:
47
- ${r.message}`:""}var Kd=[{id:"setup",skillNames:["scip-setup"],keywords:["setup","adopt","install","bootstrap"],message:"Setup request: use scip-setup; keep CI setup out of the default path."},{id:"debug",skillNames:["scip-diagnose"],keywords:["debug","bug","regression","failing","fails","error","wrong","broken","doesn't work","not working","crash"],message:"Debug, root-cause, or issue-triage request: use scip-diagnose."},{id:"review",skillNames:["scip-audit","scip-plan","scip-verify"],keywords:["review","maintainability","architecture","boundary"],message:"Review request: use scip-audit for current structure, scip-plan for prospective API impact, or scip-verify for a finished change."},{id:"implementation",skillNames:["scip-plan","scip-verify"],keywords:["implement","build","change","refactor","fix","add","update"],message:"Before editing: use scip-plan and `scip-query plan-context <target>` to establish the current flow, affected consumers, and reuse options. After editing: use scip-verify."},{id:"exploration",skillNames:["scip-explore"],keywords:["explain","how does","walk me through","trace","understand"],message:"Exploration request: use scip-explore before answering behavioral questions."},{id:"diagram",skillNames:["scip-explore"],keywords:["diagram","visualize","visualise","flow map","architecture map"],message:"Diagram request: use scip-explore and back every node and edge with scip-query evidence."},{id:"health",skillNames:["scip-audit","scip-improve"],keywords:["health","score","dossier","cleanup","dead code","duplicate","debloat","as high as","maximize","maximise"],message:"Health or cleanup request: use scip-audit before editing; use scip-improve when the user wants confirmed issues fixed autonomously."}];function qb(e){let t=Kd.find(i=>i.skillNames.some(o=>zd(e,o)));if(t)return t;let n=0,r=[];for(let i of Kd){let o=i.keywords.filter(s=>zd(e,s)).length;n+=o,o>0&&r.push(i)}return n<2||r.length===0?null:r[0]}function Vb(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function zd(e,t){let n=t.trim().split(/\s+/).map(r=>Ve(r)).join("\\s+");return new RegExp(`(?<![A-Za-z0-9_-])${n}(?![A-Za-z0-9_-])`,"i").test(e)}function uo(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Wb(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function po(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=fa(t);if(n)try{let r=ke(n),i=He(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}import{existsSync as jr,mkdirSync as Yb,symlinkSync as Xb,readlinkSync as go,unlinkSync as ho,readdirSync as fu}from"fs";import{join as Ne,dirname as Pn,resolve as st,relative as Qb,isAbsolute as Zb}from"path";import{homedir as Lr,platform as eS}from"os";import{fileURLToPath as gu}from"url";import{execFileSync as cu}from"child_process";import{createRequire as Hb}from"module";import{existsSync as Gb}from"fs";import{platform as wn,arch as lu}from"os";var $n="v0.8.1",mo="https://github.com/sourcegraph/scip",Ar=`github.com/sourcegraph/scip/cmd/scip@${$n}`,du=Hb(import.meta.url),uu="SCIP_QUERY_SCIP_BIN";function Ub(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[uu];if(t&&e.fileExists(t))return{source:"env",path:t};if(e.platform==="win32"){let n=e.resolveSidecar(e.arch);if(n&&e.fileExists(n))return{source:"sidecar",path:n}}return null}function Jb(e){for(let t of e==="arm64"?["arm64","x64"]:[e])try{return du.resolve(`scip-query-scip-windows/scip-win32-${t}.exe`)}catch{}return null}function Ht(e=process.env){let t=Ub({platform:wn(),arch:lu(),env:e,isOnPath:It,fileExists:Gb,resolveSidecar:Jb});return t?.source==="path"?er("scip")??t.path:t?.path??null}function Cn(){return Ht()!==null}function pu(){let e=Ht();if(!e)return null;try{return cu(e,["--version"],{stdio:"pipe",timeout:1e4,killSignal:"SIGKILL"}).toString().trim()}catch{return null}}function Kb(){let e=wn(),t=lu(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`${mo}/releases/download/${$n}/${o}`,filename:o}}function fo(){let e=Kb();if(console.log("\nThe `scip` CLI is required but not found on PATH.\n"),wn()==="darwin"||wn()==="linux")console.log("Install the reviewed version with Go:"),console.log(` go install ${Ar}
48
- `),console.log("Or download that exact release manually:");else if(wn()==="win32"){let t=zb();console.log("On Windows the scip binary ships via the npm sidecar package scip-query-scip-windows,"),console.log("installed automatically with scip-query. If it is missing:"),console.log(` npm install -g ${t}`),console.log(`Or set ${uu} to a local scip.exe path.
49
- `),console.log("Upstream release page:")}else console.log("Download from:");console.log(e?` ${e.url}
50
- `:` ${mo}/releases/tag/${$n}
51
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function zb(){let t=du("../../package.json").optionalDependencies?.["scip-query-scip-windows"];if(!t||!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(t))throw new Error("scip-query package metadata does not declare an exact Windows sidecar version.");return`scip-query-scip-windows@${t}`}function mu(e){if(It("go")){e(`Installing immutable ${Ar} via go install into the Go bin directory (GOBIN or GOPATH/bin); expected executable: scip.`);try{if(cu("go",["install",Ar],{stdio:"inherit",timeout:3e5,env:process.env}),It("scip")){let t=Ht(),n=pu();if(t&&n&&n.includes($n))return e(`Successfully installed ${Ar}; resolved executable: ${t}; reported version: ${n}.`),!0;e(`go install completed, but the resolved scip executable did not report ${$n} (executable: ${t??"unresolved"}; version: ${n??"unavailable"}).`)}}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${mo}/releases`),!1}var tS=eS()==="win32",Dr=["_shared","scip-query","scip-setup","scip-explore","scip-plan","scip-diagnose","scip-audit","scip-improve","scip-verify"];function Or(e={}){let t=e.quiet?()=>{}:console.log,n=gu(import.meta.url),r=st(Pn(n),"..","skills"),i=[Ne(Lr(),".claude","skills"),Ne(Lr(),".codex","skills"),Ne(Lr(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=Pn(s);if(!jr(a))continue;Yb(s,{recursive:!0});let c=bu(s);nS(s,r,c,o,t);for(let l of Dr){let d=Ne(r,l),u=Ne(s,l);if(!jr(d)){o.skipped.push(`${c}/${l}`);continue}if(jr(u)){try{let m=go(u);if(st(m)===st(d)){o.alreadyLinked.push(`${c}/${l}`),t(` ok: ${l} \u2192 ${c} (already linked)`);continue}}catch{o.skipped.push(`${c}/${l}`),t(` skip: ${l} \u2192 ${c} (exists, not a symlink)`);continue}ho(u)}Xb(d,u,tS?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function nS(e,t,n,r,i){let o=new Set(Dr);for(let s of fu(e)){if(o.has(s))continue;let a=Ne(e,s),c;try{c=st(Pn(a),go(a))}catch{continue}yu(c,t)&&(ho(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function hu(e={}){let t=gu(import.meta.url),n=st(Pn(t),"..","skills"),r=e.homeDir??Lr(),i=[Ne(r,".claude","skills"),Ne(r,".codex","skills"),Ne(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!jr(s))continue;let a=bu(s);for(let c of fu(s)){let l=Ne(s,c),d;try{let u=go(l);d=st(Pn(l),u)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!yu(d,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{ho(l)}catch(u){o.skipped.push(`${a}/${c} (${u instanceof Error?u.message:String(u)})`)}}}return o}function yu(e,t){let n=Qb(st(t),st(e));return n===""||!n.startsWith("..")&&!Zb(n)}function bu(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as Qm}from"child_process";import{performance as lt}from"perf_hooks";import{chmodSync as l$,existsSync as se,mkdirSync as d$,realpathSync as u$,renameSync as ls,rmSync as as,unlinkSync as ds,writeFileSync as p$}from"fs";import{dirname as si,extname as m$,join as Ct,resolve as f$}from"path";import{execFileSync as NR}from"child_process";import{createHash as _R}from"crypto";import{copyFileSync as Yr,existsSync as je,mkdirSync as Kr,mkdtempSync as BR,readdirSync as zp,renameSync as Yp,rmSync as Jt,statSync as qR}from"fs";import{basename as Jr,dirname as B,extname as VR,join as oe,resolve as qp}from"path";import{platform as WR}from"os";import rS from"better-sqlite3";import{execFileSync as iS}from"child_process";import{existsSync as oS,readdirSync as sS}from"fs";import{extname as Mr,join as aS}from"path";function $t(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Fr({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Fr(e){let t=new Set((e.extensions??Us).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!oS(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=lr(e.projectRoot),r=cS(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new rS(e.dbPath);try{let o=dS(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
52
- VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let u=0;for(let m of d){if(o.has(m))continue;let g=pt(e.projectRoot,m,{inputKind:"auxiliary source file"}),f=s.run(uS(m),m,g);u+=Number(f.changes)}return u})(r),l={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${l.existing} already present).`),l}finally{i.close()}}function cS(e,t){let n=lS(e,t);if(n)return n;let r=[],i=o=>{let s=o?aS(e,o):e,a;try{a=sS(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Js.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(Mr(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function lS(e,t){try{return iS("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split(`
53
- `).filter(r=>r&&t.has(Mr(r).toLowerCase())).sort()}catch{return null}}function dS(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.add(a.relative_path)}return n}function uS(e){return Mr(e).toLowerCase()===".vue"?"vue":Mr(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as TS}from"crypto";import{existsSync as ES}from"fs";import{dirname as IS,join as vu}from"path";function yo(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function Nr(e,t,n){let r=e.changes.map(a=>a.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=yo(e),s=new Set(o.reasons);return r.some(a=>!i.has(a))&&s.add("changed-file-outside-project"),t===null?(s.add("dependency-graph-unavailable"),Su(r,i,s)):s.size>0?Su(r,i,s):{mode:"closure",changedFiles:r,affectedFiles:pS(r,t,i),reasons:[]}}function Su(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function pS(e,t,n){let r=new Map;for(let[s,a]of t)if(n.has(s))for(let c of a){if(!n.has(c))continue;let l=r.get(c)??new Set;l.add(s),r.set(c,l)}let i=new Set(e),o=[...e];for(let s=0;s<o.length;s+=1){let a=o[s];if(a!==void 0)for(let c of r.get(a)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}import{appendFileSync as mS,existsSync as fS,mkdirSync as gS,renameSync as hS,rmSync as yS,statSync as bS,truncateSync as SS}from"fs";import{basename as vS,dirname as xS}from"path";var Tn=".previous",RS=".rotation.lock",kS=2e3,bo=class extends Error{constructor(n,r){super(`Timed out after ${r}ms waiting for rotating JSONL lock: ${n}`);this.lockPath=n;this.timeoutMs=r;this.name="RotatingJsonlLockTimeoutError"}lockPath;timeoutMs;code="ROTATING_JSONL_LOCK_TIMEOUT"},So=class extends Error{constructor(n){super(`Rotating JSONL lock ownership changed before release: ${n}`);this.lockPath=n;this.name="RotatingJsonlLockReleaseError"}lockPath;code="ROTATING_JSONL_LOCK_RELEASE_FAILED"},wS=Object.freeze({monotonicNow:W,wait(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},tryAcquireLock(e,t){let n=Ot(e,{kind:"rotating-jsonl",detail:{target:vS(t)}});return n.kind==="acquired"?{kind:"acquired",lock:n.lock}:{kind:"contended"}},makeDirectory(e){gS(e,{recursive:!0})},exists:fS,readBytes(e){return on(e,{maxBytes:rn,inputKind:"rotating JSONL segment"})},size(e){return bS(e).size},truncate:SS,remove(e){yS(e,{force:!0})},rename:hS,append:mS});function _r(e,t,n){let r=n.runtime??wS,i=JSON.stringify(t);if(i===void 0)throw new TypeError("Rotating JSONL records must be JSON-serializable values.");let o=Buffer.from(`${i}
54
- `),s=Math.max(1,Math.floor(n.maxSegmentBytes),o.length);return $S(e,n.lockTimeoutMs,r,()=>{r.makeDirectory(xS(e));let a=CS(e,rn,r);n.onPhase?.("tail-repaired");let c=`${e}${n.previousSuffix??Tn}`,l=!1,d=!1;return r.exists(e)&&r.size(e)+o.length>s&&(r.exists(c)&&(r.remove(c),d=!0),n.onPhase?.("previous-pruned"),r.rename(e,c),l=!0,n.onPhase?.("current-rotated")),r.append(e,o),n.onPhase?.("record-appended"),{lineBytes:o.length,segmentLimitBytes:s,repairedTailBytes:a,rotated:l,prunedPrevious:d}})}function $S(e,t,n,r){let i=`${e}${RS}`,o=Math.max(0,t??kS),s=n.monotonicNow()+o,a;for(;;){let m=n.tryAcquireLock(i,e);if(m.kind==="acquired"){a=m.lock;break}let g=s-n.monotonicNow();if(g<=0)throw new bo(i,o);n.wait(Math.min(5,g))}let c=!1,l,d;try{d=r()}catch(m){c=!0,l=m}let u=!1;try{u=a.release()}catch(m){if(!c)throw m}if(c)throw l;if(!u)throw new So(i);return d}function CS(e,t,n){if(!n.exists(e))return 0;let r=PS(e,t,n);if(r.length===0||r[r.length-1]===10)return 0;let i=r.lastIndexOf(10),o=i<0?0:i+1;return n.truncate(e,o),r.length-o}function PS(e,t,n){let r=n.size(e);if(r>t)throw new Ti("rotating JSONL segment",e,"too-large",r,t);let i=n.readBytes(e),o=n.size(e);if(o!==r||i.byteLength!==r)throw new Ti("rotating JSONL segment",e,"changed-during-read",o,t);return i}var AS="<global-symbols>";function jS(e){let t=[];for(let n of e.all(`
55
- SELECT relative_path, language, position_encoding, text
56
- FROM documents
57
- `))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
58
- SELECT d.relative_path,
59
- c.chunk_index,
60
- c.start_line,
61
- c.end_line,
62
- hex(c.occurrences) AS occurrences_hex
63
- FROM chunks c
64
- JOIN documents d ON d.id = c.document_id
65
- `))t.push({relativePath:n.relative_path,kind:"chunk",values:[n.chunk_index,n.start_line,n.end_line,n.occurrences_hex]});for(let n of e.all(`
66
- SELECT d.relative_path,
67
- r.start_line,
68
- r.start_char,
69
- r.end_line,
70
- r.end_char,
71
- g.symbol,
72
- g.display_name,
73
- g.kind,
74
- g.documentation,
75
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
76
- g.enclosing_symbol,
77
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
78
- FROM defn_enclosing_ranges r
79
- JOIN documents d ON d.id = r.document_id
80
- JOIN global_symbols g ON g.id = r.symbol_id
81
- `))t.push({relativePath:n.relative_path,kind:"definition",values:vo(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
82
- SELECT d.relative_path,
83
- c.chunk_index,
84
- m.role,
85
- g.symbol,
86
- g.display_name,
87
- g.kind,
88
- g.documentation,
89
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
90
- g.enclosing_symbol,
91
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
92
- FROM mentions m
93
- JOIN chunks c ON c.id = m.chunk_id
94
- JOIN documents d ON d.id = c.document_id
95
- JOIN global_symbols g ON g.id = m.symbol_id
96
- `))t.push({relativePath:n.relative_path,kind:"mention",values:vo(n,[n.chunk_index,n.role])});for(let n of e.all(`
97
- SELECT g.symbol,
98
- g.display_name,
99
- g.kind,
100
- g.documentation,
101
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
102
- g.enclosing_symbol,
103
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
104
- FROM global_symbols g
105
- WHERE NOT EXISTS (
106
- SELECT 1 FROM defn_enclosing_ranges r WHERE r.symbol_id = g.id
107
- ) AND NOT EXISTS (
108
- SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
109
- )
110
- `))t.push({relativePath:AS,kind:"global-symbol",values:vo(n)});return LS(t)}function LS(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),o=t.get(r.relativePath)??[];o.push(i),t.set(r.relativePath,o)}let n=new Map;for(let[r,i]of[...t].sort(([o],[s])=>o.localeCompare(s))){let o=TS("sha256");for(let s of i.sort())o.update(String(Buffer.byteLength(s))),o.update(":"),o.update(s),o.update(`
111
- `);n.set(r,o.digest("hex"))}return n}function DS(e,t){let n=[],r=[],i=[],o=[],s=new Set([...e.keys(),...t.keys()]);for(let a of[...s].sort()){let c=e.get(a),l=t.get(a);c===void 0?n.push(a):l===void 0?i.push(a):c!==l?r.push(a):o.push(a)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function xo(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),s=e.affectedFiles.filter(c=>!i.has(c)).sort(),a=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:a/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:s}}function Ro(e,t=_S){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),s=(l,d)=>{let u=r();return Eu(e.refreshResult,l,n?u:i(),Math.max(0,u-o),d)};if(!t.databaseExists(e.previousDbPath))return s("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return s("candidate-index-unavailable");let a=null,c=null;try{a=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let l=[...new Set([...t.indexedPaths(a),...t.indexedPaths(c)])].sort(),d=Gn(e.previousSnapshot,e.currentSnapshot),u=new Set(l),m=d.changes.length>0&&!yo(d).fullProject&&d.changes.every(S=>u.has(S.path)),g=Nr(d,m?t.dependencyGraph(a):new Map,l),f=DS(t.factDigests(a),t.factDigests(c)),h=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?h:i()).toISOString(),durationMs:Math.max(0,h-o),manifest:d,plan:g,comparison:f,evaluation:xo(g,f,l.length)}}catch(l){return s("oracle-error",l instanceof Error?l.message:String(l))}finally{xu(a),xu(c)}}function wu(e,t,n,r=Date.now()){return Eu(e,t,r,0,n)}function $u(e){let t=IS(e);return{latestPath:vu(t,"affected-shadow-latest.json"),historyPath:vu(t,"affected-shadow.jsonl")}}function Cu(e,t=n=>Ns(n,"affected-shadow source file")){let n=$u(e),r;try{r=JSON.parse(t(n.latestPath))}catch(y){let v=HS(y),w=v?"telemetry-missing":WS(y);return at(n,w,v?void 0:y instanceof Error?y.message:String(y))}if(K(r)&&typeof r.version=="number"&&r.version!==1)return at(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!qS(r))return at(n,"telemetry-malformed");if(r.status==="unavailable")return VS(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:at(n,"telemetry-malformed");if(r.status!=="evaluated")return at(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!K(r.manifest)||!K(i)||!K(o)||!K(s))return at(n,"telemetry-malformed");let a=i.mode,c=Z(i.affectedFiles),l=Z(i.reasons),d=Z(o.changedFiles),u=Z(s.predictedFiles),m=Z(s.actualFiles),g=Z(s.missingFiles),f=s.recall,h=s.affectedRatio;if(a!=="none"&&a!=="closure"&&a!=="full-project"||c===null||l===null||d===null||u===null||m===null||g===null||typeof s.passed!="boolean"||!Ru(f)||!Ru(h))return at(n,"telemetry-malformed");let S=m.length===0?1:(m.length-g.length)/m.length;return!ku(c,u)||!ku(d,m)||s.passed!==(g.length===0)||Math.abs(f-S)>Number.EPSILON||g.some(y=>!m.includes(y)||u.includes(y))?at(n,"telemetry-malformed"):{state:s.passed?"passing":"failing",...n,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,mode:a,recall:f,affectedRatio:h,predictedFiles:u,actualFiles:m,missingFiles:g,fallbackReasons:l}}function Pu(e){if(e.state==="unavailable")return`unavailable (${e.reason})`;let t=e.missingFiles.length>0?`, ${e.missingFiles.length} missed`:"",n=e.fallbackReasons.length>0?`; fallback: ${e.fallbackReasons.join(", ")}`:"";return`${e.state}, ${(e.recall*100).toFixed(1)}% recall, ${e.predictedFiles.length} predicted / ${e.actualFiles.length} changed, ${(e.affectedRatio*100).toFixed(1)}% of project${t}${n}`}function Tu(e,t,n=BS){let r=$u(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var OS=8*1024*1024,MS=Tn;function FS(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function NS(e,t,n=OS){_r(e,FS(t),{maxSegmentBytes:n,previousSuffix:MS})}function vo(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var _S={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:W,databaseExists:e=>ES(e),openDatabase:(e,t,n)=>new gt({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Un(e),dependencyGraph:e=>Yn(e),factDigests:e=>jS(e)},BS={appendHistory:NS,writeLatest:(e,t)=>la(e,t,{spacing:2,trailingNewline:!0})};function Eu(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(n).toISOString(),durationMs:r,reason:t,...i?{error:i}:{}}}function xu(e){try{e?.close()}catch{}}function qS(e){return K(e)&&e.version===1&&typeof e.recordedAt=="string"&&(e.refreshResult==="rebuilt"||e.refreshResult==="reused")&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0}function VS(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function Ru(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function ku(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function at(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function WS(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function HS(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as GS}from"crypto";import{copyFileSync as US,existsSync as Iu,rmSync as Au}from"fs";import{resolve as JS}from"path";import Du from"better-sqlite3";var KS={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},zS={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Ou(e){let t=W(),n=YS(e.affectedFiles);if(XS(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Au(e.candidateDbPath,{force:!0}),!Iu(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Iu(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");ju(e.previousDbPath,"previous SQLite generation",!1),ju(e.miniDbPath,"incremental SQLite mini database"),US(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new Du(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),ko(r,"main","candidate SQLite generation"),ko(r,"incremental","incremental SQLite mini database"),QS(r,n),ZS(r,n.length);let i=wo(r,"main",!0),o=ct(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{ev(r),tv(r),nv(r),e.onStage?.("after-delete"),rv(r),e.onStage?.("after-symbol-reconciliation"),iv(r),e.onStage?.("after-insert"),ov(r),sv(r,n.length,o),e.onStage?.("before-commit")}).immediate(),Mu(r,"main","candidate SQLite generation");let c=[...av(r)].filter(([l,d])=>i.get(l)!==d).map(([l])=>l).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:W()-t}}catch(i){try{r?.close()}finally{Au(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function YS(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function XS(e,t,n){let r=[e,t,n].map(i=>JS(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function ju(e,t,n=!0){let r=new Du(e,{readonly:!0,fileMustExist:!0});try{ko(r,"main",t),n&&Mu(r,"main",t)}finally{r.close()}}function ko(e,t,n){for(let[r,i]of Object.entries(KS)){let s=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:a,type:c,notnull:l,pk:d})=>({name:a,type:c.toUpperCase(),notnull:l,pk:d}));if(JSON.stringify(s)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(zS)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),s=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(a=>a.name);if(o?.tbl_name!==i.table||JSON.stringify(s)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}Lu(e,t,"documents",["relative_path"],n),Lu(e,t,"global_symbols",["symbol"],n)}function Lu(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(a=>{if(a.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${a.name}')`).all().map(l=>l.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function Mu(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function QS(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function ZS(e,t){let n=ct(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=ct(e,`SELECT COUNT(*) AS value
112
- FROM main.documents d
113
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
114
- FROM temp.incremental_affected_paths p
115
- LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
116
- WHERE d.id IS NULL
117
- LIMIT 1`).pluck().get(),o=e.prepare(`SELECT d.relative_path
118
- FROM incremental.documents d
119
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
120
- WHERE p.relative_path IS NULL
121
- LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function ev(e){e.exec(`
122
- CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
123
- INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
124
- SELECT g.symbol
125
- FROM main.defn_enclosing_ranges r
126
- JOIN main.documents d ON d.id = r.document_id
127
- JOIN main.global_symbols g ON g.id = r.symbol_id
128
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path;
129
- INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
130
- SELECT g.symbol
131
- FROM main.mentions m
132
- JOIN main.chunks c ON c.id = m.chunk_id
133
- JOIN main.documents d ON d.id = c.document_id
134
- JOIN main.global_symbols g ON g.id = m.symbol_id
135
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
136
- WHERE m.role = 1;
137
-
138
- CREATE TEMP TABLE incremental_new_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
139
- INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
140
- SELECT g.symbol
141
- FROM incremental.defn_enclosing_ranges r
142
- JOIN incremental.global_symbols g ON g.id = r.symbol_id;
143
- INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
144
- SELECT g.symbol
145
- FROM incremental.mentions m
146
- JOIN incremental.global_symbols g ON g.id = m.symbol_id
147
- WHERE m.role = 1;
148
- `)}function tv(e){let t=e.prepare(`WITH changed_symbols AS (
149
- SELECT symbol FROM temp.incremental_old_defined_symbols
150
- UNION
151
- SELECT symbol FROM temp.incremental_new_defined_symbols
152
- ), unaffected_definitions AS (
153
- SELECT g.symbol
154
- FROM main.defn_enclosing_ranges r
155
- JOIN main.documents d ON d.id = r.document_id
156
- JOIN main.global_symbols g ON g.id = r.symbol_id
157
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
158
- WHERE p.relative_path IS NULL
159
- UNION
160
- SELECT g.symbol
161
- FROM main.mentions m
162
- JOIN main.chunks c ON c.id = m.chunk_id
163
- JOIN main.documents d ON d.id = c.document_id
164
- JOIN main.global_symbols g ON g.id = m.symbol_id
165
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
166
- WHERE m.role = 1 AND p.relative_path IS NULL
167
- )
168
- SELECT u.symbol
169
- FROM unaffected_definitions u
170
- JOIN changed_symbols c ON c.symbol = u.symbol
171
- LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function nv(e){e.exec(`
172
- DELETE FROM main.mentions
173
- WHERE chunk_id IN (
174
- SELECT c.id
175
- FROM main.chunks c
176
- JOIN main.documents d ON d.id = c.document_id
177
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
178
- );
179
- DELETE FROM main.chunks
180
- WHERE document_id IN (
181
- SELECT d.id
182
- FROM main.documents d
183
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
184
- );
185
- DELETE FROM main.defn_enclosing_ranges
186
- WHERE document_id IN (
187
- SELECT d.id
188
- FROM main.documents d
189
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
190
- );
191
- DELETE FROM main.documents
192
- WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
193
- `)}function rv(e){e.exec(`
194
- UPDATE main.global_symbols
195
- SET display_name = NULL,
196
- kind = NULL,
197
- documentation = NULL,
198
- signature = NULL,
199
- enclosing_symbol = NULL,
200
- relationships = NULL
201
- WHERE symbol IN (SELECT symbol FROM temp.incremental_old_defined_symbols);
202
-
203
- INSERT OR IGNORE INTO main.global_symbols(
204
- symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
205
- )
206
- SELECT symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
207
- FROM incremental.global_symbols;
208
-
209
- UPDATE main.global_symbols
210
- SET display_name = (
211
- SELECT source.display_name FROM incremental.global_symbols source
212
- WHERE source.symbol = main.global_symbols.symbol
213
- ),
214
- kind = (
215
- SELECT source.kind FROM incremental.global_symbols source
216
- WHERE source.symbol = main.global_symbols.symbol
217
- ),
218
- documentation = (
219
- SELECT source.documentation FROM incremental.global_symbols source
220
- WHERE source.symbol = main.global_symbols.symbol
221
- ),
222
- signature = (
223
- SELECT source.signature FROM incremental.global_symbols source
224
- WHERE source.symbol = main.global_symbols.symbol
225
- ),
226
- enclosing_symbol = (
227
- SELECT source.enclosing_symbol FROM incremental.global_symbols source
228
- WHERE source.symbol = main.global_symbols.symbol
229
- ),
230
- relationships = (
231
- SELECT source.relationships FROM incremental.global_symbols source
232
- WHERE source.symbol = main.global_symbols.symbol
233
- )
234
- WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
235
- `)}function iv(e){let t=ct(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=ct(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=ct(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
236
- SELECT id + ?, language, relative_path, position_encoding, text
237
- FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
238
- SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
239
- FROM incremental.chunks`).run(n,t),e.prepare(`INSERT INTO main.mentions(chunk_id, symbol_id, role)
240
- SELECT m.chunk_id + ?, target.id, m.role
241
- FROM incremental.mentions m
242
- JOIN incremental.global_symbols source ON source.id = m.symbol_id
243
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(n),e.prepare(`INSERT INTO main.defn_enclosing_ranges(
244
- id, document_id, symbol_id, start_line, start_char, end_line, end_char
245
- )
246
- SELECT r.id + ?, r.document_id + ?, target.id,
247
- r.start_line, r.start_char, r.end_line, r.end_char
248
- FROM incremental.defn_enclosing_ranges r
249
- JOIN incremental.global_symbols source ON source.id = r.symbol_id
250
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function ov(e){e.exec(`
251
- DELETE FROM main.global_symbols
252
- WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
253
- AND NOT EXISTS (
254
- SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
255
- );
256
- `)}function sv(e,t,n){let r=ct(e,"SELECT COUNT(*) AS value FROM main.documents"),i=ct(e,`SELECT COUNT(*) AS value
257
- FROM main.documents d
258
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),s=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||s!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function av(e){let t=wo(e,"main",!0),n=wo(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function wo(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
259
- FROM ${t}.documents d
260
- ${r}
261
- ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
262
- FROM ${t}.chunks c
263
- JOIN ${t}.documents d ON d.id = c.document_id
264
- ${r}
265
- ORDER BY d.relative_path, c.chunk_index, c.start_line, c.end_line, c.id`).all(),s=e.prepare(`SELECT d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char,
266
- g.symbol, g.display_name, g.kind, g.documentation,
267
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature,
268
- g.enclosing_symbol,
269
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships
270
- FROM ${t}.defn_enclosing_ranges r
271
- JOIN ${t}.documents d ON d.id = r.document_id
272
- JOIN ${t}.global_symbols g ON g.id = r.symbol_id
273
- ${r}
274
- ORDER BY d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char, g.symbol`).all(),a=e.prepare(`SELECT d.relative_path, c.chunk_index, m.role, g.symbol
275
- FROM ${t}.mentions m
276
- JOIN ${t}.chunks c ON c.id = m.chunk_id
277
- JOIN ${t}.documents d ON d.id = c.document_id
278
- JOIN ${t}.global_symbols g ON g.id = m.symbol_id
279
- ${r}
280
- ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,u]of Object.entries({documents:i,chunks:o,definitions:s,mentions:a}))for(let m of u){let g=JSON.stringify([d,m]),f=c.get(m.relative_path)??[];f.push(g),c.set(m.relative_path,f)}let l=new Map;for(let[d,u]of[...c].sort(([m],[g])=>m.localeCompare(g))){let m=GS("sha256");for(let g of u.sort())m.update(g).update(`
281
- `);l.set(d,m.digest("hex"))}return l}function ct(e,t){return e.prepare(t).get().value}import{writeFileSync as cv}from"fs";function Gt(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}async function Nu(e){let t=e.readFingerprint(),n=lv(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return dv(e.cachePath,e.readFingerprint(),r),r}function lv(e,t){try{let n=JSON.parse(U(e,{maxBytes:xe,inputKind:"post-index augmentation cache"}));return Fu(n.fingerprint)===Fu(t)?{result:n.result}:null}catch{return null}}function dv(e,t,n){cv(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
282
- `)}function Fu(e){return JSON.stringify(e)}import{statSync as uv}from"fs";import{dirname as pv,join as mv}from"path";var $o="reindex-activity.jsonl",fv=Tn,gv=1024*1024,rj=1440*60*1e3;function Co(e){return mv(pv(e),$o)}function hv(e){if(e.reused)return 0;let t=_u(e.indexPath)+_u(e.dbPath);for(let n of e.shards??[])!n.reused&&n.outputBytes!==null&&(t+=n.outputBytes);return t}function Po(e,t){let n=t.lastRefresh;n&&To(Co(e),{version:1,event:"run",recordedAt:n.completedAt,trigger:n.trigger,result:n.result,durationMs:n.durationMs,estimatedLogicalOutputBytes:hv(t)})}function Bu(e,t){To(Co(e),{version:1,event:"run",recordedAt:t.completedAt,trigger:t.trigger,result:"failed",durationMs:t.durationMs,estimatedLogicalOutputBytes:0})}function qu(e,t,n=new Date){To(Co(e),{version:1,event:"suppressed",recordedAt:n.toISOString(),trigger:t,reason:"completed-index-is-fresh"})}function yv(e,t,n=gv,r){_r(e,t,{maxSegmentBytes:n,previousSuffix:fv,...r?{runtime:r}:{}})}function To(e,t){try{yv(e,t)}catch{}}function _u(e){try{return uv(e).size}catch{return 0}}import{createHash as bv}from"crypto";import{existsSync as Eo,readdirSync as Sv}from"fs";import{dirname as Io,join as Br,relative as vv,resolve as Ao,sep as Vu}from"path";function Wu(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=Ju(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Hu(e,t){let n=new Map;for(let i of e){let o=t[i]?.packageName;o&&n.set(o,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let o=t[i],s=r.get(i);if(!o||o.parseFailed){for(let a of e)a!==i&&s.add(a);continue}for(let a of o.dependencyNames){let c=n.get(a);c&&c!==i&&s.add(c)}for(let a of[...o.pathsTargets,...o.referencesPaths]){let c=Ju(a,e);c&&c!==i&&s.add(c)}}return xv(e,r)}function Gu(e,t,n){let r={};for(let i of e){let o=new Map;for(let s of t.files[i]??[])o.set(s.path,s);for(let s of n[i]??[])for(let a of t.files[s]??[])o.set(a.path,a);for(let s of t.shared)o.set(s.path,s);r[i]={files:[...o.values()].sort((s,a)=>s.path.localeCompare(a.path))}}return r}function jo(e){if(e===".")return"root";let t=bv("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Uu(e,t){let n=Ao(e),r={};for(let i of t)r[i]=Rv(n,i);return r}function Ju(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function xv(e,t){let n={};for(let r of e){let i=new Set,o=[...t.get(r)??[]];for(;o.length>0;){let s=o.pop();if(!(s===r||i.has(s))){i.add(s);for(let a of t.get(s)??[])a!==r&&!i.has(a)&&o.push(a)}}n[r]=[...i].sort((s,a)=>s.localeCompare(a))}return n}function Rv(e,t){let n=t==="."?e:Br(e,t),r=kv(n),i=wv(n),o=i?$v(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:o.pathsTargets,referencesPaths:o.referencesPaths,parseFailed:r.failed||o.failed}}function kv(e){let t=Br(e,"package.json");if(!Eo(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Lo(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let o of["dependencies","devDependencies","peerDependencies"]){let s=n.value[o];if(s&&typeof s=="object"&&!Array.isArray(s))for(let a of Object.keys(s))i.add(a)}return{name:r,dependencyNames:[...i],failed:!1}}function wv(e){let t=Br(e,"tsconfig.json");if(Eo(t))return t;let n;try{n=Sv(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Br(e,n[0]):void 0}function $v(e,t){let n=Lo(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Cv(n.value,e,t),i=Ku(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Cv(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Io(t),o=new Set;for(let s of r){if(!s||typeof s!="object")continue;let a=s.path;if(typeof a!="string"||a.trim()==="")continue;let c=zu(a,i,n);c&&o.add(c)}return[...o]}function Ku(e,t,n,r){let i=Pv(t);if(i)return{pathsTargets:Tv(i,Io(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Ev(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=Lo(o);return s.ok?Ku(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function Pv(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Tv(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let o of i){if(typeof o!="string")continue;let s=zu(o,t,n);s&&r.add(s)}return[...r]}function Ev(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=Ao(Io(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Vu).includes("node_modules")&&de(n,i)&&Eo(i))return i}function zu(e,t,n){let r=e.replace(/\/?\*+$/,""),i=Ao(t,r===""?".":r);if(!de(n,i))return;let s=vv(n,i).split(Vu).join("/");return s===""?".":s}function Iv(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){if(t+=o,o==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}o==='"'&&(r=!1),n+=1;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
283
- `;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function Lo(e){try{let t=U(e,{maxBytes:xe,inputKind:"TypeScript project manifest"}),n=JSON.parse(Iv(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as Av,readdirSync as jv,statSync as Lv}from"fs";import ce from"path";var Dv=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function En(e,t=[]){let n=ce.resolve(e),r=t.flatMap(c=>Mv(n,c));if(r.length>0)return Yu(n,Xu(r));let i=Ov(n),o=Xu(i),s=Nv(n,o)?[n,...o]:o,a=s.length>0?s:[n];return Yu(n,a)}function Yu(e,t){return[...new Set(t.map(n=>Bv(e,n)))].sort((n,r)=>n.localeCompare(r))}function Ov(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=jv(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=ce.join(r,o.name);if(o.isDirectory()){!Dv.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&Fv(s)&&t.push(ce.dirname(s))}}return t}function Mv(e,t){let n=t.trim();if(!n)return[];let r=ce.resolve(e,n);if(!de(e,r))return[];try{let i=Lv(r);if(i.isDirectory())return[r];if(i.isFile()&&Qu(ce.basename(r)))return[ce.dirname(r)]}catch{return[]}return[]}function Fv(e){if(!Qu(ce.basename(e)))return!1;let t=Zu(e);return t?ce.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function Qu(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function Xu(e){let t=[...new Set(e.map(n=>ce.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&qv(n,r)))}function Nv(e,t){if(t.length===0||t.some(r=>ce.resolve(r)===e))return!1;let n=ce.join(e,"tsconfig.json");return Av(n)&&_v(n)}function _v(e){let n=Zu(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!ce.extname(r))):!1}function Zu(e){try{let t=JSON.parse(V(e,"TypeScript project config"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Bv(e,t){let n=ce.relative(e,t);return n?n.split(ce.sep).join("/"):"."}function qv(e,t){let n=ce.relative(e,t);return!!n&&!n.startsWith("..")&&!ce.isAbsolute(n)}import{createHash as sx}from"crypto";import{existsSync as Oo,statSync as ax,writeFileSync as Mo}from"fs";import{join as cx}from"path";import{createRequire as Vv}from"module";import{dirname as Wv,isAbsolute as bj,relative as Sj,resolve as vj,sep as xj}from"path";var ep=Vv(import.meta.url),Hv=1,tp="0.4.0";function Do(){let e=Gv();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Gv(){try{let e=ep.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(V(e,"scip-typescript package manifest"));if(t.version!==tp)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${tp}`};let n=Wv(e),r=ep.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(V(r,"TypeScript package manifest"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:Uv(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Uv(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Hv}`}import{createHash as Jv}from"crypto";import{dirname as Kv,join as np}from"path";var qr=3;var zv="typescript-index";function rp(e){let t=np(e,zv),n=ua(t);return{...n,requestDir:n.legacyRequestDir}}function ip(e){try{let t=Fs(Et(V(np(Kv(e),"meta.json"),"reindex metadata")));return t?Jv("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as Yv}from"crypto";import{existsSync as Xv}from"fs";var Qv=12e4,Zv=5,Vr=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;constructor(t,n={}){this.projectRoot=ha(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??ix(),this.runtime=n.runtime??ox,this.mailboxLimits=n.mailboxLimits??{}}request(t){let n=ir(this.cacheDir),r=rp(this.cacheDir),i=Di(n.statePath);if(!op(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.now(),s=o+this.timeoutMs,a=(this.runtime.monotonicNow??W)()+this.timeoutMs,c=ji("typescript-index-v3",{baseGeneration:this.baseGeneration,request:t}),l=Li(c),d=pa(r,{mailboxVersion:Ai,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:s,protocolVersion:qr,id:l,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??W)()<=a;){if(Xv(d.responsePath))return ex(U(d.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),l,c,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=Di(n.statePath);if(!op(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Zv)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}};function op(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===qr&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&un(e.processIdentity,r))}function ex(e,t,n,r,i,o){let s=JSON.parse(e);if(s.protocolVersion!==qr||s.id!==t||s.operationKey!==n||s.ok===!0&&s.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(s.ok!==!0)throw new Error(typeof s.error=="string"?s.error:"TypeScript index service request failed.");let a=tx(s.response,i),c=[...new Set(o)].sort(),l=a.fragments.map(d=>d.relativePath).sort();if(JSON.stringify(l)!==JSON.stringify(c))throw new Error("TypeScript index service omitted or added an affected document.");return a}function tx(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(nx)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:rx(o.bytesBase64);return{relativePath:o.relativePath,bytes:s,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function nx(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function rx(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function ix(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Qv}var ox={now:Date.now,monotonicNow:W,randomId:Yv,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:jt,readProcessIdentity:Lt};function lx(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=Gn(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(l=>l.kind!=="modified"||l.inputKind!=="source"||!mn(l.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Nr(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=dx([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=sp(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=sp(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=cp(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=cp(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:ap(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:ap(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:a,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function dx(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function lp(e){let t=W();try{if(!Oo(e.previousDbPath)||!Oo(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Do();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new gt({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),s,a;try{s=Un(o,{includeIgnored:!1}).filter(mn).sort(),a=Yn(o)}finally{o.close()}let c=performance.now()-n,l=lx({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?En(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:a,producerIdentity:r.producerIdentity,rootTsconfigExists:Oo(cx(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let d=ip(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let m=new Vr({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:l.tsconfigPath,projectArgument:l.projectArgument,projectIdentity:l.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles}),g=performance.now()-n,f=ax(e.previousShardPath).size>=bl;n=performance.now();let h=f?null:on(e.previousShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:Pi}),S=f?{completeIndexBytes:null,affectedIndexBytes:fl(m.fragments)}:yl({packageVersion:r.packageVersion,baseIndexBytes:h,fragments:m.fragments}),y=performance.now()-n;n=performance.now(),f?Sl({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:m.fragments}):(gl({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:h,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),hl({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.nextFragmentGeneration,fragments:m.fragments,documentIdentities:l.nextDocumentIdentities}));let v=performance.now()-n;n=performance.now(),S.completeIndexBytes&&Mo(e.candidateShardPath,S.completeIndexBytes),Mo(e.candidateAffectedScipPath,S.affectedIndexBytes);let w=performance.now()-n,R={scipPath:f?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!f,durationMs:W()-t,cold:m.cold,changedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:l.previousFragmentGeneration,nextFragmentGeneration:l.nextFragmentGeneration,manifest:l.manifest,plan:l.plan,projectFileCount:s.length,referenceFragmentsByFile:new Map(m.fragments.map(j=>[j.relativePath,j.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:g,serviceMs:m.durationMs,assemblyMs:y,fragmentStoreMs:v,writeMs:w}};return e.onStatus(`Incremental TypeScript index emitted ${R.affectedFiles.length} affected document(s) in ${(R.durationMs/1e3).toFixed(3)}s (${R.cold?"cold":"warm"} service; ${f?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${g.toFixed(0)}ms, assembly ${y.toFixed(0)}ms, fragments ${v.toFixed(0)}ms, write ${w.toFixed(0)}ms).`),R}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function dp(e){let t=Do();if(!t.available)throw new Error(t.reason);let n=vl({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:on(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:Pi}),packageVersion:t.packageVersion});Mo(e.candidateShardPath,n)}function sp(e,t,n){let r=e.files.filter(i=>Ds(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return Fo(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function ap(e,t){return Fo(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function cp(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),s=Ra({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),a=new Map;for(let c of i){let l=s.identityFor(c,"typescript-scip-document-v1");if(l.key){a.set(c,l.key);continue}if(o.has(c))return null;a.set(c,Fo(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function Fo(e){return sx("sha256").update(e).digest("hex")}import{existsSync as Wr,renameSync as _o,rmSync as Bo,statSync as ux}from"fs";import{cpus as px}from"os";import{join as pp}from"path";function mx(e,t,n){if(!e.defaultOutputPath)return;let r=pp(t,e.defaultOutputPath);n!==r&&Wr(r)&&_o(r,n)}function fx(e,t,n){if(!e.defaultOutputPath)return null;let r=pp(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Bo(i,{force:!0}),Wr(r)?(_o(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function gx(e){e&&(Bo(e.defaultOutputPath,{force:!0}),e.backupPath&&Wr(e.backupPath)&&_o(e.backupPath,e.defaultOutputPath))}function hx(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,px().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function mp(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=hx(o.length,r),c=await Sx(o,a,l=>No(l,t,n));if(a>1){let l=new Map;for(let d of c.filter(u=>u.result.skipped&&u.retryable)){let u=o.find(m=>m.id===d.result.id);u&&(n(`Retrying ${u.label} indexer serially after parallel failure...`),l.set(u.id,(await No(u,t,n)).result))}s.push(...c.map(({result:d})=>l.get(d.id)??d))}else s.push(...c.map(({result:l})=>l));for(let l of i)s.push((await No(l,t,n)).result);return s.sort((l,d)=>e.findIndex(u=>u.id===l.id)-e.findIndex(u=>u.id===d.id))}async function No(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Bo(e.scipPath,{force:!0});let r=fx(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=W();try{e.trustedProjectTool&&ia(t,e.trustedProjectTool);let a=Zn(e.binary,e.args),c=await mr({command:a.binary,args:a.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:yx(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024});if(c.status!==0){let l=c.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${c.status}${l?`:
284
- ${l}`:""}`)}mx(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
285
- `)[0]}`,d=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:W()-o,command:i,skipped:{language:e.language,reason:d}},retryable:bx(a)}}finally{gx(r)}if(!Wr(e.scipPath)){let a=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?a:`${e.label}: ${a}`;return n(`Skipping ${e.label}: ${a}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:W()-o,command:i,skipped:{language:e.language,reason:c}},retryable:!1}}let s;try{s=ux(e.scipPath).size}catch{s=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:W()-o,command:i,outputBytes:s},retryable:!1}}function yx(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):El.indexer}function bx(e){return e instanceof pr?e.kind==="spawn"&&up(e.cause):up(e)}function up(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}async function Sx(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),s=Array.from({length:o},async()=>{for(;i<e.length;){let a=i++;r[a]=await n(e[a])}});return await Promise.all(s),r}import{execFileSync as gp}from"child_process";import{homedir as fp,platform as vx}from"os";import{delimiter as xx,join as Hr}from"path";function Gr(e,t){let n=e.installMethods,r=tr(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n){if(!i.identity||!i.destination){t(`Refusing ${i.label} installation for ${r}: the installer descriptor lacks an immutable identity or destination.`);continue}if(!It(i.prerequisite))continue;let o=Rx(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{gp(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:vx()==="win32"});let s=dn(e);if(s){let a=s===e.indexerBinary?"":` (using ${s})`;return t(`Successfully installed ${i.identity} via ${i.label}${a}; resolved executable: ${s}.`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(s){let a=s instanceof Error?s.message:String(s);t(`${i.label} install failed: ${a}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function Rx(e){if(e.binary==="npm")return qo("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=qo("go",["env","GOBIN"]);if(t)return t;let n=qo("go",["env","GOPATH"]);if(n)return Hr(n.split(xx)[0],"bin")}return e.binary==="dotnet"?Hr(process.env.DOTNET_CLI_HOME??fp(),".dotnet","tools"):e.binary==="dart"?Hr(process.env.PUB_CACHE??Hr(fp(),".pub-cache"),"bin"):e.destination}function qo(e,t){try{return gp(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import gR from"better-sqlite3";import{existsSync as hR}from"fs";import{dirname as yR,join as bR,resolve as SR}from"path";import{randomUUID as wx}from"crypto";import{mkdtempSync as $x,rmSync as Cx,statSync as yp}from"fs";import{tmpdir as Px}from"os";import{join as bp}from"path";import{Worker as Tx}from"worker_threads";function kx(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Ut(){return{skippedReferences:0,skippedReferenceReasons:kx(),skippedReferenceSamples:[]}}function Ur(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}var Ex=3e5,Sp=64*1024*1024,Ix={createResultDirectory:()=>$x(bp(Px(),"scip-query-vue-workers-")),spawn:(e,t)=>new Tx(e,{workerData:t}),resultSize:e=>yp(e).size,readResult:e=>U(e,{maxBytes:Sp,inputKind:"Vue worker result"}),removeResultDirectory:e=>Cx(e,{recursive:!0,force:!0})};function vp(e){return e.length>=8&&Rp(e.length)>1}async function xp(e,t=Ix){let n=Rp(e.vueFiles.length),r=Wx(e.vueFiles),i=Gx(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),s=e.timeoutMs??qx(),a=e.maxResultBytes??Vx();hp("timeoutMs",s),hp("maxResultBytes",a);let c=wx(),l=t.createResultDirectory(),d=[],u,m,g;try{for(let h=0;h<i.length;h++){let S=h,y=i[h]??[],v=y.map(j=>j.taskId),w=bp(l,`${S}.json`),R=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:y,resultPath:w,runId:c,workerId:S,taskIds:v});d.push({workerId:S,taskIds:v,resultPath:w,handle:R,completion:Ax(R,S)})}await jx(d,s);let f=d.sort((h,S)=>h.workerId-S.workerId).map(h=>Dx(h,c,a,t));g={occurrences:f.flatMap(h=>h.occurrences),...Ut()};for(let h of f)Ur(g,h)}catch(f){u=f}finally{let f=await Lx(d);if(f.length===0)try{t.removeResultDirectory(l)}catch(h){f.push(h)}if(f.length>0){let h=u===void 0?f:[u,...f];m=new AggregateError(h,`Vue worker cleanup failed: ${Bx(h[0])}`)}}if(m)throw m;if(u!==void 0)throw u;if(!g)throw new Error("Vue workers completed without producing a merged result.");return g}function Ax(e,t){return new Promise((n,r)=>{let i=!1,o=c=>{i||(i=!0,e.off("error",s),e.off("exit",a),c?r(c):n())},s=c=>{o(new Error(`Vue reference worker ${t} failed: ${c.message}`,{cause:c}))},a=c=>{o(c===0?void 0:new Error(`Vue reference worker ${t} exited with code ${c}`))};e.once("error",s),e.once("exit",a)})}async function jx(e,t){let n;try{await Promise.race([Promise.all(e.map(r=>r.completion)),new Promise((r,i)=>{n=setTimeout(()=>i(new Error(`Vue reference workers timed out after ${(t/1e3).toFixed(3)}s`)),t),n.unref()})])}finally{n&&clearTimeout(n)}}async function Lx(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function Dx(e,t,n,r){let i=r.resultSize(e.resultPath);if(!Number.isSafeInteger(i)||i<0||i>n)throw new Error(`Vue reference worker ${e.workerId} result is ${i} bytes; limit is ${n} bytes`);let o;try{o=JSON.parse(r.readResult(e.resultPath))}catch(s){throw new Error(`Vue reference worker ${e.workerId} produced invalid JSON`,{cause:s})}if(!In(o)||o.version!==1||o.runId!==t||o.workerId!==e.workerId)throw new Error(`Vue reference worker ${e.workerId} result identity does not match its assignment`);if(!_x(o.taskIds,e.taskIds))throw new Error(`Vue reference worker ${e.workerId} result task identities do not match its assignment`);if(o.ok===!1)throw typeof o.error!="string"?new Error(`Vue reference worker ${e.workerId} failure payload is malformed`):new Error(`Vue reference worker ${e.workerId} failed: ${o.error}`);if(o.ok!==!0||!Ox(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function Ox(e){if(!In(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(Mx)||!Xe(e.skippedReferences)||!In(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!Xe(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(Fx)}function Mx(e){return In(e)&&typeof e.sourceFile=="string"&&Xe(e.sourceLine)&&Xe(e.sourceStartChar)&&Xe(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&Xe(e.symbolId)}function Fx(e){return In(e)&&typeof e.sourceFile=="string"&&Xe(e.sourceLine)&&Xe(e.sourceStartChar)&&Xe(e.sourceEndChar)&&typeof e.token=="string"&&Nx(e.reason)}function Nx(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function Xe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function In(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _x(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function hp(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function Bx(e){return e instanceof Error?e.message:String(e)}function Rp(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function qx(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:Ex}function Vx(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:Sp}function Wx(e){let t=Hx(),n=[];for(let r of e){let i=kp(r),o=Math.max(1,Math.ceil(i/t));for(let s=0;s<o;s++)n.push({taskId:`${n.length}:${r}:${s}`,fileName:r,startOffset:Math.floor(i*s/o),endOffset:s===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(s+1)/o),countFileSkip:s===0})}return n}function Hx(){return Number.POSITIVE_INFINITY}function Gx(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Ux(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((s,a)=>a.weight<s.weight?a:s);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function Ux(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,kp(e.fileName)-e.startOffset)}function kp(e){try{return yp(e).size}catch{return 1}}import{createRequire as Jx}from"module";import{existsSync as Kx}from"fs";import{dirname as wp,extname as zx,join as $p,relative as Yx,resolve as Xx}from"path";import{pathToFileURL as Qx}from"url";function Zx(e){e.transaction(()=>{e.prepare(`
286
- DELETE FROM mentions
287
- WHERE chunk_id IN (
288
- SELECT c.id
289
- FROM chunks c
290
- JOIN documents d ON d.id = c.document_id
291
- WHERE d.language = 'vue' OR d.relative_path LIKE '%.vue'
292
- )
293
- `).run(),e.prepare(`
294
- DELETE FROM chunks
295
- WHERE document_id IN (
296
- SELECT id
297
- FROM documents
298
- WHERE language = 'vue' OR relative_path LIKE '%.vue'
299
- )
300
- `).run()})()}function Cp(e,t){return e.prepare(`
301
- SELECT relative_path AS relativePath
302
- FROM documents
303
- WHERE language = 'vue' OR relative_path LIKE '%.vue'
304
- ORDER BY relative_path
305
- `).all().map(r=>Xx(t,r.relativePath))}function Pp(e,t){let{vueCore:n,ts:r,volarTs:i}=eR(e),{parsed:o,vueOptions:s}=tR(n,r,t),a=wp(t),c=n.createVueLanguagePlugin(r,o.options,s,g=>g),l=nR(n,r,c),d=rR(a,o),{languageServiceHost:u}=i.createLanguageServiceHost(r,r.sys,l,g=>g,d),m=r.createLanguageService(u);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function eR(e){let t=Jx(Qx($p(e,"package.json")).href);return{vueCore:Vo(t,"@vue/language-core",e),ts:Vo(t,"typescript",e),volarTs:Vo(t,"@volar/typescript",e)}}function tR(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,wp(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function nR(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Kx(o))return;let s=U(o,{maxBytes:Re,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??lR(o))});return r.current=i,i}function rR(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Vo(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function Tp(e,t,n){let r=iR(e);return i=>{if(!i.name)return null;let o=Qe(t,i.fileName),s=n.get(i.fileName);if(!s)return null;let a=n.positionAt(s,i.textSpan.start),c=r.get(o);if(!c)return null;let l=c.starts.find(u=>u.line===a.line&&u.displayName===i.name);if(l)return l.symbolId;let d=c.containingByLine.get(a.line);return d&&d.displayName===i.name?d.symbolId:oR(c.starts,a.line,2,i.name)}}function iR(e){let t=e.prepare(`
306
- SELECT
307
- d.relative_path AS relativePath,
308
- der.start_line AS startLine,
309
- der.end_line AS endLine,
310
- der.symbol_id AS symbolId,
311
- gs.display_name AS displayName
312
- FROM defn_enclosing_ranges der
313
- JOIN documents d ON d.id = der.document_id
314
- JOIN global_symbols gs ON gs.id = der.symbol_id
315
- ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
316
- `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function oR(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let a=Math.floor((i+o)/2);e[a].line<t?i=a+1:o=a-1}let s=null;for(let a of[o,i]){let c=e[a];if(!c||c.displayName!==r)continue;let l=Math.abs(c.line-t);l>n||(!s||l<s.distance)&&(s={distance:l,symbolId:c.symbolId})}return s?.symbolId??null}function Ep(e,t,n){let r=pR(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
317
- INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
318
- VALUES (?, ?, ?, ?)
319
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=Qe(t,l),u=Np(r.name,r.version,d);o.run(u,"default",7,`Vue component|${d}`);let m=mR(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Ip(e,t,n,r,i){return e.transaction(()=>(Zx(e),sR(e,t,n,r),aR(e,i)))()}function sR(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
320
- INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
321
- VALUES (?, ?, ?, ?, X'00')
322
- `),s=e.prepare(`
323
- INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
324
- VALUES (?, ?, 1)
325
- `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Qe(t,a),d=i.get(l);if(!d)continue;let u=o.run(d.id,-1,0,0);s.run(Number(u.lastInsertRowid),c)}}function Ap(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=r.language.maps.get(s,o);if(Wo(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function jp(e){let t=new Set,n=[];for(let r of e){let i=Lp(r);t.has(i)||(t.add(i),n.push(r))}return n}function Lp(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function aR(e,t){let n=uR(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
326
- INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
327
- VALUES (?, ?, ?, ?, X'00')
328
- `),i=e.prepare(`
329
- INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
330
- VALUES (?, ?, 0)
331
- `),o=new Set,s=0,a=0;for(let c of t){let l=Lp(c);if(o.has(l))continue;o.add(l);let d=n.get(c.sourceFile);if(!d)continue;let u=r.run(d,a++,c.sourceLine,c.sourceLine),m=i.run(Number(u.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*Dp(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function Op(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Wo(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function cR(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function Mp(e,t){return Qe(e,t).startsWith("node_modules/")}function Qe(e,t){return Yx(e,t).replaceAll("\\","/")}function lR(e){switch(zx(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function Fp(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=U(t,{maxBytes:Re,inputKind:"Vue source file"}),r={text:n,lineStarts:dR(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:cR}}function dR(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function uR(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.set(a.relativePath,a.id)}return n}function pR(e){try{let t=JSON.parse(U($p(e,"package.json"),{maxBytes:xe,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function mR(e,t,n,r){let i=Qe(n,r),o=Np(t.name,t.version,i);return e.get(o)?.id??null}function Np(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}async function Uo(e){return Gt($t(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),vR(e)}async function vR(e){let t=SR(e.projectRoot,e.tsconfig);if(!hR(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new gR(e.dbPath);try{let r=Cp(n,e.projectRoot),i=bR(yR(e.dbPath),"augment-vue-meta.json");return await Nu({cachePath:i,readFingerprint:()=>wR(n,e.projectRoot,e.tsconfig),compute:()=>xR({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}async function xR(e){let t=Ep(e.db,e.projectRoot,e.vueFiles),n=vp(e.vueFiles)?await xp({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):kR(e,t);return RR(e,t,n)}function RR(e,t,n){let r=jp(n.occurrences),i=Ip(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:LR(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:jR(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function kR(e,t){let n=$R({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return CR({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function wR(e,t,n){let r=e.prepare(`
332
- SELECT
333
- (SELECT COUNT(*) FROM documents) AS documents,
334
- (SELECT COUNT(*) FROM global_symbols) AS symbols,
335
- (SELECT COUNT(*) FROM chunks) AS chunks,
336
- (SELECT COUNT(*) FROM mentions) AS mentions,
337
- (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
338
- (SELECT MAX(id) FROM chunks) AS maxChunkId,
339
- (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
340
- `).get();return{version:3,tsconfig:n,files:Kn(t),db:r}}function $R(e){let t=Fp();return{projectRoot:e.projectRoot,context:Pp(e.projectRoot,e.configPath),symbolLookup:Tp(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function CR(e){let t=[],n=Ut(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=PR(e,i);t.push(...o.occurrences),Ur(n,o)}return{occurrences:t,...n}}function PR(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return _p(e.projectRoot,t,"missing-source-file");let r=e.context.language.scripts.get(t.fileName),i=r?.generated?.languagePlugin.typescript?.getServiceScript(r.generated.root)?.code;if(!r||!i)return _p(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=Qe(e.projectRoot,t.fileName),a=[...Dp(n.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:OR(a),processedStarts:new Set};return TR({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function TR(e){let t=[],n=Ut();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||ER(e.sourceInfo.text,r.start))continue;let i=Op(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!Mp(e.projectRoot,d.fileName));if(!s){Ho(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=Qe(e.projectRoot,s.fileName),c=IR(e.sourceFile,r.text,a);if(c){Ho(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=Ap(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){Ho(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}Bp(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),DR(t,e,r,i,a,l)}return{occurrences:t,...n}}function ER(e,t){let n=e.lastIndexOf(`
341
- `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function IR(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function _p(e,t,n){let r=Ut();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:Qe(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Ho(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(a=>a.reason===o&&a.sourceFile===r).length>=2)return;let s=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,token:i.text,reason:o})}function Go(e,t){let n=new Map;for(let o of e){let s=n.get(o.sourceFile)??[];s.push(o),n.set(o.sourceFile,s)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let s=!1;for(let a of r){let c=n.get(a)?.[o];if(c&&(i.push(c),s=!0,i.length===t))break}if(!s)break}return i}function AR(e,t){let n=Go(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=Go(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function jR(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let s=n.length-i,a=Math.ceil((t-r.length)/s);r.push(...Go(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function LR(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return AR(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function DR(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of MR(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(s))continue;let a=t.tokenContext.tokenByStart.get(s);a&&(Bp(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function Bp(e,t,n,r,i,o,s){let a=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:s})}function OR(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function MR(e,t,n,r,i,o){let s=e.getDocumentHighlights?.(t,n,[t])??[],a=[];for(let c of s)if(c.fileName===t)for(let l of c.highlightSpans){let d=FR(r,l.textSpan.start,o,i.text);d!==null&&a.push(d)}return a}function FR(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Wo(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function zt(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log}=e,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=GR(e),s=Date.now(),a=W();Kr(B(o.outputScip),{recursive:!0}),Kr(B(o.outputDb),{recursive:!0});let c=e.languages??yt(t);if(c.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${c.join(", ")}`);let l=sn("reindex.fingerprint",()=>Vs(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:c.length}),d,u;if(e.skipIfUnchanged!==!1&&!$l(t,o.outputDb)&&qp(o.outputScip)===qp(oe(B(o.outputDb),"index.scip"))){let h=mt(t);if(d=h?dr(h,l):void 0,d){let S=ur(d);if(S){if(!HR(o,l))try{Bi({snapshot:d,manifest:S,targetCacheDir:B(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${d.generationId.slice(0,12)}`)}catch(y){r(`Shared generation attach failed; continuing locally: ${Kt(y)}`)}}else{let y=await Pl(d);if(y.kind==="owner")u=y.release;else if(y.kind==="generation-ready"){let v=ur(d);if(v)try{Bi({snapshot:d,manifest:v,targetCacheDir:B(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${d.generationId.slice(0,12)} after waiting`)}catch(w){r(`Shared generation attach failed after waiting; continuing locally: ${Kt(w)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let m=pl(oe(B(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!m)throw u?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${B(o.outputDb)}.`);let g;try{g=await an("reindex.lock",()=>bk(oe(B(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:c.length})}catch(h){throw m.release(),u?.(),h}let f=null;try{dl(o.outputDb,o.outputScip,o.metaPath);let h=zR(B(o.outputDb));h.removed>0&&r(`Removed ${h.removed} abandoned reindex workspace(s)`);for(let j of h.errors)r(`Could not remove abandoned reindex workspace: ${j}`);let S=null,y=sn("reindex.reuse-check",()=>(S=UR({opts:e,paths:o,languages:c,fingerprint:l,start:s,monotonicStart:a,onStatus:r}),S),()=>({languages:c.length,reused:S!==null}));if(y)return Vp({snapshot:d,paths:o,projectRoot:t,fingerprint:l,onStatus:r}),Po(o.outputDb,y),Ni(t,B(o.outputDb)),y;await an("reindex.scip-cli-ready",()=>dk(i,r));let v=KR(o);f=v.runDir;let w,R=await an("reindex.fresh",async()=>(w=await YR({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:v,fingerprint:l,start:s,monotonicStart:a,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),w),()=>({languages:c.length,reused:w?.reused,skipped:w?.skipped.length}));return Vp({snapshot:d,paths:o,projectRoot:t,fingerprint:l,onStatus:r}),Po(o.outputDb,R),Ni(t,B(o.outputDb)),R}catch(h){let S=Qr({trigger:e.trigger,result:"failed",start:s,monotonicStart:a,error:h instanceof Error?h.message:String(h)});throw lm(o.metaPath,S),Bu(o.outputDb,S),h}finally{f&&Jt(f,{recursive:!0,force:!0}),g(),m.release(),u?.()}}function Vp(e){if(e.snapshot){if(ur(e.snapshot)){qi(e.snapshot,B(e.paths.outputDb),"local-fresh");return}try{let t=mt(e.projectRoot),n=t?dr(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}Cl({snapshot:e.snapshot,sourceCacheDir:B(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=mt(e.projectRoot);return(r?dr(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),qi(e.snapshot,B(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${Kt(t)}`)}}}function HR(e,t){if(!je(e.outputScip)||!je(e.outputDb)||!cm(e.metaPath,t))return!1;let n=bt(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Kt(e){return e instanceof Error?e.message:String(e)}function GR(e){let t=e.outputScip??oe(e.projectRoot,"index.scip"),n=e.outputDb??oe(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:oe(B(n),"meta.json")}}function UR(e){let t=bt(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!je(e.paths.outputScip)||!je(e.paths.outputDb)||!cm(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;Gt($t(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=W()-e.monotonicStart,r=Qr({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return lm(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:JR(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function JR(e,t,n,r){let i=sm(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:An(i[o]),outputBytes:jn(Yo(e.outputDb,o)),durationMs:0}))}function KR(e){let t=BR(oe(B(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:oe(t,Jr(e.outputScip)),tempOutputDb:oe(t,Jr(e.outputDb)),tempMetaPath:oe(t,Jr(e.metaPath))}}function zR(e){let t=[],n;try{n=zp(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[Kt(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{Jt(oe(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${Kt(o)}`)}return{removed:r,errors:t}}async function YR(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await an("reindex.language-indexers",async()=>(n=await QR(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:s,languageFingerprints:a,shards:c,typescriptProjectShardContext:l,incrementalTypeScript:d}=r;if(s.length>0&&e.onStatus(`Reused ${s.length} cached language shard(s): ${s.join(", ")}`),XR({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let g=sn("reindex.publish",()=>ak(e,i,o,s,a,l),{mode:"metadata-only",languages:i.length,reused:s.length}),f=g.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(f/1e3).toFixed(1)}s`),{languages:i.map(h=>h.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:f,reused:!0,skipped:o,lastRefresh:g,shards:c}}let u=sn("reindex.publish",()=>sk(e,t,i,o,s,a,l,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:s.length,skipped:o.length}),m=u.durationMs;return e.onStatus(`Done in ${(m/1e3).toFixed(1)}s`),{languages:i.map(g=>g.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:u,shards:c}}function XR(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!je(e.run.paths.outputScip)||!je(e.run.paths.outputDb))return!1;let t=bt(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function QR(e,t){let n=rk({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[M,_]of n)_.reused&&(r.push({language:M,scipPath:_.scipPath}),i.add(M));for(let M of i)e.onStatus(`Reusing cached ${M} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),s=bt(e.paths.outputDb,e.paths.metaPath),a=Dn(e.paths.metaPath),c=s.state==="legacy"||s.state==="current",l=a?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?lp({projectRoot:e.projectRoot,cacheDir:B(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Ln(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Ln(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:zo(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,u=new Set(d?["typescript"]:[]),m=d?void 0:ZR(e,n),{preparedRuns:g,skippedLanguages:f,languageOutputScipPaths:h}=uk({languages:e.languages.filter(M=>!i.has(M)&&!u.has(M)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,trustProjectTools:e.opts.trustProjectTools===!0,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:m?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),S=m?g.filter(M=>M.language!=="typescript"||m.missedProjectIds.has(M.id)):g,y=await mp(S,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),v=[];if(m){tk(e.paths.outputDb,y);let M=h.typescript??e.tempPaths.tempOutputScip;v=nk({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:M,reusedProjects:m.reusedProjects})}let w=[...y,...v],{indexedOutputs:R}=mk(w,f),j=d?[{language:"typescript",scipPath:d.scipPath}]:[],P=[...r,...j,...R];fk(P,f,e.languages,e.opts.allowPartial,e.onStatus);let G=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:jn(d.scipPath)??void 0}]:[],A=ik(n,[...y,...G],m?{outputDb:e.paths.outputDb,classification:m.classification}:void 0);return{indexedOutputs:P,skippedLanguages:f,reusedLanguages:[...i],languageFingerprints:ok(n,e.languages),shards:A,typescriptProjectShardContext:m?{projects:m.allProjects,fingerprints:m.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function ZR(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=En(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Uu(e.projectRoot,r),o=Wu(n.fingerprint.files,r),s=Hu(r,i),a=Gu(r,o,s),c=Dn(e.paths.metaPath),d=ek(c,a,f=>je(Xr(e.paths.outputDb,f))),u=[...d.entries()].filter(([,f])=>f.reused).map(([f])=>f),m=new Set(u),g=new Set(r.filter(f=>!m.has(f)).map(f=>`typescript:${f}`));return{allProjects:r,fingerprints:a,classification:d,reusedProjects:u,missedProjectIds:g}}function ek(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let s=e.version===nn&&Ci(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[i]:void 0;if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(Ze(s)!==Ze(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function tk(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=Xr(e,r);Kr(B(i),{recursive:!0}),Yr(n.scipPath,i)}}function nk(e){return e.reusedProjects.map((t,n)=>{let r=Xr(e.outputDb,t),i=Ln(e.tempOutputScip,"typescript-project-cached",n);return Yr(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:jn(i)??void 0}})}function rk(e){let t=Dn(e.paths.metaPath),n=sm(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Yo(e.paths.outputDb,i),s=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:s,scipPath:o});continue}if(t.version!==nn){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:s,scipPath:o});continue}if(!Ci(t).languageShardReuse||!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:o});continue}let a=t.languageFingerprints[i];if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:o});continue}if(!je(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}if(Ze(a)!==Ze(s)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:s,scipPath:o})}return r}function ik(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:An(o.fingerprint),outputBytes:jn(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),s=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,a=s?n.classification.get(s):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:a?.reason??o?.reason??i.skipped?.reason,fingerprint:a?An(a.fingerprint):o?An(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:An(o.fingerprint),outputBytes:jn(Xr(n.outputDb,i)),durationMs:0});return r}function An(e){return _R("sha256").update(Ze(e)).digest("hex").slice(0,16)}function jn(e){try{return qR(e).size}catch{return null}}function ok(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function sk(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(Wp(e.paths.outputDb,n),l=Hp(n,e.tempPaths.tempOutputScip,e.onStatus));let d=gk({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:a,completeScipAvailable:c,completeScipSanitized:l,materializeFullFallback:()=>{if(!a||a.completeScipUpdated)return l;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),dp({cacheDir:B(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let v=n.map(w=>w.language==="typescript"?{language:w.language,scipPath:a.candidateScipPath}:w);return Wp(e.paths.outputDb,v),l=Hp(v,e.tempPaths.tempOutputScip,e.onStatus),l}});if(Gt($t(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&a){let v=null,w=null;try{v=new gt({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),w=new gt({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let R=ka(v,e.fingerprint,a.referenceFragmentsByFile,w);e.onStatus(`Cached exact TypeScript reference fragments for ${R} affected document(s).`)}catch(R){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${R instanceof Error?R.message:String(R)}.`)}finally{v?.close(),w?.close()}}let u=zo(e.paths.metaPath),m=d.mode==="incremental"&&a?yk(a,d.changedDocumentPaths):Ro({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:u,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),g=Qr({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(v=>v.language),skipped:[...r]}),f=d.mode==="incremental"&&d.scipCompanion==="deferred",h={...o};f&&delete h.typescript;let{metadata:S,pruneProjects:y}=Qp({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:h,typescriptProjectShardContext:s,lastRefresh:g});return S.scipCompanion=f?"deferred":"current",Zp(e.paths.outputDb,y),Xo(e.tempPaths.tempMetaPath,S),ll({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:a?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:a?.timings.serviceMs,materializationDurationMs:a?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&a?{typescriptOverlayGeneration:a.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}}),xl(B(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),Xp(e.paths.outputDb,m,e.onStatus),g}function ak(e,t,n,r,i,o){let s=zo(e.paths.metaPath),a=null;try{Yr(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(u){a=wu("reused","oracle-error",`Could not snapshot the prior database: ${u instanceof Error?u.message:String(u)}`)}Gt($t(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),a??=Ro({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:s,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=Qr({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(u=>u.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=Qp({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Zp(e.paths.outputDb,d),Xo(e.paths.metaPath,l),ul(e.paths.outputDb,e.paths.metaPath),Xp(e.paths.outputDb,a,e.onStatus),c}function zo(e){return Os(Dn(e)?.fingerprint)}function Xp(e,t,n){try{Tu(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function Qp(e){let t=ck({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:nn,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function ck(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=Dn(e.metaPath),n=t?.version===nn?t.typescriptProjectShards:void 0;return{field:n,pruneProjects:n?Object.keys(n):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Zp(e,t){let n=am(e);if(t===null){Jt(n,{recursive:!0,force:!0});return}let r;try{r=zp(n)}catch{return}for(let i of lk(r,t))Jt(oe(n,i),{force:!0})}function lk(e,t){let n=new Set(t.map(r=>`${jo(r)}.scip`));return e.filter(r=>!n.has(r))}function Wp(e,t){for(let n of t){let r=Yo(e,n.language);Kr(B(r),{recursive:!0}),n.scipPath!==r&&Yr(n.scipPath,r)}}async function dk(e,t){if(!Ht()){if(WR()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
342
- To install the reviewed version, run: scip-query reindex --install-missing
343
- Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!mu(t))throw new Error(`The scip CLI is required but could not be installed.
344
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function uk(e){let t=[],n=[],r=e.languages.map((o,s)=>({language:o,scipPath:e.languages.length>1?Ln(e.tempOutputScip,o,s):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:o,scipPath:s})=>[o,s]));for(let{language:o,scipPath:s}of r){let a=pk({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?em(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function pk(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Jo({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??En(e.projectRoot,e.typescriptProjects);return t.length===0?[Jo({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,r)=>Jo({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Ln(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Jo(e){let t=kt(e.language),n=tr(t),r=na(t,e.projectRoot),i=e.trustProjectTools&&r?ra(t,e.projectRoot):null,o=dn(t);if(!i&&!o&&r){let l=`${n} is available only as repository-local code at ${r}. Review that exact tool and rerun with --trust-project-tools.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}if(!i&&!o&&!ta(t)){if(e.skipAutoInstall){let l=`${n} not found on PATH. To install the reviewed version, run: scip-query reindex --install-missing${t.installUrl?` (manual source: ${t.installUrl})`:""}`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Gr(t,e.onStatus)){let l=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}}let s=i?.canonicalPath??dn(t);if(!s){let l=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}let{binary:a,args:c}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:s,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});if(i&&!i.executable){let l=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}return i&&e.onStatus(`Trusted project-local ${e.language} indexer ${i.relativePath} (${i.sha256.slice(0,12)}\u2026, ${i.canonicalPath}).`),{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:s,binary:a,args:c,env:oa(t,e.env,s),...i?{trustedProjectTool:i}:{}}}}function mk(e,t){let n=new Map;for(let i of e)if(i.skipped)em(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`,s=n.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};s.scipPaths.push(i.scipPath),n.set(o,s)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)kl(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&Yp(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function em(e,t){let n=e.find(r=>r.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function fk(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
345
- `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
346
- `+o)}if(t.length!==0&&(i(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(o=>o.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
347
- `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
348
- `))}function Hp(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=wl(e.map(o=>o.scipPath),t);return nm(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Yp(e[0].scipPath,t);return!1}function gk(e){let t;if(hk(e)){let i=oe(e.run.tempPaths.runDir,"typescript-affected.db");try{tm(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Gp(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let s=Ou({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${s.affectedDocumentCount} SQLite document(s) in ${(s.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:s.changedDocumentPaths,patchDurationMs:s.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){t=o instanceof Error?o.message:String(o),Jt(i,{force:!0}),Jt(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}}let n=e.completeScipSanitized;e.completeScipAvailable||(n=e.materializeFullFallback());let r=performance.now();return Gp(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function hk(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!je(e.run.paths.outputDb)||!je(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function yk(e,t){let n=W(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(s=>!i.has(s)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:W()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:xo(e.plan,o,e.projectFileCount)}}function Gp(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!je(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||tm(e,r);let o=Ht();if(!o)throw new Error("scip CLI is not available");NR(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024,timeout:3e5,killSignal:"SIGKILL"})}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:o})}}function tm(e,t){let n=Rl(e);nm(n,t)}function nm(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Ln(e,t,n){let r=VR(e)||".scip",i=Jr(e,r);return oe(B(e),`${i}.${n+1}.${t}${r}`)}async function bk(e,t){for(let n=0;n<2;n++){let r=Sk(e,t);if(r)return r;let i=vk(e);if(i&&om(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await Rk(i)}catch(a){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${i.pid}); refusing to steal an active lock: ${Kt(a)}`,{cause:a})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${B(e)}; refusing to steal an active lock.`);let s=_i(e,{parseLegacy:zr});if(!ol(e,s,{parseLegacy:zr}))throw new Error(`Reindex lock ownership changed before preemption completed for ${B(e)}.`);continue}throw new Error(`Another scip-query reindex is already running for ${B(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${B(e)}.`)}function Sk(e,t){let n=Lt(process.pid),r=Ot(e,{kind:"reindex",processIdentity:n,detail:{projectRoot:t.projectRoot,...process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1"?{processGroupLeader:!0}:{},...t.trigger?{trigger:t.trigger}:{}},parseLegacy:zr});if(r.kind==="acquired"&&r.reclaimed){let i=rm(r.reclaimed,e);i&&om(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${B(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function vk(e){return rm(_i(e,{parseLegacy:zr}),e)}var zr=e=>{let t=im(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function rm(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:B(t),startedAt:e.record.startedAt,trigger:n.trigger}}return im(e.parsed,t)}function im(e,t){try{let n=e;return typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0?null:{version:n.version===2?2:1,pid:n.pid,...n.processIdentity===void 0?{}:(()=>{let r=aa(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:B(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function om(e,t){return e?.kind==="manual-cli"&&xk(t?.trigger)}function xk(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function Rk(e){return!jt(e.pid)||(Ko(e),Up(e,"SIGTERM"),await Jp(e,2e3))?!0:(Ko(e),Up(e,"SIGKILL"),Jp(e,1e3))}function Up(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!jt(e.pid))return;Ko(e)}try{process.kill(e.pid,t)}catch{}}async function Jp(e,t){let n=W()+t;for(;W()<n;){if(Kp(e))return!0;await kk(50)}return Kp(e)}function Ko(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=Lt(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!un(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Kp(e){if(!jt(e.pid))return!0;if(!e.processIdentity)return!1;let t=Lt(e.pid);return t!==null&&!un(e.processIdentity,t)}function kk(e){return new Promise(t=>setTimeout(t,e))}function sm(e,t,n){return Object.fromEntries(t.map(r=>{let i=kt(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:qs(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=r==="clojure"?wk(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&$k(n),...o,clojureConfigPath:s,files:Kn(e,{language:r,markerFiles:i})}]}))}function wk(e){return e?.trim()||void 0}function $k(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Yo(e,t){return oe(B(e),"language-indexes",`${t}.scip`)}function am(e){return oe(B(e),"language-indexes","typescript-projects")}function Xr(e,t){return oe(am(e),`${jo(t)}.scip`)}function Dn(e){try{return $i(Et(V(e,"reindex metadata")))}catch{return null}}function cm(e,t){try{let n=Et(V(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return!1;let r=n.metadata;return n.capabilities.publishableGeneration&&Ze(r.fingerprint)===Ze(t)&&Ze([...r.indexedLanguages??[]].sort())===Ze(t.languages)}catch{return!1}}function Xo(e,t){da(e,t,{spacing:2,trailingNewline:!0})}function lm(e,t){try{let n=$i(Et(V(e,"reindex metadata")));if(!n)return;Xo(e,{...n,lastRefresh:t})}catch{}}function Qr(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:W()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function Ze(e){return JSON.stringify(e)}var Qo=864e5;function dm(e,t={}){let r=[...t.check?e.filter(l=>l.check===t.check):[...e]].sort((l,d)=>l.ts-d.ts),i=new Map;for(let l of r){let d=`${l.check}\0${l.findingId}`,u=i.get(d);u||(u={check:l.check,findingId:l.findingId,caughtAt:l.ts,events:[]},i.set(d,u)),u.events.push(l)}let o=[...i.values()].filter(l=>t.sinceMs===void 0||l.caughtAt>=t.sinceMs),s=Ck(r),a=new Map;for(let l of o){let d=a.get(l.check)??[];d.push(l),a.set(l.check,d)}let c=[];for(let[l,d]of a){let u=0,m=0,g=0,f=0,h=0,S=0,y=[];for(let w of d){g+=w.events.filter(P=>P.event==="reopened").length;let R=w.events[w.events.length-1],j=`${w.check}\0${w.findingId}`;if(R.event==="resolved"&&s.has(j))f+=1;else if(R.event==="resolved"){let P=gn(w.events.slice(0,-1)),G=P?.comparisonBaseCommit??P?.commit,A=R.comparisonBaseCommit??R.commit;G&&(A===G||R.verifiedAgainstCommit===G)?(u+=1,y.push((R.ts-w.caughtAt)/Qo)):h+=1}else R.event==="suppressed"?m+=1:S+=1}let v=u+m;c.push({check:l,caught:d.length,fixed:u,suppressed:m,reopened:g,moved:f,unverified:h,open:S,precision:v>0?u/v:null,medianDaysToFix:y.length>0?Pk(y):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,d)=>l.check.localeCompare(d.check))}}function Ck(e){let t=new Map;for(let i of e){if(i.event!=="caught"||!i.commit||!i.symbol)continue;let o=t.get(i.commit)??[];o.push(i),t.set(i.commit,o)}let n=new Map;for(let i of e)i.event==="caught"&&i.symbol&&n.set(`${i.check}\0${i.findingId}`,i.symbol);let r=new Set;for(let i of e){if(i.event!=="resolved"||!i.commit)continue;let o=`${i.check}\0${i.findingId}`,s=i.symbol??n.get(o);if(!s)continue;(t.get(i.commit)??[]).some(c=>c.check===i.check&&c.symbol===s&&c.findingId!==i.findingId)&&r.add(o)}return r}function um(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*Qo:Qo;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function Pk(e){let t=[...e].sort((r,i)=>r-i),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}import{statSync as Tk}from"fs";import{basename as Ek,isAbsolute as Ik,join as Ak,relative as jk}from"path";import{watch as Lk}from"chokidar";import Dk from"ignore";var Zr=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(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Oe(t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onReindexError=t.onReindexError??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.clock=t.clock??Mk,this.reindexRunner=t.reindexRunner??Vk(),this.subscriptionFactory=t.subscriptionFactory??Fk,this.gitignoreFilter=lr(t.projectRoot),this.extraIgnore=Dk(),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(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let t=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer();let n=this.activeOperation;return n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"}),this.stopPromise=this.finishStop(t,n).finally(()=>{this.stopInProgress=!1}),this.stopPromise}requestRefresh(t,n={}){if(!this.stopped){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=mm(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(r,i)=>this.isIgnoredWatchPath(r,i?.isDirectory()??!1),usePolling:t,...t?{interval:500,binaryInterval:1e3}:{}});n.on("all",(r,i)=>{this.stopped||this.handleFileChange(i)}),n.on("error",r=>this.handleSourceWatcherError(n,r,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,r){if(r||this.sourcePollingFallbackStarted||!Wk(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==t),t.close();try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(t,n){let r=this.relativeWatchPath(t);if(!r)return!1;let i=n?`${r}/`:r;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(t){let n=this.relativeWatchPath(t);!n||n===".."||n.startsWith("../")||n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||n.endsWith("index.db")||n.endsWith("index.scip")||n.endsWith("index.db.tmp")||Ek(n).startsWith($o)||this.scheduleReindex({kind:"watch-source",detail:n})}relativeWatchPath(t){let n=Ik(t)?t:Ak(this.projectRoot,t);return jk(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=mm(this.pendingTrigger,t),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let n=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let o=this.watchConfig.cooldownMs-t;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 n=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=this.wallNow();this.setStatus({state:"indexing",startedAt:r});let i=this.reindexRunner.start(this.reindexRequest(n));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,n)===!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,n),this.onError(s),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===i&&(this.activeOperation=null)})}async finishStop(t,n){let r=[],i=n?n.cancel():null,o=await Promise.allSettled(t.map(s=>Promise.resolve().then(()=>s.close())));for(let s of o)s.status==="rejected"&&r.push(`watch subscription close failed: ${String(s.reason)}`);if(i)try{let s=await i;s.state==="degraded"&&r.push(s.reason)}catch(s){r.push(`reindex cancellation failed: ${s instanceof Error?s.message:String(s)}`)}return r.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:r.join("; ")}),{state:"degraded",reasons:r}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}reindexRequest(t){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:t}}setStatus(t){this.status=t,this.onStatus(t)}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 t=this.lastGitState,n=this.readGitState();if(!t||!n||this.stopped){this.lastGitState=n;return}this.lastGitState=n;let r=t.head!==n.head,i=t.indexPath!==n.indexPath||t.indexMtimeMs!==n.indexMtimeMs||t.indexSize!==n.indexSize;r&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):r?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:n.indexPath??"index changed"})}readGitState(){let t=pn(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n=ga(this.projectRoot,t),r={head:pn(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let i=Tk(n);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Ok(e){let{projectRoot:t,config:n,languages:r,pnpmWorkspaces:i,typescriptProjectMode:o,typescriptProjects:s,clojureConfigPath:a,indexerConcurrency:c,trigger:l}=e,d=ke(t),u=Object.keys(d).length>0?d:n,m=He(t,u),g=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:t,SCIP_REINDEX_OUTPUT_SCIP:m.indexPath,SCIP_REINDEX_OUTPUT_DB:m.dbPath,SCIP_REINDEX_LANGUAGES:(u.languages??r)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(u.indexerConcurrency??c??""),SCIP_REINDEX_PNPM_WORKSPACES:g?.pnpmWorkspaces??i?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:g?.projectMode??o,projects:g?.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 Mk={now:W,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Fk=(e,t)=>Lk(e,t),Nk=15*6e4,_k=1e3,Bk=64*1024;function qk(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function pm(e,t){let n=e instanceof Error?e.message:String(e),r=t.stderrTail.trim()||t.stdoutTail.trim();return r?`${n}
349
- ${r}`:n}function Vk(e={}){let t=e.timeoutMs??Nk,n=e.terminationGraceMs??_k,r=e.maxOutputBytes??Bk,i=e.resolveLaunch??Ok;return{start(o){let s=i(o),a=new AbortController,c=qk(),l=!1,d=mr({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:r,maxStderrBytes:r,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(u=>{if(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0)throw new Error(pm(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c));return u.durationMs}).catch(u=>{throw u instanceof pr&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(pm(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 mm(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}function Wk(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}import{existsSync as uw}from"fs";import{existsSync as gm,mkdirSync as hm,writeFileSync as ym}from"fs";import{homedir as Hk}from"os";import{dirname as bm,isAbsolute as Gk,join as Zo,relative as fm,resolve as Uk}from"path";function Sm(e,t={}){let n=t.dossierDir?Uk(e.projectRoot,t.dossierDir):Zo(e.projectRoot,"docs","scip-query"),r={markdownPath:Zo(n,"health-dossier.md"),jsonPath:Zo(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=tw({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return Qk(r.markdownPath,Jk(i),r),Zk(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function Jk(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${ts(e.health)}`,"","## Items That Need Attention","",...Kk(e),"","## Blocked Or Unavailable Checks","",...zk(e),"","## Setup Smoke Tests","",...e.smokeTests.map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),"","## Setup Steps","",...e.steps.map(n=>`- ${n.status.toUpperCase()} ${n.label}${n.message?`: ${n.message}`:""}`),"","## Indexer Remediation","",...Yk(e),"","## JSON","",`Machine-readable report: \`${Xk(e)}\``,""].join(`
350
- `)}`}function Kk(e){return e.health.issuesNeedAttention.length===0?["No prioritized health actions were reported."]:e.health.issuesNeedAttention.map(t=>`- ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort}, evidence ${t.evidence}; confirmation ${t.confirmationStatus}; safe to start ${t.safeForAgentToStart?"yes":"no"}). ${t.recommendedNextStep}`)}function zk(e){let t=[...e.smokeTests.filter(n=>n.status!=="pass").map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),...e.indexerRemediation.filter(n=>!n.after.runnable).map(n=>`- BLOCKED ${n.language}: ${n.recovery??`Install ${n.binaryLabel}.`}`)];return t.length>0?t:["No blocked or unavailable setup checks were reported."]}function Yk(e){return e.indexerRemediation.length===0?["All detected indexers were already runnable."]:e.indexerRemediation.map(t=>{let n=t.after.runnable?"READY":"BLOCKED",r=t.attempted?"install attempted":"no automatic install attempted";return`- ${n} ${t.language}: ${t.binaryLabel} (${r})`})}function ts(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function Xk(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Qk(e,t,n){if(hm(bm(e),{recursive:!0}),(gm(e)?V(e,"health dossier Markdown"):null)===t){n.unchanged.push(e);return}ym(e,t),n.written.push(e)}function Zk(e,t,n){hm(bm(e),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
351
- `,i=gm(e)?V(e,"health dossier JSON"):null;if(i&&ew(i,r)){n.unchanged.push(e);return}ym(e,r),n.written.push(e)}function ew(e,t){try{let n=JSON.parse(e),r=JSON.parse(t);return delete n.generatedAt,delete r.generatedAt,JSON.stringify(n)===JSON.stringify(r)}catch{return e===t}}function tw(e,t){return es(e,t)}function es(e,t){return typeof e=="string"?nw(e,t):Array.isArray(e)?e.map(n=>es(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,es(r,t)])):e}function nw(e,t){if(e===t)return".";if(!Gk(e))return e;let n=fm(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=fm(Hk(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as rw}from"child_process";import{dirname as vm,join as iw,resolve as ow}from"path";import{fileURLToPath as sw}from"url";var ei={typescript:{ast:"typescript",packages:["tree-sitter-typescript"]},javascript:{ast:"javascript",packages:["tree-sitter-javascript"]},java:{ast:"java",packages:["tree-sitter-java"]},scala:{ast:"scala",packages:["tree-sitter-scala"]},kotlin:{ast:"kotlin",packages:["tree-sitter-kotlin"]},rust:{ast:"rust",packages:["tree-sitter-rust"]},python:{ast:"python",packages:["tree-sitter-python"]},ruby:{ast:"ruby",packages:["tree-sitter-ruby"]},cpp:{ast:"cpp",packages:["tree-sitter-cpp"]},c:{ast:"c",packages:["tree-sitter-c"]},csharp:{ast:"csharp",packages:["tree-sitter-c-sharp"]},php:{ast:"php",packages:["tree-sitter-php"]}};function aw(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of ei[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function ns(e){return[...new Set(e.filter(t=>ei[t]!==void 0))].sort()}function xm(e,t={}){let n=t.runtime??dw,r=t.packageRoot??cw(),i=ns(e),o=i.filter(u=>n.probe(ei[u].ast)),s=i.filter(u=>!o.includes(u));if(s.length===0)return{supportedLanguages:i,availableBefore:o,installed:[],availableAfter:o,unavailable:[],attempted:!1};let a=lw(r),c=aw(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let d=i.filter(u=>n.probe(ei[u].ast));return{supportedLanguages:i,availableBefore:o,installed:l.ok?c:[],availableAfter:d,unavailable:i.filter(u=>!d.includes(u)),attempted:!0,...l.error?{error:l.error}:{}}}function cw(){let e=vm(sw(import.meta.url));for(;;){let t=iw(e,"package.json");try{if(JSON.parse(V(t,"AST parser package manifest")).name==="scip-query")return e}catch{}let n=vm(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function lw(e){return JSON.parse(V(ow(e,"package.json"),"AST parser package manifest")).optionalDependencies??{}}var dw={probe:e=>zn(e)==="ast",resetProbe:Hs,install:(e,t)=>{let n=rw(process.env.npm_execpath?process.execPath:"npm",[...process.env.npm_execpath?[process.env.npm_execpath]:[],"install","--no-save","--no-package-lock","--include=optional",...t],{cwd:e,encoding:"utf8",timeout:3e5,killSignal:"SIGKILL",maxBuffer:10485760});return n.status===0?{ok:!0}:{ok:!1,error:(n.stderr||n.stdout||n.error?.message||"npm install failed").trim()}}};function wm(e){let t=[];e.watchEnabled||t.push({id:"enable-automatic-refresh",scope:"repository",label:"Enable automatic incremental indexing",recommended:!0,requiresConsent:!0,reason:"A demand-started project service keeps indexes current and exits after a clean idle period.",command:"scip-query setup"}),e.files.agentsMd||e.files.claudeMd?t.push({id:"update-agent-guidance",scope:"repository",label:"Update project agent guidance",recommended:!0,requiresConsent:!0,reason:"Existing AGENTS.md or CLAUDE.md guidance can be updated in place.",command:"scip-query setup-agent"}):t.push({id:"create-agent-guidance",scope:"repository",label:"Create project agent guidance",recommended:!1,requiresConsent:!0,reason:"No AGENTS.md or CLAUDE.md file exists, so setup should ask before creating one.",command:"scip-query setup-agent"}),(!e.files.codexHooks||!e.files.claudeSettings)&&t.push({id:"install-project-hooks",scope:"checkout",label:"Install project agent hooks",recommended:!0,requiresConsent:!0,reason:"Project hooks help agents check freshness and route through scip-query before editing.",command:"scip-query setup-hooks"});let n=e.readiness.indexers.filter(r=>!r.runnable);return n.length>0&&t.push({id:"install-indexers",scope:"user",label:"Install missing language indexers",recommended:!0,requiresConsent:!0,reason:`${n.length} detected language indexer(s) are not runnable.`,command:"scip-query setup --install-missing"}),{actions:t}}async function $m(e={}){let t=[],n=Ge(),{projectRoot:r,paths:i,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?al(r,n.config,e.languages):null,c=a?.config??n.config,l=Mt(c,{projectRoot:r}),d=l.filter(D=>D.level==="error"),u=null,m=null;if(d.length===0&&c.watch?.enabled!==s)try{u=cl(r,c,s)}catch(D){m=Yt(D)}let g=u?.config??c,f=Cn();q(t,{id:"automatic-indexing-config",label:"Automatic indexing config",status:m!==null?"failed":d.length>0||!s?"skipped":"ok",message:m??(d.length>0?"Skipped because the existing project config has validation errors.":s?u?.changed?"Enabled demand-started automatic incremental indexing for this project.":"Demand-started automatic incremental indexing is already enabled.":"Automatic incremental indexing remains explicitly disabled for this project."),...u?{details:[u.configPath]}:{}}),q(t,{id:"scip-cli",label:"scip CLI",status:f?"ok":"warn",message:f?"scip CLI is available.":"scip CLI is not available; installation requires explicit --install-missing consent."});let h=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:Or({quiet:!0});q(t,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":h.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${h.installed.length} installed, ${h.alreadyLinked.length} already linked, ${h.pruned.length} pruned, ${h.skipped.length} skipped.`,details:[...h.pruned.map(D=>`Pruned ${D}`),...h.skipped.map(D=>`Skipped ${D}`)]});let S=u?Mt(g,{projectRoot:r}):l,y=S.filter(D=>D.level==="error");q(t,{id:"config",label:"Project config",status:y.length>0?"failed":S.length>0?"warn":"ok",message:S.length===0?"Config OK.":`${S.length} diagnostic(s), ${y.length} error(s).`,details:S.map(D=>`${D.level.toUpperCase()} ${D.path}: ${D.message}`)});let v=$e(r,g);q(t,{id:"readiness",label:"Indexer readiness",status:v.languages.length===0?"failed":v.indexers.some(D=>!D.runnable)?"warn":"ok",message:v.languages.length===0?"No supported project languages detected.":`Detected languages: ${v.languages.join(", ")}`,details:v.indexers.map(D=>`${D.runnable?"OK":D.installed?"WARN":"MISSING"} ${D.language}: ${D.binaryLabel}${D.note?` - ${D.note}`:""}`)});let w=e.installAstParsers!==!0?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:xm(v.languages);q(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers!==!0?"skipped":w.unavailable.length>0?"warn":"ok",message:e.installAstParsers!==!0?"Skipped because installing missing parser packages requires explicit consent.":w.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${w.availableAfter.length}/${w.supportedLanguages.length} selected language parser(s) available${w.installed.length>0?`; installed ${w.installed.join(", ")}`:""}.`,details:[...w.unavailable.length>0?[`Unavailable: ${w.unavailable.join(", ")}`]:[],...w.error?[w.error]:[]]});let R=e.installIndexers===!0,j=R?Rw(r,v,t):[];R||q(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because installing missing indexers requires explicit consent."});let P=$e(r,g),G=await pw({projectRoot:r,paths:i,config:g,readiness:P,configHasErrors:y.length>0,steps:t,onStatus:e.onStatus,installMissing:e.installIndexers===!0}),A=G.reindexResult,M=G.freshness,_=Oe(g),N=mw({projectRoot:r,cacheDir:i.cacheDir,watchConfig:_,readiness:P,configHasErrors:y.length>0,reindexResult:A,postReindexFreshness:M,steps:t}),H=$e(r,g),Pe=ot(H),ut=Me(r,g,i);q(t,{id:"capabilities",label:"Capability matrix",status:Tw(Pe),message:Ew(Pe)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let Ls=e.runHealth===!1?$w(t):await ww(i.dbPath,t),Le=H.languages.includes("rust")?rr(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;q(t,{id:"rust-semantic-session",label:"Rust semantic session",status:Le===null?"skipped":Le.valid?"ok":"failed",message:Le===null?"Skipped because Rust was not detected.":`${Le.transport}/${Le.state} selected from ${Le.source}; ${Le.fallback} fallback; opt out with ${Le.optOut}.`});let ae=null;try{e.noHooks?q(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(ae=Wt(r),q(t,{id:"project-hooks",label:"Project agent hooks",status:ae.skipped.length>0?"warn":"ok",message:`${ae.installed.length} installed, ${ae.updated.length} updated, ${ae.unchanged.length} already configured, ${ae.removed.length} hook config(s) cleaned up, ${ae.skipped.length} skipped.`,details:[...ae.gitExcluded.map(D=>`Checkout-local Git exclude: ${D}`),...ae.removed.map(D=>`Removed ${D}`),...ae.skipped.map(D=>`Skipped ${D.target}: ${D.reason}`),...ae.warnings]}))}catch(D){q(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:Yt(D)})}let Te=null;try{e.noAgentGuidance?q(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(Te=Er(r,{gitHook:e.gitHook}),q(t,{id:"agent-guidance",label:"Project agent guidance",status:Te.skipped.length>0?"warn":"ok",message:`${Te.written.length} written, ${Te.unchanged.length} already wired, ${Te.skipped.length} skipped.`,details:Te.skipped.map(D=>`Skipped ${D.target}: ${D.reason}`)}))}catch(D){q(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Yt(D)})}let Wn=fw({reindexResult:A,readiness:H,capabilities:Pe,freshness:ut,health:Ls,hooksResult:ae,agentResult:Te,watchConfig:_,watchService:N,rustSemanticSession:Le,steps:t});q(t,{id:"smoke-tests",label:"Setup smoke tests",status:gw(Wn),message:hw(Wn),details:Wn.map(D=>`${D.command}: ${D.status} - ${D.evidence}`)});let Ah={repository:[...a?.changed?[a.configPath]:[],...u?.changed?[u.configPath]:[],...Te?.written.filter(D=>!D.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...ae?.installed??[],...ae?.updated??[],...ae?.gitExcluded??[],...Te?.written.filter(D=>D.startsWith(".git/hooks/"))??[]])],user:[...h.installed,...w.installed,...j.filter(D=>D.attempted).map(D=>`${D.binaryLabel} installer`)]},qe={projectRoot:r,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:f,languages:H.languages,steps:t,skills:h,astParsers:w,initialReadiness:v,indexerRemediation:j,readiness:H,capabilities:Pe,freshness:ut,reindex:A,automaticRefreshConfig:u,watchService:N,rustSemanticSession:Le,health:Ls,smokeTests:Wn,healthDossier:null,hooks:ae,setupAgent:Te,changeScopes:Ah,filesWritten:Te?.written??[],verdict:is(t,H)};if(e.runHealth===!1)return q(t,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),qe.verdict=is(t,H),qe;let De=Sm(qe,{dossierDir:e.dossierDir});return qe.healthDossier=De,qe.changeScopes.repository.push(...De.written),qe.filesWritten=[...qe.filesWritten,...De.written],q(t,{id:"health-dossier",label:"Health dossier",status:De.status==="failed"?"failed":"ok",message:De.status==="failed"?De.error:`${De.written.length} written, ${De.unchanged.length} unchanged.`,details:[De.markdownPath,De.jsonPath]}),qe.verdict=is(t,H),qe}async function pw(e){if(e.readiness.languages.length===0||e.configHasErrors)return q(e.steps,{id:"reindex",label:"Index refresh",status:"skipped",message:e.readiness.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."}),{reindexResult:null,freshness:null};let t=[],n=null,r=null;try{let i=0,o=!1;for(let s=0;s<2;s+=1){if(n=await zt({projectRoot:e.projectRoot,languages:e.readiness.languages,outputScip:e.paths.indexPath,outputDb:e.paths.dbPath,pnpmWorkspaces:e.config.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.config.indexer?.typescript?.projectMode,typescriptProjects:e.config.indexer?.typescript?.projects,clojureConfigPath:e.config.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,installMissing:e.installMissing,indexerConcurrency:e.config.indexerConcurrency,trigger:{kind:"setup",detail:"scip-query setup"},onStatus:a=>{t.push(a),e.onStatus?.(a)}}),i+=n.durationMs,o||=!n.reused,r=Me(e.projectRoot,e.config,e.paths),s===0&&n.skipped.length===0&&r.state==="stale"){t.push(`Index inputs changed during the first build (${r.reason}); running one settling refresh.`);continue}break}if(!n)throw new Error("Setup index refresh produced no result.");q(e.steps,{id:"reindex",label:"Index refresh",status:n.skipped.length>0?"warn":"ok",message:`${o?"Indexed":"Reused"} ${n.languages.join(", ")} in ${(i/1e3).toFixed(1)}s.`,details:[...t,...n.skipped.map(s=>`Skipped ${s.language}: ${s.reason}`)]})}catch(i){q(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:Yt(i),details:t})}return{reindexResult:n,freshness:r}}function mw(e){let t=e.readiness.languages.length===0?"Skipped because no supported languages were detected.":e.configHasErrors?"Skipped because config validation has errors.":e.watchConfig.enabled?e.reindexResult===null||e.reindexResult.skipped.length>0||e.postReindexFreshness?.state!=="fresh"?"Skipped because the initial refresh did not produce a complete fresh generation.":null:"Disabled by watch.enabled=false; setup left the explicit opt-out unchanged.";if(t!==null)return q(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=Sr({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:ye,watchOverrides:e.watchConfig});if(e.watchConfig.idleTimeoutMs>0&&n.state.idleDeadlineAt===void 0)throw new Error("Automatic indexing service did not publish its configured clean-idle deadline.");let r=e.watchConfig.idleTimeoutMs===0?"configured to remain running":`clean-idle exit scheduled for ${n.state.idleDeadlineAt}`;return q(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"ok",message:`${n.disposition} pid ${n.state.pid}; ${r}.`,details:[`watcher=${n.state.watcher.state}`,`autoRefresh=${e.watchConfig.autoRefresh}`,`gitPollMs=${e.watchConfig.gitPollMs}`]}),n}catch(n){return q(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:Yt(n)}),null}}function Cm(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${ts(e.health)}`),console.log(""),e.health.issuesNeedAttention.length===0)console.log("Items that need attention: none reported by the health pass.");else{console.log("Items that need attention:");for(let t of e.health.issuesNeedAttention)console.log(` - ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort})`)}if(e.health.unavailableReason&&console.log(`Health pass: ${e.health.unavailableReason}`),e.health.warnings.length>0){console.log("Health warnings:");for(let t of e.health.warnings)console.log(` - ${t}`)}e.healthDossier&&console.log(`Health dossier: ${e.healthDossier.markdownPath}`),console.log(""),console.log("Change scopes:"),rs("Repository records (commit)",e.changeScopes.repository),rs("Checkout preferences (do not commit)",e.changeScopes.checkout),rs("User environment",e.changeScopes.user),console.log(""),console.log("Setup steps:");for(let t of e.steps)console.log(` ${t.status.toUpperCase()} ${t.label}${t.message?` - ${t.message}`:""}`);console.log(""),console.log("Smoke tests:");for(let t of e.smokeTests)console.log(` ${t.status.toUpperCase()} ${t.command} - ${t.evidence}`);if(e.indexerRemediation.length>0){console.log(""),console.log("Indexer remediation:");for(let t of e.indexerRemediation){let n=t.after.runnable?"ready":"blocked",r=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${r})`),t.recovery&&console.log(` ${t.recovery}`)}}}function rs(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function fw(e){let t=e.steps.find(o=>o.id==="reindex"),n=e.steps.find(o=>o.id==="project-hooks"),r=e.steps.find(o=>o.id==="agent-guidance"),i=e.steps.find(o=>o.id==="watch-refresh");return[{id:"reindex",command:"scip-query reindex",status:e.reindexResult?"pass":t?.status==="failed"?"fail":"unavailable",evidence:e.reindexResult?`${e.reindexResult.languages.join(", ")} indexed${e.reindexResult.reused?" from cache":""}.`:t?.message??"No reindex result was produced."},{id:"status",command:"scip-query status",status:e.freshness.state==="fresh"?"pass":"fail",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"scip-query config-validate",status:yw(e.steps),evidence:bw(e.steps)},{id:"capabilities",command:"scip-query capabilities",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?`${e.capabilities.matrix.length} language capability row(s) available.`:"No detected languages produced capability rows."},{id:"capability-matrix",command:"scip-query capability-matrix --json",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?Sw(e.capabilities):"No detected languages produced capability rows."},{id:"health",command:"scip-query health",status:e.health.score===null?"unavailable":"pass",evidence:e.health.score===null?e.health.unavailableReason??"Health report was not available.":`Health score ${e.health.score}.`},{id:"diff-impact",command:"scip-query diff-impact --json",status:Rm(e.readiness,e.freshness),evidence:km(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:Rm(e.readiness,e.freshness),evidence:km(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:vw(e.capabilities),evidence:xw(e.capabilities)},{id:"setup-hooks",command:"scip-query setup-hooks",status:e.hooksResult?"pass":n?.status==="failed"?"fail":"unavailable",evidence:e.hooksResult?`${e.hooksResult.installed.length} installed, ${e.hooksResult.updated.length} updated, ${e.hooksResult.unchanged.length} already configured.`:n?.message??"Project agent hooks were not configured."},{id:"watch-refresh",command:"scip-query status --json",status:i?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",evidence:i?.message??"Watch refresh policy was not evaluated."},{id:"rust-semantic-session",command:"scip-query status --json",status:e.rustSemanticSession===null?"unavailable":e.rustSemanticSession.valid?"pass":"fail",evidence:e.rustSemanticSession===null?"Rust was not detected.":`${e.rustSemanticSession.transport}/${e.rustSemanticSession.state}; ${e.rustSemanticSession.fallback} fallback; ${e.rustSemanticSession.optOut}.`},{id:"setup-agent",command:"scip-query setup-agent",status:e.agentResult?"pass":r?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:r?.message??"Project agent guidance was not written."}]}function gw(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function hw(e){let t=e.filter(i=>i.status==="pass").length,n=e.filter(i=>i.status==="unavailable").length,r=e.filter(i=>i.status==="fail").length;return`${t} passed, ${n} unavailable, ${r} failed.`}function yw(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function bw(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function Sw(e){let t=e.matrix.filter(n=>[n.indexing,n.sourceFacts,n.semantic,n.cleanupVerification].some(r=>r.status==="unavailable")).length;return`${e.matrix.length} language row(s), ${t} with unavailable capability cells.`}function Rm(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function km(e,t){if(!e.gitAvailable)return"Git is not available for this project.";let n=t.lastRefresh?` Last refresh: ${t.lastRefresh.result} by ${t.lastRefresh.trigger.kind} at ${t.lastRefresh.completedAt}.`:"";return`Git is available and index freshness is ${t.state}: ${t.reason}${n}`}function vw(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function xw(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(i=>i.cleanupVerification.status==="available").length,n=e.matrix.filter(i=>i.cleanupVerification.status==="partial").length,r=e.matrix.filter(i=>i.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${r} unavailable cleanup-verification row(s).`}function Rw(e,t,n){let r=[];if(t.languages.length===0)return q(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),r;for(let s of t.indexers){if(s.runnable)continue;let a=kt(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=Gr(a,m=>c.push(m)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let u=kw(nr(a,e));r.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:d,before:s,after:u,messages:c,recovery:u.runnable?void 0:u.note??u.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(r.length===0)return q(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),r;let i=r.filter(s=>!s.after.runnable),o=r.filter(s=>s.attempted);return q(n,{id:"indexer-remediation",label:"Indexer remediation",status:i.length>0?"warn":"ok",message:i.length===0?`${o.length} install attempt(s); all detected indexers are runnable.`:`${o.length} install attempt(s); ${i.length} indexer(s) still blocked.`,details:r.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),r}function kw(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function ww(e,t){if(!uw(e)){let n="Skipped because no SQLite index database exists yet.";return q(t,{id:"health",label:"Health audit",status:"skipped",message:n}),os(n)}try{let n=await yr({full:!0,json:!0});return q(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),Cw(n)}catch(n){let r=Yt(n);return q(t,{id:"health",label:"Health audit",status:"failed",message:r}),os(r)}}function $w(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return q(e,{id:"health",label:"Health audit",status:"skipped",message:t}),os(t)}function Cw(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(Pw),warnings:e.warnings??[]}}function Pw(e){return{category:e.category,description:e.description,count:e.count,impact:e.impact,effort:e.effort,evidence:e.evidence,locRecoverable:e.locRecoverable,confirmationStatus:"unconfirmed",safeForAgentToStart:!1,recommendedNextStep:"Run scip-audit to confirm this signal; use scip-improve when the user wants confirmed issues fixed autonomously."}}function os(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function is(e,t){return e.some(n=>n.status==="failed")?"blocked":t.indexers.some(n=>!n.runnable)||e.some(n=>n.status==="warn"||n.status==="skipped")?"partial":"ready"}function Tw(e){let t=e.matrix.flatMap(n=>[n.indexing.status,n.sourceFacts.status,n.semantic.status,n.cleanupVerification.status]);return t.some(n=>n==="unavailable")||t.some(n=>n==="partial")?"warn":"ok"}function Ew(e){return e.matrix.length===0?"No language capability rows.":`${e.matrix.filter(n=>n.indexing.status==="available").length}/${e.matrix.length} language(s) have available indexing.`}function q(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Yt(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as Iw}from"readline";function Aw(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function jw(e,t,n){if(n.length===0)return e;if(t==="up")return{...e,cursor:(e.cursor-1+n.length)%n.length};if(t==="down")return{...e,cursor:(e.cursor+1)%n.length};let r=n[e.cursor]?.id;if(!r)return e;let i=new Set(e.selected);return i.has(r)?i.delete(r):i.add(r),{...e,selected:i}}async function Pm(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=Aw(e);Iw(t);let i=t.isRaw;t.setRawMode(!0),t.resume();let o=(s=!1)=>{s||n.write(`\x1B[${e.length+3}A`),n.write(`scip-query setup
352
- `),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
353
-
354
- `),e.forEach((a,c)=>{let l=c===r.cursor?"\u203A":" ",d=r.selected.has(a.id)?"\u25CF":"\u25CB";n.write(`${l} ${d} ${a.label} [${a.scope}]\x1B[K
355
- `)}),n.write("\x1B[K")};o(!0);try{return await new Promise((s,a)=>{let c=(d,u)=>{if(u.ctrl&&u.name==="c"){l(),a(new Error("Setup cancelled."));return}if(u.name==="return"||u.name==="enter"){l(),n.write(`
356
- `),s(r.selected);return}let m=u.name==="up"?"up":u.name==="down"?"down":u.name==="space"?"toggle":null;m&&(r=jw(r,m,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!i),t.pause()}}import{existsSync as Tm,mkdirSync as Lw,writeFileSync as Dw}from"fs";import{dirname as Ow,join as Em}from"path";function Im(e,t={}){let n=Em(e,".github","workflows","scip-query.yml"),r=Mw({hasNpmProject:Tm(Em(e,"package.json"))});return Tm(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(Lw(Ow(n),{recursive:!0}),Dw(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function Mw(e){let t=`scip-query@${ye}`;return`name: scip-query
357
-
358
- # Generated by scip-query setup-ci.
359
- # Install the language indexers your repository needs before the reindex step
360
- # if they are not already provided by your dependency install.
361
-
362
- on:
363
- pull_request:
364
-
365
- jobs:
366
- diff-gate:
367
- runs-on: ubuntu-latest
368
- steps:
369
- - uses: actions/checkout@v4
370
- with:
371
- fetch-depth: 0
372
- - uses: actions/setup-node@v4
373
- with:
374
- node-version: 22
375
- - uses: actions/cache@v4
376
- with:
377
- path: ~/.cache/scip-query
378
- key: scip-query-\${{ runner.os }}-\${{ hashFiles('package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb', 'Cargo.lock', 'go.sum', 'poetry.lock', 'uv.lock') }}
379
- ${e.hasNpmProject?` - run: npm ci
380
- `:[" # TODO: install this repository's dependencies before indexing."," # This project did not have a package.json when the workflow was generated."].join(`
381
- `)+`
382
- `} - run: npx ${t} reindex
383
- - run: npx ${t} diff-gate --base "origin/\${{ github.base_ref }}"
384
- `}import{existsSync as Fw}from"fs";import{join as ti}from"path";function Am(e){let t=e.global===!0,n=e.project===!0,r=!t&&!n,i=t||r,o=n||r,s={dryRun:e.dryRun===!0};return i&&(s.global=hu({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=Nw(e.projectRoot,{dryRun:e.dryRun})),s}function Nw(e,t={}){return{hooks:Wt(e,{remove:!0,dryRun:t.dryRun}),agentSetup:_d(e,{dryRun:t.dryRun}),left:_w(e)}}function _w(e){return[[".scipquery.json",ti(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",ti(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",ti(e,".scipquery","ledger")],["docs/scip-query/",ti(e,"docs","scip-query")]].filter(([,t])=>Fw(t)).map(([t])=>t)}import{existsSync as Bw}from"fs";import{createRequire as qw}from"module";import ri from"path";import{performance as ni}from"perf_hooks";var Vw=qw(import.meta.url),On;function Mm(e){let t=Ww();if(!t)return or("typescript is not installed");let n=Sa(e);if(n.length===0)return or("no tsconfig found");try{return new ss(e.config.projectRoot,t,n.map(r=>Hw(t,r)))}catch(r){return or(r instanceof Error?r.message:String(r),n[0],n)}}function Fm(e,t,n){let r=ni.now(),i=jm(t,e),o=ni.now()-r,s=ni.now(),a=jm(n,e),c=ni.now()-s,l=[],d=0,u=0,m=0,g=0,f=0;for(let h of e){let S=i.get(h.symbolId)??[],y=a.get(h.symbolId)??[];u+=S.length,m+=y.length;let v=Lm(S),w=Lm(y),R=Dm(S,w),j=Dm(y,v);if(R.length===0&&j.length===0){d+=1;continue}g+=R.length,f+=j.length,l.push({symbol:h.symbol,missing:R,extra:j})}return{slot:"semantic-references",definitions:e.length,matches:d,mismatchCount:l.length,missingReferenceCount:g,extraReferenceCount:f,baselineReferenceCount:u,candidateReferenceCount:m,baselineMs:Number(o.toFixed(3)),candidateMs:Number(c.toFixed(3)),mismatches:l}}var ss=class{constructor(t,n,r){this.projectRoot=t;this.ts=n;this.bundles=r}projectRoot;ts;bundles;language="typescript";referencesCache=new Map;availability(){return{available:!0,tsconfigPath:this.bundles[0]?.tsconfigPath,tsconfigPaths:this.bundles.map(t=>t.tsconfigPath)}}importUsage(t){return[]}referencesFor(t){let n=this.referencesCache.get(t.symbolId);if(n)return n;let r=this.computeReferences(t);return this.referencesCache.set(t.symbolId,r),r}referencesForDefinitions(t){let n=new Map;for(let r of t)n.set(r.symbolId,this.referencesFor(r));return n}calleesFor(t){return[]}signatureFor(t){return null}computeReferences(t){let n=ri.join(this.projectRoot,t.relativePath),r=this.bundleForFile(n);if(!r)return[];let i=r.service.getProgram()?.getSourceFile(n);if(!i)return[];let o=Uw(this.ts,i,t);if(o===null)return[];let s=r.service.findReferences(n,o)??[],a=[];for(let c of s)for(let l of c.references){let d=Jw(this.ts,r.service,this.projectRoot,l);d&&(d.file===t.relativePath&&d.line>=t.startLine&&d.line<=t.endLine||a.push(d))}return ya(a)}bundleForFile(t){let n=_m(t);return this.bundles.find(r=>r.files.has(n))??null}};function Ww(){if(On!==void 0)return On;try{On=Vw("typescript")}catch{On=null}return On}function Hw(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(Om(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,ri.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>Om(e,s)).join(`
385
- `));let i=new Set(r.fileNames.map(_m)),o=e.createLanguageService(Gw(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function Gw(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?ri.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(Bw(n))return e.ScriptSnapshot.fromString(U(n,{maxBytes:Re,inputKind:"TypeScript language-service source file"}))},getScriptVersion:()=>"0",readDirectory:e.sys.readDirectory,readFile:e.sys.readFile,fileExists:e.sys.fileExists,directoryExists:e.sys.directoryExists,realpath:e.sys.realpath,useCaseSensitiveFileNames:()=>e.sys.useCaseSensitiveFileNames}}function Uw(e,t,n){let r=t.text.split(`
386
- `),i=Math.max(0,n.startLine),o=Math.min(r.length-1,Math.max(n.endLine,n.startLine));for(let s=i;s<=o;s+=1){let a=r[s]?.indexOf(n.leaf)??-1;if(a>=0)return e.getPositionOfLineAndCharacter(t,s,a)}return null}function Jw(e,t,n,r){let i=ba(n,r.fileName);if(!i)return null;let o=t.getProgram()?.getSourceFile(r.fileName);if(!o)return null;let s=e.getLineAndCharacterOfPosition(o,r.textSpan.start);return{file:i,line:s.line,column:s.character}}function jm(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function Lm(e){return new Set(e.map(Nm))}function Dm(e,t){return e.filter(n=>!t.has(Nm(n)))}function Nm(e){return`${e.file}:${e.line}:${e.column}`}function _m(e){return ri.resolve(e).replace(/\\/g,"/")}function Om(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
387
- `)}function Bm(e){let t=[],n=U(e,{maxBytes:rn,inputKind:"profile JSONL artifact"});for(let[r,i]of n.split(`
388
- `).entries()){let o=i.trim();if(!o)continue;let s;try{s=JSON.parse(o)}catch(a){throw new Error(`${e}:${r+1}: invalid profile JSON: ${a instanceof Error?a.message:String(a)}`,{cause:a})}if(!s||typeof s!="object"||Array.isArray(s))throw new Error(`${e}:${r+1}: profile event must be a JSON object`);t.push(s)}return t}function qm(e,t={}){let n=new Map,r=new Map,i=new Map,o=new Set,s=new Set,a=new Set,c=new Set,l=0,d=0,u=0;for(let[S,y]of e.entries()){let v=Ce(y.name)??Ce(y.phase),w=e$(y.durationMs),R=Ce(y.runId);v&&w!==null&&(l+=1,s.add(v),R&&o.add(R),Kw(i,y,v,w),zw(r,y,v,w,R),Ce(y.subsystemWorkIdentity)&&c.add(v));let j=Ce(y.workIdentity);if(!j)continue;d+=1,v&&a.add(v);let P=Zw(y.workOutcome);if(!v||w===null||!P){u+=1;continue}let G=R??`unknown-run-${S}`,A=JSON.stringify([v,j]),M=n.get(A)??{spanName:v,workIdentity:j,observations:[]};M.observations.push({runId:G,command:Ce(y.command)??"unknown",durationMs:w,outcome:P}),n.set(A,M)}let m=[...n.values()].map(Qw).filter(S=>S!==null).sort((S,y)=>y.estimatedAvoidableMs-S.estimatedAvoidableMs||y.repeatComputations-S.repeatComputations||S.spanName.localeCompare(y.spanName)||S.workIdentity.localeCompare(y.workIdentity)),g=[...r.values()].map(Yw).filter(S=>S!==null).sort((S,y)=>y.laterRunMs-S.laterRunMs||y.laterRunEvents-S.laterRunEvents||S.spanName.localeCompare(y.spanName)),f=[...i.values()].map(Xw).sort((S,y)=>y.totalDurationMs-S.totalDurationMs||S.subsystem.localeCompare(y.subsystem)),h=t.top??20;return{profileEvents:e.length,spanEvents:l,distinctSpanNames:s.size,instrumentedEvents:d,unclassifiedInstrumentedEvents:u,exactIdentifiedSpanNames:a.size,workloadIdentifiedEvents:f.reduce((S,y)=>S+y.workloadIdentifiedEvents,0),workloadIdentifiedSpanNames:c.size,runCount:o.size,repeatedGroups:m.length,largestOpportunityMs:m[0]?.estimatedAvoidableMs??0,rows:m.slice(0,h),repeatedWorkloads:g.length,largestRepeatedWorkloadMs:g[0]?.laterRunMs??0,workloadRows:g.slice(0,h),subsystemCoverage:f}}function Vm(e,t){let n=["scip-query work-audit",`Profile: ${t}`,`Profile events: ${e.profileEvents}; spans: ${e.spanEvents}; distinct span names: ${e.distinctSpanNames}; runs: ${e.runCount}`,`Subsystem identity coverage: ${e.workloadIdentifiedSpanNames}/${e.distinctSpanNames} span names, ${e.workloadIdentifiedEvents}/${e.spanEvents} events`,`Exact identity coverage: ${e.exactIdentifiedSpanNames}/${e.distinctSpanNames} span names, ${e.instrumentedEvents}/${e.spanEvents} events`,`Repeated work groups: ${e.repeatedGroups}; largest measured opportunity: ${e.largestOpportunityMs}ms`,""];if(e.rows.length===0)n.push("No exact repeated computations were found in work-identified profile events."),e.instrumentedEvents===0&&n.push("This profile predates exact work identities or its spans have not been instrumented yet.");else{n.push("Exact repeated computations:"),n.push("avoidableMs withinRunMs crossRunMs repeats runs span workIdentity commands");for(let r of e.rows)n.push([r.estimatedAvoidableMs,r.withinRunAvoidableMs,r.crossRunRecomputeMs,r.repeatComputations,r.runCount,r.spanName,r.workIdentity,r.commands.join(", ")].join(" "))}if(n.push("",`Repeated subsystem workloads: ${e.repeatedWorkloads}`),e.workloadRows.length===0)n.push("No named subsystem workload was observed in more than one run.");else{n.push("laterRunMs firstRunMs laterEvents runs subsystem span subsystemWorkIdentity commands");for(let r of e.workloadRows)n.push([r.laterRunMs,r.firstRunMs,r.laterRunEvents,r.runCount,r.subsystem,r.spanName,r.subsystemWorkIdentity,r.commands.join(", ")].join(" "))}return n.push("","Rows are independent measurements; nested spans can overlap and must not be summed."),n.push("Within-run time is direct duplication. Cross-run time is a durable-cache opportunity that still needs safe invalidation."),n.push("Subsystem workload time is an aggregate observation against the same command/project inputs, not proven avoidable time."),`${n.join(`
389
- `)}
390
- `}function Kw(e,t,n,r){let i=Ce(t.subsystem)??n.split(/[.:]/,1)[0]??n,o=e.get(i)??{subsystem:i,events:0,totalDurationMs:0,spanNames:new Set,workloadIdentifiedEvents:0,workloadIdentifiedSpanNames:new Set,exactIdentifiedEvents:0,exactIdentifiedSpanNames:new Set};o.events+=1,o.totalDurationMs+=r,o.spanNames.add(n),Ce(t.subsystemWorkIdentity)&&(o.workloadIdentifiedEvents+=1,o.workloadIdentifiedSpanNames.add(n)),Ce(t.workIdentity)&&(o.exactIdentifiedEvents+=1,o.exactIdentifiedSpanNames.add(n)),e.set(i,o)}function zw(e,t,n,r,i){let o=Ce(t.subsystemWorkIdentity);if(!o||!i||t.workloadIdentityKind!=="published-project")return;let s=Ce(t.subsystem)??n.split(/[.:]/,1)[0]??n,a=JSON.stringify([n,o]),c=e.get(a)??{subsystem:s,spanName:n,subsystemWorkIdentity:o,observations:[]};c.observations.push({runId:i,command:Ce(t.command)??"unknown",durationMs:r}),e.set(a,c)}function Yw(e){let t=new Map;for(let o of e.observations){let s=t.get(o.runId)??[];s.push(o),t.set(o.runId,s)}let n=[...t.values()];if(n.length<2)return null;let r=n[0],i=n.slice(1).flat();return{subsystem:e.subsystem,spanName:e.spanName,subsystemWorkIdentity:e.subsystemWorkIdentity,commands:[...new Set(e.observations.map(o=>o.command))].sort(),runCount:n.length,totalEvents:e.observations.length,firstRunEvents:r.length,laterRunEvents:i.length,totalDurationMs:Xt(e.observations.map(o=>o.durationMs)),firstRunMs:Xt(r.map(o=>o.durationMs)),laterRunMs:Xt(i.map(o=>o.durationMs))}}function Xw(e){return{subsystem:e.subsystem,events:e.events,totalDurationMs:e.totalDurationMs,spanNames:[...e.spanNames].sort(),workloadIdentifiedEvents:e.workloadIdentifiedEvents,workloadIdentifiedSpanNames:e.workloadIdentifiedSpanNames.size,exactIdentifiedEvents:e.exactIdentifiedEvents,exactIdentifiedSpanNames:e.exactIdentifiedSpanNames.size}}function Qw(e){let t=e.observations.filter(a=>a.outcome==="computed");if(t.length<2)return null;let n=new Map;for(let a of t){let c=n.get(a.runId)??[];c.push(a),n.set(a.runId,c)}let r=[...n.values()],i=Xt(r.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=Xt(r.slice(1).map(a=>a[0]?.durationMs??0)),s=[...new Set(e.observations.map(a=>a.command))].sort();return{spanName:e.spanName,workIdentity:e.workIdentity,commands:s,computations:t.length,runCount:r.length,repeatComputations:t.length-1,withinRunRepeats:t.length-r.length,crossRunRecomputes:Math.max(0,r.length-1),totalComputeMs:Xt(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:i,crossRunRecomputeMs:o,estimatedAvoidableMs:i+o,cacheHits:ii(e.observations,"cache-hit"),cacheMisses:ii(e.observations,"cache-miss"),reused:ii(e.observations,"reused"),skipped:ii(e.observations,"skipped")}}function Zw(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function ii(e,t){return e.filter(n=>n.outcome===t).length}function e$(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Ce(e){return typeof e=="string"&&e.length>0?e:null}function Xt(e){return e.reduce((t,n)=>t+n,0)}var Wm={status:"experimental-composite",comparableAcrossLanguages:!1,scope:"completed-analyses-only",note:"The score summarizes analyses that completed under the attached capability matrix. It is not normalized across languages or frameworks and is not suitable for a public leaderboard."};function Hm(e,t){let n=t$(t);return{...e,warnings:[...e.warnings??[],Wm.note,...n],capabilities:t,scoreInterpretation:Wm}}function t$(e){return e.matrix.flatMap(t=>{let n=[t.indexing,t.sourceFacts,t.semantic,t.cleanupVerification].map(r=>/syntax only/i.test(r.reason)?`${r.label}=partial (syntax only)`:r.status==="available"?null:`${r.label}=${r.status}`).filter(r=>r!==null);return n.length===0?[]:[`${t.language} capability limits: ${n.join(", ")}. Unsupported analyses are not clean zeros.`]})}import{basename as n$,join as r$}from"path";var Mn=class extends Error{constructor(n,r,i){super(`${n} ${i?`Current revision: ${i}. Retry with --replace ${i} after reviewing it.`:"The suppression file was left untouched."}`);this.path=r;this.currentRevision=i;this.name="SuppressionWriteConflictError"}path;currentRevision};function Km(e,t,n={}){let r=n instanceof Date?{now:n}:n,i=o$(t),o=s$(r.expectedRevision),s=r$(Ec(e),Ic(i)),a=r.now??new Date,c="unchanged",l=ht(s,d=>{if(!d.revision.exists){if(o)throw new Mn(`Cannot replace ${s}: the observed suppression no longer exists.`,s);return c="created",{kind:"write",text:Jm(Gm(i,void 0,a,r.toolVersion))}}let u=i$(d);if(a$(u.suppression,i))return c="unchanged",{kind:"unchanged"};if(!o)throw new Mn(`A different suppression decision already exists at ${s}.`,s,d.revision.hash);if(o!==d.revision.hash)throw new Mn(`Suppression ${s} changed after the revision you reviewed.`,s,d.revision.hash);return c="replaced",{kind:"write",text:Jm(Gm(i,u.suppression,a,r.toolVersion))}},{maxRetries:0,onBeforeCommit:r.onBeforeCommit});return{path:s,disposition:c,revision:l.current.revision.hash}}function i$(e){let t;try{t=JSON.parse(e.text)}catch(r){throw new Error(`Cannot update ${e.path}: the existing suppression is malformed JSON.`,{cause:r})}let n=jc(t,c$(e.path));if("error"in n)throw new Error(`Cannot update ${e.path}: ${n.error}.`);return n}function Gm(e,t,n,r=ye){let i=n.toISOString();return{kind:Pc,schemaVersion:Tc,suppressionIdentity:Ac(e),writer:{tool:"scip-query",version:r},...e,createdAt:t?.createdAt??e.createdAt??i,...t?{updatedAt:i}:{}}}function o$(e){let t=e.reason?.trim();if(!t)throw new Error("suppression requires a non-empty reason");let n=e.id?.trim(),r=e.check?.trim();if(!n&&!r)throw new Error("suppression requires an id or a check");return{...n?{id:n}:{},...r?{check:r}:{},...e.file?{file:e.file}:{},reason:t,...e.expiresAt?{expiresAt:e.expiresAt}:{},...e.createdAt?{createdAt:e.createdAt}:{}}}function s$(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Error("--replace requires the 64-character SHA-256 revision reported by suppress.");return t}function a$(e,t){return JSON.stringify(Um(e))===JSON.stringify(Um(t))}function Um(e){let{createdAt:t,...n}=e;return n}function c$(e){let t=n$(e);return t.endsWith(".json")?t.slice(0,-5):t}function Jm(e){return`${JSON.stringify(e,null,2)}
391
- `}var g$=new Set(Ms),h$=18e4,Zm=100*1024*1024,y$=new Set(Gs),b$=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],S$=[["health","--json"],["dead","--json","--full"],["isolated","--json","--full"],["similar","--json","--full"],["similar-files","--json","--full"],["recent-duplicates","--json","--full"],["doc-drift","--json","--full"],["unused-params","--json","--full"],["wrapper-candidates","--json","--full"],["passthrough-candidates","--json","--full"],["stale-abstractions","--json","--full"],["incomplete-migration","--json","--full"],["cleanup-plan","--verify","--json"],["complexity-hotspots","--json","--full"]];function v$(e){return e.filter(t=>g$.has(t))}async function ef(e){let t=X(e),n=re(),r=ke(n),i=He(n,r),o=b(t,"json");try{let s=v$(_t(t,"language")),a=await zt({projectRoot:n,languages:s.length>0?s:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:b(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,clojureConfigPath:r.indexer?.clojure?.configPath,skipIfUnchanged:!b(t,"force"),allowPartial:b(t,"allowPartial"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",installMissing:b(t,"installMissing"),trustProjectTools:b(t,"trustProjectTools"),indexerConcurrency:Q(t,"indexerConcurrency")??r.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...o?{onStatus:()=>{}}:{}});if(o){I("reindex",[],t,a);return}console.log(`${a.reused?"Reused":"Indexed"} ${a.languages.join(", ")} in ${(a.durationMs/1e3).toFixed(1)}s`)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exit(1)}}function tf(){let e=re(),t=Ft(e);try{let n=Fr({projectRoot:e,dbPath:t,onStatus:r=>console.log(r)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function nf(e){let t=X(e),n=re(),r=Ft(n);try{let i=await Uo({projectRoot:n,dbPath:r,tsconfig:$(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${i.vueFiles}; resolved references: ${i.resolvedReferences}; inserted mentions: ${i.insertedMentions}; not-inserted identifier tokens: ${i.skippedReferences}; synthetic symbols: ${i.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${i.skippedReferenceReasons["no-definition"]}; same-file definition ${i.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${i.skippedReferenceReasons["unindexed-definition"]}; missing source ${i.skippedReferenceReasons["missing-source-file"]}; missing service script ${i.skippedReferenceReasons["missing-service-script"]}. Samples: ${i.skippedReferenceSamples.length} omitted, ${i.resolvedReferenceSamples.length} resolved.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function rf(e){let t=X(e);ue(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=mc(n,{base:$(t,"base")}),o=fc(n,r,i.changedFiles,i.changedRanges);gr(yn,o)})}function of(){let e=fd(process.env[xt]);ue(t=>{gr(Rt,md(t,e))})}async function sf(e){let t=X(e);try{let n=await Ol({base:$(t,"base")});if(b(t,"json")){I("diff-impact",[],t,n);return}Ml(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function af(e,t){let n=X(t),r=String(e).split(",").filter(i=>i.length>0);ue(i=>{let o=[];for(let c of r)zc.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:$(n,"scope"),full:b(n,"full")},a=o.length===1?Yc(i,o[0],s):Xc(i,o,s);gr(hn,a)})}async function cf(e){let t=X(e);if(b(t,"writeBaseline")||b(t,"baseline")){O$(t);return}try{let n=await yr({scope:$(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:r,config:i,dbPath:o}=Ge(),s=ot($e(r,i),{hasIndexedGraph:se(o)}),a=Hm(n,s);if(b(t,"json")){I("health",[],t,a);return}Dl(a)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function lf(e){let t=X(e),n=re(),r=Q(t,"timeoutMs")??h$,i=b(t,"progress"),o=b(t,"profile"),s=$(t,"profileOut"),a={projectRoot:n,...A$(n),index:cs(se(Ft(n))),commands:[]};b(t,"coldIndex")&&(Qt(i,"cold index started"),a.coldIndex=await x$(n),Qt(i,`cold index finished ${a.coldIndex.durationMs}ms`),cn({type:"bench-index",phase:"cold-index",projectRoot:n,durationMs:a.coldIndex.durationMs,result:a.coldIndex.result,files:a.coldIndex.files,symbols:a.coldIndex.symbols},s),Qt(i,"warm index started"),a.warmIndex=await C$(n),Qt(i,`warm index finished ${a.warmIndex.durationMs}ms`),cn({type:"bench-index",phase:"warm-index",projectRoot:n,durationMs:a.warmIndex.durationMs,result:a.warmIndex.result,files:a.warmIndex.files,symbols:a.warmIndex.symbols},s),a.index=cs(se(Ft(n))));for(let c of P$(t))a.commands.push(E$(n,c,r,{progress:i,profile:o,profileOut:s}));if(b(t,"json")){I("bench",[],t,a);return}j$(a)}function df(e,t){let n=X(t),r=f$(String(e)),i=qm(Bm(r),{top:Q(n,"top")??20});if(b(n,"json")){I("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(Il(Vm(i,r)))}function uf(e){let t=X(e);ue(n=>{let r=n.config.projectRoot,i=$(t,"scope")??null,o=b(t,"full"),s=Q(t,"limit")??200,a=Math.max(0,Q(t,"maxMismatches")??10),c=Ys(n).filter(w=>mn(w.relativePath)).filter(w=>!n.isIgnored(w.relativePath)).sort(D$),l=i?c.filter(w=>w.relativePath.includes(i)):c,d=o?l:l.slice(0,s),u=lt.now(),m=xa(n),g=Number((lt.now()-u).toFixed(3)),f=lt.now(),h=Mm(n),S=Number((lt.now()-f).toFixed(3)),y=Fm(d,m,h),v={projectRoot:r,selection:{scope:i,full:o,limit:o?null:s,maxMismatchDetails:a,totalTypeScriptDefinitions:c.length,scopedDefinitions:l.length,comparedDefinitions:d.length},baseline:{provider:"ts-morph",createMs:g,availability:m.availability()},candidate:{provider:"tsserver",createMs:S,availability:h.availability()},comparison:{...y,mismatches:y.mismatches.slice(0,a)}};if(b(t,"json")){I("typescript-semantic-compare",[],t,v);return}L$(v)})}async function x$(e){let t=ke(e),n=He(e,t),r=si(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;R$(e,r);let o=k$(e,r,i);rl(e,r);try{let s=await mf(()=>zt({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench --cold-index"},onStatus:()=>{}}));return zm(e,r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...ff(e)}}catch(s){throw zm(e,r,i,o,"restore-backup"),s}}function oi(e){return Ct(nl(),"bench-restores",`${il(e)}.json`)}function R$(e,t){let n=oi(t);if(!se(n))return!1;let r=pf(V(n,"benchmark restore marker")),i=u$(e),o=cr(t);if(!r||r.canonicalProjectRoot!==i||r.originalCachePath!==o||oi(r.originalCachePath)!==n)throw new Error(`refusing invalid cold-index restore marker ${n}`);return se(r.backupPath)?(Fi(e,r.backupPath,r.originalCachePath,r.ownerSha256),se(r.originalCachePath)&&(ft(e,r.originalCachePath),as(r.originalCachePath,{recursive:!0,force:!0})),ls(r.backupPath,r.originalCachePath),ft(e,r.originalCachePath)):se(r.originalCachePath)&&ft(e,r.originalCachePath),ds(n),!0}function k$(e,t,n){if(!se(t))return!1;let r=ft(e,t),i=w$(r.record.canonicalCacheDir,n);if(se(i))throw new Error(`refusing existing cold-index backup ${i}`);let o=oi(r.record.canonicalCacheDir),s={schemaVersion:1,canonicalProjectRoot:r.record.canonicalProjectRoot,originalCachePath:r.record.canonicalCacheDir,backupPath:i,ownerSha256:r.ownerSha256};$$(o),p$(o,`${JSON.stringify(s,null,2)}
392
- `,{flag:"wx",mode:384});try{ls(r.physicalCacheDir,i)}catch(a){throw ds(o),a}return!0}function zm(e,t,n,r,i){if(!r)return;let o=oi(t),s=pf(V(o,"benchmark restore marker"));if(!s||s.backupPath!==n||s.originalCachePath!==cr(t))throw new Error(`refusing invalid cold-index restore marker ${o}`);Fi(e,n,s.originalCachePath,s.ownerSha256),i==="restore-backup"?(se(t)&&(ft(e,t),as(t,{recursive:!0,force:!0})),ls(n,s.originalCachePath),ft(e,s.originalCachePath)):as(n,{recursive:!0,force:!0}),ds(o)}function pf(e){try{let t=JSON.parse(e);return t.schemaVersion===1&&typeof t.canonicalProjectRoot=="string"&&typeof t.originalCachePath=="string"&&typeof t.backupPath=="string"&&typeof t.ownerSha256=="string"&&/^[a-f0-9]{64}$/.test(t.ownerSha256)?t:null}catch{return null}}function w$(e,t){let n=`${e}.bench-backup-`,r=cr(t);if(!r.startsWith(n)||!/^\d+$/.test(r.slice(n.length)))throw new Error(`refusing cold-index backup outside the owned cache namespace: ${t}`);return r}function $$(e){let t=si(e);d$(t,{recursive:!0,mode:448}),process.platform!=="win32"&&l$(t,448)}async function C$(e){let t=ke(e),n=He(e,t),r=await mf(()=>zt({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench warm index"},onStatus:()=>{}}));return{durationMs:r.durationMs,result:r.value.reused?"reused":"rebuilt",languages:r.value.languages,...ff(e)}}async function mf(e){let t=lt.now(),n=await e();return{durationMs:Math.round(lt.now()-t),value:n}}function ff(e){return se(Ft(e))?ue(t=>{let n=Dt(t);return{files:n.documents,symbols:n.symbols}}):{}}function P$(e){let t=_t(e,"command");return t.length>0?t.map(T$).filter(n=>n.length>0):[...b$.map(n=>[...n]),...b(e,"includeHeavy")?S$.map(n=>[...n]):[]]}function T$(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function E$(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;Qt(r.progress,`${i} started`),cn({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=lt.now(),s={...r.profile?I$(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=Qm(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:Zm,timeout:n}),c=Math.round(lt.now()-o),l={command:i,durationMs:c,exitCode:a.status,signal:a.signal,timedOut:a.error?.code==="ETIMEDOUT"||a.error?.name==="ETIMEDOUT",stdoutBytes:a.stdout?.length??0,stderrBytes:a.stderr?.length??0,...r.profileOut?{profilePath:r.profileOut}:{}};return Qt(r.progress,`${i} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),cn({type:"bench-command-finish",command:i,projectRoot:e,durationMs:c,exitCode:l.exitCode,signal:l.signal,timedOut:l.timedOut,stdoutBytes:l.stdoutBytes,stderrBytes:l.stderrBytes},r.profileOut),l}function Qt(e,t){e&&process.stderr.write(`[bench] ${Wi(t)}
393
- `)}function I$(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function A$(e){let t=Qm("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:Zm,timeout:3e4,killSignal:"SIGKILL"});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
394
- `).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(r=>y$.has(m$(r).toLowerCase())).length}}function j$(e){console.log("scip-query bench"),console.log(`Project: ${e.projectRoot}`),console.log(`Repo files: ${e.repoFiles??"unknown"}; source-like files: ${e.sourceFiles??"unknown"}`),e.index&&console.log(`Index: ${e.index.files} files, ${e.index.symbols} symbols, ${Ue(e.index.indexSizeBytes)}`),e.coldIndex&&Ym("Cold index",e.coldIndex),e.warmIndex&&Ym("Warm index",e.warmIndex),console.log(`
395
- Commands:`);for(let t of[...e.commands].sort((n,r)=>r.durationMs-n.durationMs)){let n=t.timedOut?"timeout":t.exitCode===0?"ok":`exit ${t.exitCode??t.signal??"unknown"}`;console.log(` ${String(t.durationMs).padStart(7)}ms ${n.padEnd(10)} ${String(t.stdoutBytes).padStart(8)}B out ${t.command}`)}}function Ym(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function L$(e){if(console.log("TypeScript semantic provider comparison"),console.log(`Project: ${e.projectRoot}`),console.log(`Definitions: ${e.selection.comparedDefinitions}/${e.selection.scopedDefinitions} compared`+(e.selection.scope?`, scope ${e.selection.scope}`:"")),console.log(`ts-morph: create ${e.baseline.createMs}ms, refs ${e.comparison.baselineMs}ms, refs ${e.comparison.baselineReferenceCount}`),console.log(`tsserver: create ${e.candidate.createMs}ms, refs ${e.comparison.candidateMs}ms, refs ${e.comparison.candidateReferenceCount}`),console.log(`Matches: ${e.comparison.matches}; mismatches: ${e.comparison.mismatchCount}; missing refs: ${e.comparison.missingReferenceCount}; extra refs: ${e.comparison.extraReferenceCount}`),e.comparison.mismatches.length!==0){console.log(`
396
- Mismatch samples:`);for(let t of e.comparison.mismatches)console.log(` ${t.symbol}`),console.log(` missing=${t.missing.length} extra=${t.extra.length}`)}}function D$(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function O$(e){let t=$(e,"scope");ue(n=>{if(b(e,"writeBaseline")){let i=Rc(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=kc(n,{scope:t});if(r.fixedFindings.length>0&&console.log(`${r.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),r.newFindings.length===0){console.log(`OK: no new findings vs baseline (${r.baselineCount} baselined, ${r.current.length} current).`);return}console.log(`FAIL: ${r.newFindings.length} new finding(s) vs ${r.baselinePath}:`);for(let i of r.newFindings)console.log(` + ${i}`);process.exitCode=1})}function gf(){let e=Or(),t=e.installed.length+e.alreadyLinked.length;console.log(`
397
- ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.pruned.length} pruned, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function hf(e){let t=X(e),n=re(),r=Wt(n,{shared:b(t,"shared"),remove:b(t,"remove"),force:b(t,"force")});if(b(t,"json")){I("setup-hooks",[],t,r);return}for(let o of r.installed)console.log(` done: ${o}`);for(let o of r.updated)console.log(` update: ${o}`);for(let o of r.unchanged)console.log(` ok: ${o} (already configured)`);for(let o of r.removed)console.log(` remove: ${o}`);for(let o of r.gitExcluded)console.log(` local: ${o} (excluded through .git/info/exclude)`);for(let o of r.warnings)console.log(` warning: ${o}`);for(let o of r.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);r.installed.length+r.updated.length+r.unchanged.length>0?(console.log(`
398
- Checkout-local scip-query hooks are configured for this clone and must not be committed.`),console.log("Review new or changed hooks in Codex/Claude Code with /hooks before they run.")):console.log(`
399
- No project-local hook config was written.`)}function yf(){let e=!1;Cn()?console.log("scip CLI: installed"):(fo(),e=!0);let t=re(),n=ke(t),r=$e(t,n);if(r.languages.length===0){console.log(`
400
- No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
401
- Detected languages: ${r.languages.join(", ")}`),console.log(`
402
- Indexer readiness:`);for(let o of r.indexers){let s=o.runnable?" OK":o.installed?" WARN":" MISSING",a=o.resolvedBinary?` (${o.resolvedBinary})`:"";console.log(`${s} ${o.language}: ${o.binaryLabel}${a}`),o.note&&console.log(` ${o.note}`),!o.installed&&o.installUrl&&console.log(` install: ${o.installUrl}`),o.runnable||(e=!0)}let i=Of(r);i.length>0&&console.log(`
403
- Semantic provider readiness:`);for(let o of i){let s=o.available?" OK":o.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${o.language}: ${G$(o)}${Mf(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function bf(e){vf(e,"capabilities")}function Sf(e){b(X(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),vf(e,"capability-matrix")}function vf(e,t){let n=X(e),{projectRoot:r,config:i,paths:o,dbPath:s}=Ge(),a=$e(r,i),c=Me(r,i,o),l=ot(a,{hasIndexedGraph:se(s)&&c.state!=="missing"});if(b(n,"json")){I(t,[],n,l);return}us(l)}function xf(){let e=re(),t=yt(e),n=sl(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Rf(e){let t=X(e),n=re(),r=ke(n),i=Mt(r,{projectRoot:n});if(b(t,"json"))I("config-validate",[],t,{diagnostics:i});else if(i.length===0)console.log("Config OK.");else for(let o of i)console.log(`${o.level.toUpperCase()} ${o.path}: ${o.message}`);i.some(o=>o.level==="error")&&(process.exitCode=1)}function kf(e,t){let n=X(t),r=$(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=Km(re(),{id:String(e),check:$(n,"check"),file:$(n,"file"),reason:r,expiresAt:$(n,"expiresAt")},{expectedRevision:$(n,"replace")});if(b(n,"json")){I("suppress",[String(e)],n,i);return}console.log(`Suppression ${i.disposition} at ${i.path}. Revision: ${i.revision}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exitCode=1}}function wf(e){let t=X(e),n=Date.now(),r=$(t,"since"),i;if(r){let y=um(r,n);if(y===null){console.error(`error: could not parse --since "${r}" (use 30d, 12w, or an ISO date).`),process.exitCode=1;return}i=y}let o=re(),s=wr(o),a=dm(s.events,{sinceMs:i,check:$(t,"check")}),c=nt("Committed outcome history",s.compatibility);if(b(t,"json")){I("effectiveness",[],t,{...a,recordCompatibility:{outcomeEvents:s.compatibility}});return}if(c&&console.log(`WARN: ${c}`),a.checks.length===0){console.log(s.events.length===0?`No outcome events recorded yet (${Ct(Sn,"*.json")} is missing or empty). Events accrue as diff-gate runs; commit the event files so history is shared.`:"No findings match the requested window/check.");return}let l=["check","caught","fixed","suppressed","open","moved","unverified","precision","median-days-to-fix"],d=a.checks.map(y=>[y.check,String(y.caught),String(y.fixed),String(y.suppressed),String(y.open),String(y.moved),String(y.unverified),y.precision===null?"-":`${Math.round(y.precision*100)}%`,y.medianDaysToFix===null?"-":y.medianDaysToFix.toFixed(1)]),u=l.map((y,v)=>Math.max(y.length,...d.map(w=>w[v].length))),m=y=>y.map((v,w)=>v.padEnd(u[w])).join(" ");console.log(m(l));for(let y of d)console.log(m(y));let g=a.checks.reduce((y,v)=>y+v.fixed,0),f=a.checks.reduce((y,v)=>y+v.suppressed,0),h=a.checks.reduce((y,v)=>y+v.unverified,0),S=g+f;S>0?console.log(`
404
- ${g} finding(s) verified fixed against a stable comparison base, ${f} suppressed, ${h} disappeared without comparable evidence \u2014 overall precision ${Math.round(g/S*100)}%.`):h>0&&console.log(`
405
- ${h} finding(s) disappeared without comparable comparison-base evidence; precision is not available.`)}function $f(e){let t=X(e),{report:n,hasIndexerProblems:r,hasErrors:i}=Cf("doctor");b(t,"json")?I("doctor",[],t,n):q$(n,r),process.exitCode=i?1:0}function Cf(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Ge(),o=Mt(n,{projectRoot:t}),s=$e(t,n),a=Me(t,n,r),c=se(i),l=ot(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=Zl(t,n,r),u=s.indexers.some(f=>!f.runnable),m=o.some(f=>f.level==="error")||u||a.state==="missing"||a.state==="stale",g=o.some(f=>f.level==="error")||u||a.state==="missing";return{report:{command:e,projectRoot:t,dbPath:i,configuredDbPath:r.dbPath,exists:c,configDiagnostics:o,readiness:s,freshness:a,capabilities:l,sharedCache:d,ok:!m},hasIndexerProblems:u,hasErrors:g}}function Pf(e){let t=X(e),n=re(),r=Er(n,{gitHook:b(t,"gitHook")});for(let i of r.written)console.log(` done: ${i}`);for(let i of r.unchanged)console.log(` ok: ${i} (already wired)`);for(let i of r.skipped)console.log(` skip: ${i.target} \u2014 ${i.reason}`);console.log(`
406
- Agents reading this project now know to route through the scip-query skills and gate their diffs.`),console.log("Check freshness once per work session. Reuse a fresh generation, let an active watcher refresh after edits, and reindex only when stale and no watcher can refresh it.")}async function Tf(e){let t=X(e);try{let n=b(t,"installMissing"),r={gitHook:b(t,"gitHook"),noHooks:b(t,"noHooks")||t.hooks===!1,dossierDir:$(t,"dossierDir"),runHealth:b(t,"yes")?!1:t.health!==!1,installSkills:t.skills!==!1,installIndexers:n,installAstParsers:n&&t.parsers!==!1,...b(t,"yes")?{automaticRefresh:!0}:{}},i=b(t,"json"),o=!i&&!b(t,"yes")&&process.stdin.isTTY&&process.stdout.isTTY;(b(t,"guided")||o)&&(r=await M$(r,{json:b(t,"json")})),i||(r.onStatus=a=>console.log(` ${a}`));let s=await $m(r);b(t,"json")?I("setup",[],t,s):Cm(s),process.exitCode=s.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function M$(e,t){let{projectRoot:n,config:r}=Ge(),i=$e(n,r),o=wm({files:F$(n),watchEnabled:Oe(r).enabled,readiness:i}),s=i.languages.map(f=>({id:`language:${f}`,scope:"project",label:`Index ${f}`,reason:"Detected in this project.",selected:!0})),a=o.actions.map(f=>({id:f.id,scope:f.scope==="repository"?"project":f.scope,label:f.label,reason:f.reason,selected:f.recommended})),c=ns(i.languages);a.push({id:"install-agent-skills",scope:"user",label:"Install agent skills",reason:"Makes scip-query workflows available to local agents.",selected:!0},...c.length>0?[{id:"install-ast-parsers",scope:"user",label:`Install or repair AST parsers (${c.join(", ")})`,reason:"Installs the Tree-sitter runtime and grammars used for source-level analysis.",selected:!0}]:[],{id:"run-health-analysis",scope:"analysis",label:"Run full health analysis and write dossier",reason:"Optional and can take much longer than indexing.",selected:!1});let l=!t.json&&process.stdin.isTTY&&process.stdout.isTTY,d=l?await Pm([...s,...a]):new Set([...N$(o.actions),...s.map(f=>f.id)]);l&&_$(o.actions,d);let u=d.has("create-agent-guidance")||d.has("update-agent-guidance"),m=o.actions.some(f=>f.id==="enable-automatic-refresh"),g=o.actions.some(f=>f.id==="install-indexers");return{...e,...m?{automaticRefresh:d.has("enable-automatic-refresh")}:{},noHooks:e.noHooks||o.actions.some(f=>f.id==="install-project-hooks")&&!d.has("install-project-hooks"),noAgentGuidance:!u,...g?{installIndexers:l?d.has("install-indexers"):e.installIndexers===!0}:{},languages:i.languages.filter(f=>d.has(`language:${f}`)),installSkills:d.has("install-agent-skills"),installAstParsers:l?d.has("install-ast-parsers"):e.installAstParsers===!0,runHealth:d.has("run-health-analysis")}}function F$(e){return{agentsMd:se(Ct(e,"AGENTS.md")),claudeMd:se(Ct(e,"CLAUDE.md")),codexHooks:se(Ct(e,".codex","hooks.json")),claudeSettings:se(Ct(e,".claude","settings.local.json"))}}function N$(e){return new Set([...e.filter(t=>t.recommended&&t.id!=="install-indexers").map(t=>t.id),"install-agent-skills"])}function _$(e,t){console.log(""),console.log("Selected setup changes:");for(let n of["repository","checkout","user"]){let r=e.filter(o=>o.scope===n&&t.has(o.id)).map(o=>o.label);console.log(` ${n} (${n==="repository"?"commit these shared project changes":n==="checkout"?"keep these local to this checkout":"changes this machine or user environment"}): ${r.length>0?r.join(", "):"none"}`)}}function Ef(e){let t=X(e),n=re(),r=Im(n,{force:b(t,"force"),dryRun:b(t,"dryRun")});if(b(t,"dryRun")){console.log(r.content);return}if(r.skipped){console.log(`skip: ${r.path} \u2014 ${r.reason}`);return}console.log(`done: ${r.path}`)}function If(e){let t=X(e);if(b(t,"global")&&b(t,"project")){console.error("error: choose either --global or --project, not both."),process.exitCode=1;return}let n=Am({projectRoot:re(),global:b(t,"global"),project:b(t,"project"),dryRun:b(t,"dryRun")});if(b(t,"json")){I("uninstall",[],t,n);return}let r=n.dryRun?"would ":"";if(n.global){for(let o of n.global.removed)console.log(` ${r}remove: ${o}`);for(let o of n.global.left)console.log(` left: ${o}`);for(let o of n.global.skipped)console.log(` skip: ${o}`)}if(n.project){for(let o of n.project.hooks.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.unchanged)console.log(` ok: ${o} (no managed block)`);for(let o of n.project.hooks.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.agentSetup.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.left)console.log(` left: ${o}`)}(n.global?.removed.length??0)+(n.project?.hooks.removed.length??0)+(n.project?.agentSetup.removed.length??0)===0&&console.log(n.dryRun?"No scip-query-owned files would be removed.":"No scip-query-owned files removed.")}function Af(e){let t=X(e),n=re(),r=ke(n),i=Q(t,"debounce"),o=Q(t,"cooldown"),s=Q(t,"gitPoll"),a=Q(t,"idleTimeout"),c=b(t,"daemon"),l=b(t,"status"),d=b(t,"stop"),u=b(t,"json"),m=[c,l,d].filter(Boolean).length;if(m>1){console.error("error: choose only one of --daemon, --status, or --stop."),process.exitCode=1;return}if(u&&m===0){console.error("error: --json requires --daemon, --status, or --stop."),process.exitCode=1;return}let g=[["--debounce",i,!1],["--cooldown",o,!0],["--git-poll",s,!1],["--idle-timeout",a,!0]].find(([,P,G])=>P!==void 0&&(!Number.isInteger(P)||(G?Number(P)<0:Number(P)<=0)));if(g){console.error(`error: ${g[0]} requires ${g[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}let f={...i===void 0?{}:{debounceMs:i},...o===void 0?{}:{cooldownMs:o},...s===void 0?{}:{gitPollMs:s},...a===void 0?{}:{idleTimeoutMs:a}};i&&((r.watch??={}).debounceMs=i),o!==void 0&&((r.watch??={}).cooldownMs=o),s&&((r.watch??={}).gitPollMs=s),a!==void 0&&((r.watch??={}).idleTimeoutMs=a);let h=Oe(r);r.watch=h;let S=He(n,r),y={projectRoot:n,cacheDir:S.cacheDir,cliVersion:ye,watchOverrides:f};if(l){let P=jf(Gi(y),h.enabled);u?I("watch",[],t,P):Lf(P);return}if(d){try{let P=Yl(y);u?I("watch",[],t,P):console.log(P.disposition==="stopped"?`Stopped watch service${P.pid?` (pid ${P.pid})`:""}.`:"Watch service is already stopped.")}catch(P){console.error(`error: ${P instanceof Error?P.message:String(P)}`),process.exitCode=1}return}if(!h.enabled){console.error('error: watch mode is disabled. Set "watch.enabled": true in .scipquery.json to start it.'),process.exitCode=1;return}if(c){try{let P=Sr(y);u?I("watch",[],t,P):console.log(`${P.disposition==="started"?"Started":"Reused"} watch service for ${n} (pid ${P.state.pid}).`)}catch(P){console.error(`error: ${P instanceof Error?P.message:String(P)}`),process.exitCode=1}return}let v=Ql(Ct(si(S.dbPath),ma),n);if(!v.acquired){console.error(v.message),process.exitCode=1;return}let w=new Zr({projectRoot:n,config:r,languages:r.languages,onStatus:P=>{process.stdout.write(`\r\x1B[K${Wi(Vi(P))}`)},onReindexComplete:P=>(console.log(`
407
- Reindex complete in ${(P/1e3).toFixed(1)}s`),Me(n,r,S).state==="fresh"),onRefreshSuppressed:P=>{qu(S.dbPath,P),console.log(`
408
- Skipped redundant refresh; the completed index already includes the queued changes.`)},onError:P=>{console.error(`
409
- Watch error: ${P.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${h.debounceMs}ms | Cooldown: ${h.cooldownMs}ms | Git poll: ${h.gitPollMs}ms`),console.log(`Press Ctrl+C to stop.
410
- `),w.start();let R=!1,j=()=>{R||(R=!0,w.stop().then(P=>{if(P.state==="degraded"){R=!1,console.error(`
411
- Unable to stop safely: ${P.reasons.join("; ")}`);return}v.release(),console.log(`
412
- Stopped.`),process.exit(0)}))};process.on("SIGINT",j),process.on("SIGTERM",j)}function jf(e,t=!0){let{classification:n}=e,r=Kl(e.paths.refreshRequestsPath);switch(n.kind){case"stopped":return e.lockIsLive&&e.lock?{enabled:t,state:"running",mode:"foreground-or-starting",pid:e.lock.pid,projectRoot:e.identity.projectRoot,worktreeId:e.identity.worktreeId,startedAt:e.lock.startedAt,refreshRequests:r}:{enabled:t,state:"stopped",mode:"none",refreshRequests:r};case"live":return{enabled:t,state:"running",mode:"daemon",pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,startedAt:n.state.startedAt,heartbeatAt:n.state.heartbeatAt,lastActivityAt:n.state.lastActivityAt,idleDeadlineAt:n.state.idleDeadlineAt,watcher:n.state.watcher,indexGeneration:n.state.indexGeneration,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,reindexActivity:n.state.reindexActivity,refreshRequests:r,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};case"stale":case"incompatible":return{enabled:t,state:n.kind,mode:"daemon",reason:n.reason,pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,heartbeatAt:n.state.heartbeatAt,watcher:n.state.watcher,indexGeneration:n.state.indexGeneration,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,reindexActivity:n.state.reindexActivity,refreshRequests:r,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};default:return B$(n)}}function Lf(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`),Xm(e.refreshRequests);return}let t="pid"in e?` (pid ${e.pid})`:"";if(console.log(`Watch service: ${e.state} [${e.mode}]${t}`),"projectRoot"in e&&e.projectRoot){let n="worktreeId"in e&&e.worktreeId?` [${e.worktreeId.slice(0,12)}]`:"";console.log(`Worktree: ${e.projectRoot}${n}`)}if("watcher"in e&&e.watcher&&console.log(`Watcher: ${Vi(e.watcher)}`),"indexGeneration"in e&&e.indexGeneration&&console.log(`Index generation: ${e.indexGeneration.slice(0,12)}`),"idleDeadlineAt"in e&&e.idleDeadlineAt&&console.log(`Idle exit: ${e.idleDeadlineAt}`),"reason"in e&&console.log(`Reason: ${e.reason}`),"lastError"in e&&e.lastError&&console.log(`Last error: ${e.lastError.message}`),"reindexActivity"in e&&e.reindexActivity){let n=e.reindexActivity;console.log(`Reindex activity (24h): ${n.runs} run(s) (${n.rebuilt} rebuilt, ${n.reused} reused, ${n.failed} failed), ${n.suppressed} redundant refresh(es) suppressed, ${Ue(n.estimatedLogicalOutputBytes)} estimated logical output`)}if("refreshRequests"in e&&e.refreshRequests&&Xm(e.refreshRequests),"typescriptSemantic"in e&&e.typescriptSemantic){let n=e.typescriptSemantic;console.log(`TypeScript semantics: ${n.state} (${n.projectsCreated} Projects, ${n.requests} requests)`)}if("typescriptIndex"in e&&e.typescriptIndex){let n=e.typescriptIndex;console.log(`TypeScript index: ${n.state} (${n.initializations} warmups, ${n.programUpdates} updates, ${n.requests} requests)`)}}function Xm(e){console.log(`Refresh requests: ${e.pending} pending, ${e.claimed} claimed, ${e.completed} completed, ${e.expired} expired${e.invalid>0?`, ${e.invalid} invalid`:""}`)}function B$(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function Df(e){let t=X(e),{report:n}=Cf("status"),r=Oe(ke(n.projectRoot)).enabled,i=jf(Gi({projectRoot:n.projectRoot,cacheDir:si(n.configuredDbPath),cliVersion:ye}),r),o=Cu(n.dbPath),s=bt(n.dbPath,n.freshness.metaPath),a=rr(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(b(t,"json")){I("status",[],t,{...n,affectedSetShadow:o,sqliteGeneration:s,rustSemanticSession:a,watchService:i,stats:cs(n.exists)});return}V$(n,{affectedSetShadow:o,capabilities:b(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:i})}function q$(e,t){console.log(`Doctor: ${e.ok?"OK":"needs attention"}`);for(let n of e.configDiagnostics)console.log(` ${n.level.toUpperCase()} ${n.path}: ${n.message}`);if(t)for(let n of e.readiness.indexers.filter(r=>!r.runnable))console.log(` MISSING ${n.language}: ${n.note??n.binaryLabel}`);console.log(` Freshness: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),us(e.capabilities)}function V$(e,t){console.log(`Project: ${e.projectRoot}`),console.log(`DB path: ${e.dbPath}`),e.dbPath!==e.configuredDbPath&&console.log(`Config: ${e.configuredDbPath} (fallback to project root index.db)`);for(let n of Of(e.readiness)){let r=n.available?"available":n.dependencyAvailable?"fallback":"unavailable",i=n.language==="typescript"?"TS sem:":`${n.language} sem:`;console.log(`${i.padEnd(9)}${r}${Mf(n)}`),n.reason&&console.log(`${n.language} note: ${n.reason}`)}console.log(`Exists: ${e.exists?"yes":"no"}`),console.log(`Fresh: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),e.freshness.lastRefresh&&console.log(`Refresh: ${U$(e.freshness.lastRefresh)}`),Lf(t.watchService),W$(e.sharedCache),console.log(`Rust sess: ${t.rustSemanticSession.transport}/${t.rustSemanticSession.state} (${t.rustSemanticSession.source}; worker fallback; opt out with ${t.rustSemanticSession.optOut})`),t.rustSemanticSession.valid||console.log("Rust note: invalid durable-session value; using worker fallback"),H$(t.sqliteGeneration),console.log(`Shadow: ${Pu(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),J$(e.exists),t.capabilities&&(console.log(""),us(e.capabilities))}function W$(e){if(e.state!=="managed"){console.log(`Shared: ${e.state}${e.reason?` (${e.reason})`:""}`);return}let t=e.activeGenerationId?.slice(0,12)??"none",n=e.lastAction??"none";console.log(`Shared: ${n}, active ${t}, ${e.generations} generation(s), ${Ue(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${Ue(e.unreferencedBytes)}), ${e.temporaryGenerations} temporary`),e.cleanup?.kind==="swept"&&console.log(`Cache GC: ${e.cleanup.deletedWorktrees??0} worktree(s), ${e.cleanup.deletedGenerations??0} generation(s), ${Ue(e.cleanup.deletedBytes??0)} removed`)}function H$(e){if(e.state==="legacy"){console.log("DB gen: legacy (no generation record)");return}if(e.state==="invalid"){console.log(`DB gen: invalid (${e.reason})`);return}let t=e.generation.publication,n=t?.mode??"unknown",r=t?[t.affectedDocumentCount===void 0?null:`${t.affectedDocumentCount} affected`,t.changedDocumentCount===void 0?null:`${t.changedDocumentCount} changed`,t.producerDurationMs===void 0?null:`${t.producerDurationMs.toFixed(0)}ms producer`,`${t.converterDurationMs.toFixed(0)}ms convert`,t.patchDurationMs===void 0?null:`${t.patchDurationMs.toFixed(0)}ms patch`,`${t.scipCompanion??"current"} SCIP companion`].filter(i=>i!==null).join(", "):"no publication metrics";console.log(`DB gen: ${e.state} ${e.generation.currentGeneration.slice(0,12)} (${n}; ${r})`),console.log(`DB layout: ${e.generation.artifactSet==="immutable-v1"?"immutable artifact set; stable paths are mirrors":"legacy stable paths"}`),e.generation.previousGeneration&&console.log(`Recovery: ${e.generation.previousGeneration.generationIdentity.slice(0,12)} at ${e.generation.previousGeneration.databasePath}`),t?.fallbackReason&&console.log(`DB fallback: ${t.fallbackReason}`),e.reason&&console.log(`DB note: ${e.reason}`)}function Of(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function G$(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function Mf(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function U$(e){let t=(e.durationMs/1e3).toFixed(1),n=e.trigger.detail?` (${e.trigger.detail})`:"",r=e.error?`: ${e.error}`:"";return`${e.result} by ${e.trigger.kind}${n} in ${t}s at ${e.completedAt}${r}`}function cs(e){if(e)return ue(t=>{let n=Dt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function J$(e){e&&ue(t=>{let n=Dt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Ue(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function us(e){console.log(`Capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`);for(let t of e.capabilities)console.log(` ${t.status.toUpperCase().padEnd(11)} ${t.label} [${t.evidence}]`),console.log(` ${t.reason}`);if(e.matrix.length!==0){console.log(`
413
- Language matrix:`);for(let t of e.matrix){console.log(` ${t.language}`);for(let n of[t.indexing,t.sourceFacts,t.semantic,t.detectors,t.cleanupVerification])console.log(` ${n.status.toUpperCase().padEnd(11)} ${n.label}`),console.log(` ${n.reason}`)}}}function Fn(e){return{...e,options:E(e.options)}}function _e({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=Fn(l);return{...d,renderShape:"list",handler:_l({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c})}}function ai({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d,...u}){let m=Fn(u);return{...m,renderShape:"table",handler:Bl({commandName:m.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d})}}function Ff({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,key:l,...d}){let u=Fn(d);return{...u,renderShape:"grouped-by-file",handler:ql({commandName:u.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,key:l})}}function Nf({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=Fn(l);return{...d,renderShape:"sectioned-report",handler:Vl({commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,coverage:s,agentResult:a,after:c})}}function ci({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=Fn(l);return{...d,budget:d.budget??"semantic",renderShape:"sectioned-report",handler:Wl(d.id,{commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,coverage:s,agentResult:a,after:c})}}import{existsSync as $C,mkdirSync as CC,writeFileSync as PC}from"fs";import{dirname as TC,relative as EC}from"path";import{existsSync as tt,readdirSync as Z$}from"fs";import{basename as eC,dirname as Gf,isAbsolute as Uf,join as tC,relative as nC,resolve as Nn,sep as rC}from"path";import{spawnSync as z$}from"child_process";import{dirname as Y$}from"path";function Bf(e){let n=(e.spawnSync??z$)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:Y$(e.specPath),maxBuffer:1024*1024*32,timeout:3e4,killSignal:"SIGKILL"});if(n.status!==0)return null;let r=n.stdout??"";return r.includes("<?xml")?r:null}function qf(e){let t=Q$(e),n=new Map,r=new Map,i=[],o=new Map;for(let a of t)a.type==="OpDeclNode"&&a.kind===3&&a.uniquename?n.set(a.uid,a.uniquename):a.type==="BuiltInKind"&&a.uniquename?r.set(a.uid,a.uniquename):a.type==="UserDefinedOpKind"&&a.uniquename&&(i.push(a),o.set(a.uid,a));let s=[];for(let a of i){let c=Vf(a.block,n,r,o,a.filename,new Set([a.uid]),0);s.push({name:a.uniquename,reads:c.reads,writes:c.writes})}return{modelParse:"sany",variables:[...n.values()].sort(),operators:i.map(a=>a.uniquename).sort(),actions:s}}var X$=8;function Q$(e){let t=[],n=/<entry>\s*<UID>(\d+)<\/UID>\s*<(\w+)>/g;for(let r of e.matchAll(n)){let i=r.index,o=e.indexOf("</entry>",i),s=e.slice(i,o<0?e.length:o),a=ps(s,"uniquename"),c=ps(s,"kind"),l=ps(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:_f(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:_f(l),block:s})}return t}function Vf(e,t,n,r,i,o,s){let a=new Set,c=new Set,l=[...e.matchAll(/<(\w+Ref)>\s*<UID>(\d+)<\/UID>/g)],d="read";for(let[,u,m]of l){if(u==="BuiltInKindRef"){let g=n.get(m)??"";g==="'"?d="write-next":g==="UNCHANGED"?d="unchanged-run":d==="unchanged-run"&&g==="$Tuple"||d!=="write-next"&&(d="read");continue}if(u==="OpDeclNodeRef"){let g=t.get(m);if(!g)continue;d==="write-next"?(c.add(g),d="read"):d==="unchanged-run"||a.add(g);continue}if(u==="UserDefinedOpKindRef"){d==="unchanged-run"&&(d="read");let g=r.get(m);if(g&&s<X$&&!o.has(g.uid)&&g.filename===i){let f=Vf(g.block,t,n,r,i,new Set([...o,g.uid]),s+1);for(let h of f.reads)a.add(h);for(let h of f.writes)c.add(h)}continue}d==="unchanged-run"&&(d="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function ps(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function _f(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var Jf=["update","insert","delete"],Kf=["select","query","findFirst","findMany"],ms=new Set([...Jf,...Kf]);function fs(e){let t=e.methods&&e.methods.length>0?e.methods:[...ms],n=new Set(Jf),r=new Set(Kf);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var iC=/^(.*)@L(\d+)-L(\d+)$/;function gs(e){let t=e.match(iC);if(!t)return{ref:e};let n=t[1],r=Number.parseInt(t[2],10),i=Number.parseInt(t[3],10);return n?r<1?{error:`codeRef "${e}" line window must start at line 1 or later`}:i<r?{error:`codeRef "${e}" line window end (L${i}) is before its start (L${r})`}:{ref:n,window:{startLine:r,endLine:i}}:{error:`codeRef "${e}" has a line window but no referent before @L${t[2]}-L${t[3]}`}}var oC=new Set(["auto","sany","tlc","apalache","none"]),di=/^[A-Za-z_][A-Za-z0-9_]*$/;function zf(e){return oC.has(e)}function ui(e,t){let n=[],r=ve(e,t);if(!r)return{errors:[`map path escapes project root: ${t}`]};if(!tt(r))return{errors:[`map file not found: ${t}`]};let i;try{i=JSON.parse(U(r,{inputKind:"TLA mapping",maxBytes:xe}))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let o=sC(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:Gf(r)},errors:n}:{errors:n}}function ve(e,t){if(!t)return null;let n=Uf(t)?Nn(t):Nn(e,t);return de(e,n)?n:null}function Yf(e,t,n){if(!n)return null;if(Uf(n)){let s=Nn(n);return de(e,s)?s:null}let r=Nn(e,n);if(de(e,r)&&tt(r))return r;let i=Nn(t,n);if(de(e,i)&&tt(i))return i;let o=de(e,r)?r:i;return de(e,o)?o:null}function Xf(e,t){let n=ve(e,t);if(!n||!tt(n))return null;let r=U(n,{inputKind:"TLA module",maxBytes:Re});return{path:n,modelParse:"regex-fallback",text:r,variables:vC(r),operators:xC(r),actions:[]}}function Qf(e,t,n){let r=ve(e,t);if(!r||!tt(r))return null;let i=U(r,{inputKind:"TLA module",maxBytes:Re}),o=qf(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function hs(e,t){let n=ve(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!tt(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let r=JSON.parse(U(n,{inputKind:"TLA trace",maxBytes:Re})),i=Array.isArray(r)?r:K(r)&&Array.isArray(r.steps)?r.steps:null;if(!i)return{steps:[],errors:["trace file must be an array or an object with a steps array"]};let o=[],s=[];for(let[a,c]of i.entries()){if(!K(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}o.push({action:c.action,before:K(c.before)?c.before:void 0,after:K(c.after)?c.after:void 0,code:typeof c.code=="string"?c.code:void 0})}return{steps:o,errors:s}}catch(r){let i=r instanceof Error?r.message:String(r);return{steps:[],errors:[`trace file is not valid JSON: ${i}`]}}}function ys(e,t){let n=new Set,r=[];for(let i of t){let o=ve(e,i)??i;n.has(o)||(n.add(o),r.push(i))}return r}function sC(e,t){if(!K(e))return t.push("map file must contain a JSON object"),null;let n=pC(e.variables,t);uC(n,t);let r=bC(e.actions,n,t),i=aC(e.init,t);lC(i,r,t);let o={module:Hf(e.module,"module",t),config:Hf(e.config,"config",t),scope:Z(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:Z(e.invariants)??[],traces:Z(e.traces)??[],unmappedWriteScope:dC(e.unmappedWriteScope,t)};return kC(e.scope,t),t.length===0?o:null}function aC(e,t){if(e===void 0)return;if(!K(e)){t.push("init must be an object when present");return}let n=Z(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let r=cC(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function cC(e,t){if(e===void 0)return;if(!K(e)){t.push("init.waive must be an object when present");return}let n=typeof e.reason=="string"?e.reason.trim():"";if(!n){t.push("init.waive.reason must be a non-empty string");return}return{reason:n}}function lC(e,t,n){if(!e)return;let r=new Set(e.codeRefs),i=new Set;for(let o of Object.values(t))for(let s of o.code)r.has(s)&&i.add(s);i.size>0&&n.push(`init.codeRefs overlaps action code referents: ${[...i].sort().join(", ")} \u2014 a referent cannot be both Init and an action`)}function dC(e,t){return e===void 0?"scope-files":e==="actions"||e==="scope-files"?e:(t.push('unmappedWriteScope must be "actions" or "scope-files" when present'),"scope-files")}function uC(e,t){li(e,t,"alias",n=>n.aliases),li(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),li(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),li(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=fs(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function li(e,t,n,r){let i=new Map;for(let[o,s]of Object.entries(e))for(let a of r(s)){let c=i.get(a);c?c.push(o):i.set(a,[o])}for(let[o,s]of i)s.length<2||t.push(`variables ${[...new Set(s)].sort().join(", ")} share ${n} "${o}" \u2014 conformance scanning cannot attribute a matching write/read to one variable unambiguously`)}function pC(e,t){if(!K(e))return t.push("variables must be an object keyed by TLA+ variable name"),{};let n={};for(let[r,i]of Object.entries(e)){if(!di.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!K(i)){t.push(`variables.${r} must be an object`);continue}let o=eg(i.code);if(!o||o.length===0){t.push(`variables.${r}.code must name at least one TypeScript referent`);continue}let s=Z(i.aliases)??[],a=fC(i.resource,r,t),c=gC(i.statements,r,t),l=hC(i.ormCalls,r,t),d=yC(i.waive,r,t),u=mC(i.selfAlias,r,t),m=u?[...new Set([r,...s])]:[...new Set(s)];u===!1&&m.length===0&&!a&&!c&&!l&&!d&&t.push(`variables.${r}.selfAlias is false but no aliases, resource, statements, ormCalls, or waive are set \u2014 ${r} would be unattributable; add an explicit alias, bind resource/statements/ormCalls, or add variables.${r}.waive with a reason`),n[r]={code:o,aliases:m,projection:typeof i.projection=="string"?i.projection:void 0,...a?{resource:a}:{},...c?{statements:c}:{},...l?{ormCalls:l}:{},...d?{waive:d}:{},...u===!1?{selfAlias:!1}:{}}}return n}function mC(e,t,n){return e===void 0?!0:typeof e=="boolean"?e:(n.push(`variables.${t}.selfAlias must be a boolean when present`),!0)}function fC(e,t,n){if(e===void 0)return;if(!K(e)){n.push(`variables.${t}.resource must be an object when present`);return}let r=typeof e.path=="string"?e.path.trim():"";if(!r){n.push(`variables.${t}.resource.path must be a non-empty string`);return}return{path:r}}function gC(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.statements must be an array when present`);return}let r=[];return e.forEach((i,o)=>{if(!K(i)){n.push(`variables.${t}.statements[${o}] must be an object`);return}let s=typeof i.pattern=="string"?i.pattern.trim():"";if(!s){n.push(`variables.${t}.statements[${o}].pattern must be a non-empty string`);return}try{Hn(s,`variables.${t}.statements[${o}].pattern`)}catch(a){let c=a instanceof Error?a.message:String(a);n.push(`variables.${t}.statements[${o}].pattern is not a valid regular expression: ${c}`);return}r.push({pattern:s})}),r.length>0?r:void 0}function hC(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.ormCalls must be an array when present`);return}let r=[];return e.forEach((i,o)=>{if(!K(i)){n.push(`variables.${t}.ormCalls[${o}] must be an object`);return}let s=typeof i.table=="string"?i.table.trim():"";if(!s){n.push(`variables.${t}.ormCalls[${o}].table must be a non-empty string`);return}if(i.methods===void 0){r.push({table:s});return}let a=Z(i.methods);if(!a){n.push(`variables.${t}.ormCalls[${o}].methods must be an array of strings when present`);return}let c=a.filter(l=>!ms.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...ms].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function yC(e,t,n){if(e===void 0)return;if(!K(e)){n.push(`variables.${t}.waive must be an object when present`);return}let r=typeof e.reason=="string"?e.reason.trim():"";if(!r){n.push(`variables.${t}.waive.reason must be a non-empty string`);return}return{reason:r}}function bC(e,t,n){if(!K(e))return n.push("actions must be an object keyed by TLA+ action name"),{};let r=new Set(Object.keys(t)),i={};for(let[o,s]of Object.entries(e)){if(!di.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!K(s)){n.push(`actions.${o} must be an object`);continue}let a=eg(s.code);if(!a||a.length===0){n.push(`actions.${o}.code must name at least one TypeScript referent`);continue}for(let m of a){let g=gs(m);"error"in g&&n.push(`actions.${o}.code: ${g.error}`)}let c=Z(s.reads)??[],l=Z(s.writes)??[],d=Z(s.calls)??[];for(let m of[...c,...l])r.has(m)||n.push(`actions.${o} references unknown variable: ${m}`);let u=SC(s.waive,s.allowUnknown===!0,c,l,r,o,n);i[o]={code:a,reads:c,writes:l,calls:d,...u?{waive:u}:{}}}return i}function SC(e,t,n,r,i,o,s){if(K(e)){let a=typeof e.reason=="string"?e.reason.trim():"";a||s.push(`actions.${o}.waive.reason must be a non-empty string`);let c=Z(e.reads)??[],l=Z(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${o}.waive must list reads or writes`),Wf(o,"reads",c,i,s),Wf(o,"writes",l,i,s),{reads:[...new Set(c)],writes:[...new Set(l)],reason:a}}if(e!==void 0&&s.push(`actions.${o}.waive must be an object when present`),t)return{reads:[...new Set(n)],writes:[...new Set(r)],reason:"legacy allowUnknown",legacy:!0}}function Wf(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function vC(e){let t=new Set;for(let n of e.matchAll(/^\s*VARIABLES?\s+([^\n]+)/gm)){let r=n[1]??"";for(let i of r.split(",")){let o=i.trim();di.test(o)&&t.add(o)}}return[...t].sort()}function xC(e){let t=new Set;for(let n of e.matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?:\([^)]*\))?\s*==/gm))t.add(n[1]);return[...t].sort()}var RC=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function Zf(e){if(!e||!tt(e))return[];let t=U(e,{inputKind:"TLA checker configuration",maxBytes:xe}).replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,r=!1;for(let i of t.split(/[\s,]+/))if(i){if(RC.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&di.test(i)&&n.add(i)}return[...n].sort()}function Hf(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function eg(e){return typeof e=="string"?[e]:Z(e)}function kC(e,t){e!==void 0&&(Z(e)||t.push("scope must be an array of strings when present"))}function pi(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var wC=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function tg(e,t){if(!tt(t))return{status:"none"};let r=U(t,{inputKind:"TLA module",maxBytes:Re}).match(wC)?.[1],i=nC(e,t).split(rC).join("/"),o=eC(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(d=>!!d)),a=Gf(t);if(!tt(a))return{status:"none"};let c=[];for(let d of Z$(a)){if(!d.endsWith(".scip-tla.json"))continue;let u=tC(a,d),m;try{m=JSON.parse(U(u,{inputKind:"TLA mapping candidate",maxBytes:xe}))}catch{continue}K(m)&&typeof m.module=="string"&&s.has(m.module)&&c.push(u)}c.sort();let l=r??i;return c.length===0?{status:"none"}:c.length>1?{status:"ambiguous",candidates:c,moduleName:l}:{status:"found",mapPath:c[0],moduleName:l}}function mi(e,t,n,r,i={count:e.length,loc:r}){let o=i.count===e.length&&i.loc===r?`${e.length}, ${r} LOC`:`${e.length} of ${i.count}, ${r} of ${i.loc} LOC`;console.log(`\u2550\u2550\u2550 ${t} (${o}) \u2550\u2550\u2550`),console.log(n),console.log("");let s=new Map;for(let l of e){let d=s.get(l.relativePath)??[];d.push(l),s.set(l.relativePath,d)}let a=[...s.entries()].map(([l,d])=>({file:l,bucket:d,totalLoc:d.reduce((u,m)=>u+m.loc,0)})).sort((l,d)=>d.totalLoc-l.totalLoc||l.file.localeCompare(d.file)),c=!0;for(let{file:l,bucket:d}of a){c||console.log(""),c=!1,console.log(` ${l}`),d.sort((u,m)=>u.startLine-m.startLine);for(let u of d){let m=u.implicitUsageReason?` [implicit usage: ${u.implicitUsageReason}]`:"";console.log(` ${pe(u.startLine,u.endLine)} (${u.loc} LOC) ${u.shortName}${m}`)}}}var bs=20,ng=te("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:z(t,0)||void 0,minLoc:T(n,"minLoc",1),includeTests:b(n,"includeTests"),skipBarrels:b(n,"skipBarrels"),includeMembers:b(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=Aa(e,i),s=o.symbols.filter(N=>N.kind==="dead-code"),a=o.symbols.filter(N=>N.kind==="file-internal"),c=o.symbols.filter(N=>N.kind==="implicit-usage"),l=!b(n,"onlyInternal"),d=!b(n,"onlyDead"),u=!b(n,"onlyDead")&&!b(n,"onlyInternal"),m=l?s:[],g=d?a:[],f=u?c:[],h=m.reduce((N,H)=>N+H.loc,0),S=g.reduce((N,H)=>N+H.loc,0),y=f.reduce((N,H)=>N+H.loc,0),v=b(n,"full"),w=v?m:m.slice(0,bs),R=v?g:g.slice(0,bs),j=v?f:f.slice(0,bs),P=w.reduce((N,H)=>N+H.loc,0),G=R.reduce((N,H)=>N+H.loc,0),A=j.reduce((N,H)=>N+H.loc,0),M={total:m.length+g.length+f.length,deadCode:m.length,fileInternal:g.length,implicitUsage:f.length,loc:h+S+y};if(b(n,"json")){I("dead",t,n,{...o,shown:{deadCode:m,fileInternal:g,implicitUsage:f},shownCounts:M,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,implicitUsage:o.counts.implicitUsage,loc:o.counts.loc}},{analysisBudget:r.analysisBudget});return}if(m.length===0&&g.length===0&&f.length===0){L.empty("No matching dead-code symbols found.");return}m.length>0&&(mi(w,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
414
- Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,P,{count:m.length,loc:h}),!v&&m.length>w.length&&console.log(`
415
- Showing top ${w.length} by LOC. Re-run with --full for the remaining ${m.length-w.length}.`)),g.length>0&&(m.length>0&&console.log(""),mi(R,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
416
- single-use helper, an abstraction-in-progress, or a callback registered
417
- through a framework path that static analysis cannot trace (signal
418
- handlers, event listeners, dependency injection). NOT necessarily dead \u2014
419
- review case by case.`,G,{count:g.length,loc:S}),!v&&g.length>R.length&&console.log(`
420
- Showing top ${R.length} by LOC. Re-run with --full for the remaining ${g.length-R.length}.`)),f.length>0&&((m.length>0||g.length>0)&&console.log(""),mi(j,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
421
- consumer that the static reference graph cannot trace. Investigation
422
- signals only \u2014 not deletion candidates and not counted as dead code.`,A,{count:f.length,loc:y}),!v&&f.length>j.length&&console.log(`
423
- Showing top ${j.length} by LOC. Re-run with --full for the remaining ${f.length-j.length}.`));let _=[];l&&_.push(`${m.length} dead code (${h} LOC)`),d&&_.push(`${g.length} file-internal (${S} LOC)`),u&&_.push(`${f.length} implicit usage (${y} LOC)`),console.log(`
424
- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${m.length+g.length+f.length} symbols \u2014 ${_.join(" + ")}`)}),rg=Se("unused-imports",{query:({db:e,args:t,budget:n})=>Oa(e,O(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
425
- ${e.length} unused import(s)`)}),ig=Hl("isolated",{query:({db:e,opts:t,budget:n})=>Ua(e,{scope:$(t,"scope"),minLoc:T(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${pe(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
426
- ${e.length} isolated symbol(s)`)}),og=te("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=cc(e,{scope:$(n,"scope"),minLoc:T(n,"minLoc",10),minCallees:T(n,"minCallees",6),limit:F(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("extract-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return L.empty("No extraction candidates found.");Fe("extraction candidates");for(let o of i){console.log(`
427
- ${J(o.relativePath,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC, ${o.totalCallees} callees)`),console.log(` Kind: ${o.extractionKind}; tier: ${o.actionTier}`),console.log(` Recommendation: ${o.recommendation}`);for(let s of o.evidenceReasons)console.log(` - ${s}`);for(let s=0;s<o.clusters.length;s++){let a=o.clusters[s];console.log(` Cluster ${s+1} (${Math.round(a.isolation*100)}% isolated, ${a.callees.length} callees):`);for(let c of a.callees)console.log(` ${c}`)}}console.log(`
428
- ${i.length} extraction candidate(s) found.`)}),sg=te("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=lc(e,{target:z(t,0)||void 0,scope:$(n,"scope"),minConsumers:T(n,"minConsumers",1),limit:F(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(b(n,"json")){I("locality-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return L.empty("No locality candidates found.");Fe("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?J(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
429
- ${s} ${o.sourceUnit.shortName}`),console.log(` Current directory: ${o.currentDirectory}; tier: ${o.recommendedTier}; action: ${o.actionTier}`),console.log(` Consumer coverage: ${o.consumerCoverage}; consumers: ${o.consumerFiles.length}`),o.nearestCommonOwner&&console.log(` Nearest common owner: ${o.nearestCommonOwner}`),o.suggestedHome&&console.log(` Suggested home: ${o.suggestedHome}`),o.whyNoSuggestedHome&&console.log(` Suggested home withheld: ${o.whyNoSuggestedHome}`),o.boundaryMarkers.length>0&&console.log(` Boundary markers: ${o.boundaryMarkers.join("; ")}`),console.log(` Recommendation: ${o.recommendation}`),o.consumerFiles.length>0){for(let a of o.consumerFiles.slice(0,8))console.log(` - consumer: ${a}`);o.consumerFiles.length>8&&console.log(` - ... ${o.consumerFiles.length-8} more consumer(s)`)}for(let a of o.counterevidence)console.log(` - counterevidence: ${a}`)}console.log(`
430
- ${i.length} locality candidate(s) found.`)}),ag=Se("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>xc(e,{scope:$(t,"scope"),maxLoc:T(t,"maxLoc",15),limit:F(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${J(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
431
- Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
432
- Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
433
- ${e.length} wrapper candidate(s).`)}),cg=Se("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>Sc(e,{scope:$(t,"scope"),maxLoc:T(t,"maxLoc",15),limit:F(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${J(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
434
- Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
435
- Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
436
- Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
437
- Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
438
- ${e.length} passthrough candidate(s).`)}),lg=Se("stale-abstractions",{query:({db:e,opts:t,budget:n})=>vc(e,{scope:$(t,"scope"),minLoc:T(t,"minLoc",3),limit:F(t,"limit",30),includeLowConfidence:b(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${J(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
439
- ${e.reason}
440
- Kind: ${e.stalenessKind}; tier: ${e.actionTier}
441
- Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
442
- ${e.length} stale abstraction(s).`)}),dg=br("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Wc(e,{scope:$(t,"scope"),minLoc:T(t,"minLoc",10),limit:F(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.score.toFixed(1).padStart(5)} ${String(e.loc).padStart(4)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${String(e.calleeCount).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No complexity hotspots found.",heuristicLabel:"complexity hotspot candidates",dashWidths:[5,4,6,7,7,6]}),ug=Ee("similar",{query:({db:e,args:t,opts:n,budget:r})=>{if(b(n,"plan")){let o=z(t,0),s=z(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:Qa(e,o,s,{scanLimit:r.scanLimit,semantic:r.semantic})}}let i=z(t,0);return i?{mode:"target",rows:Xa(e,i,{minSimilarity:T(n,"minSimilarity",.4),limit:F(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Za(e,{minSimilarity:T(n,"minSimilarity",.4),limit:F(n,"limit",20),scope:$(n,"scope"),minCallees:T(n,"minCallees",4),crossFileOnly:b(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.semantic})}},emptyMessage:e=>{if(e.mode==="plan")return e.result?void 0:"No similarity evidence found for that pair.";if(!(e.rows.length>0))return e.mode==="target"?"No similar symbols found.":"No similar symbol pairs found."},heuristicLabel:"similarity candidates",render:e=>{if(e.mode==="plan"){let t=e.result;if(!t)return;let n=t.similarityBasis==="source-tokens"?"source-token overlap":"weighted callee overlap";console.log(`
443
- ${Math.round(t.similarity*100)}% ${n}
444
- `),console.log(` A: ${t.symbolA.shortName} (${t.symbolA.file}, ${t.symbolA.loc} LOC)`),console.log(` B: ${t.symbolB.shortName} (${t.symbolB.file}, ${t.symbolB.loc} LOC)`),console.log(` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`),console.log(` Recommendation: ${t.recommendation}
445
- `),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let r of t.sharedEvidence)console.log(` ${r}`);if(t.uniqueToA.length>0){console.log(`
446
- Unique to A (${t.uniqueToA.length}):`);for(let r of t.uniqueToA)console.log(` ${r}`)}if(t.uniqueToB.length>0){console.log(`
447
- Unique to B (${t.uniqueToB.length}):`);for(let r of t.uniqueToB)console.log(` ${r}`)}console.log(`
448
- Strategy: ${t.consolidationStrategy}`);return}if(e.mode==="target"){L.list(e.rows,t=>{let n=t.similarityBasis??"callees",r=n==="source-tokens"?"Shared source tokens":"Shared callees",i=n==="source-tokens"?"Only tokens in":"Only in",o=[`
449
- ${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${r}: ${t.sharedCallees.join(", ")}`];return t.evidenceClassReasons.length&&o.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.uniqueToA.length&&o.push(` ${i} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${i} B: ${t.uniqueToB.join(", ")}`),o.join(`
450
- `)});return}L.list(e.rows,t=>`
451
- ${Math.round(t.similarity*100)}% similar:
452
- A: ${t.shortNameA} (${t.fileA})
453
- B: ${t.shortNameB} (${t.fileB})
454
- Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})
455
- Recommendation: ${t.recommendation}
456
- `+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
457
- `:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
458
- ${e.rows.length} similar pair(s) found.`)}}),pg=it({commandName:"similar-files",query:({db:e,args:t,opts:n})=>ec(e,{minSimilarity:T(n,"minSimilarity",.5),limit:F(n,"limit",20),scope:$(n,"scope"),minDeps:Q(n,"minDeps"),filePattern:z(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{L.list(e,t=>{let n=[`
459
- ${Math.round(t.similarity*100)}% similar:`,` ${t.fileA}`,` ${t.fileB}`,` Shared deps (${t.sharedDeps.length}): ${t.sharedDeps.join(", ")}`];return t.uniqueToA.length&&n.push(` Only in first: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&n.push(` Only in second: ${t.uniqueToB.join(", ")}`),n.join(`
460
- `)}),console.log(`
461
- ${e.length} similar pair(s) found.`)}}),mg=it({commandName:"similar-chains",query:({db:e,opts:t})=>ac(e,{minSimilarity:T(t,"minSimilarity",.5),limit:F(t,"limit",15),scope:$(t,"scope"),minChainLength:T(t,"minLength",3),maxChainLength:T(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
462
- \u2500\u2500 Chain pair ${t+1} (${Math.round(n.similarity*100)}% similar, ${n.divergencePoints.length} divergence point(s)) \u2500\u2500`),console.log(` Chain A: ${n.chainA.join(" \u2192 ")}`),console.log(` Chain B: ${n.chainB.join(" \u2192 ")}`),n.commonPrefix.length&&console.log(` Common prefix: ${n.commonPrefix.join(" \u2192 ")}`),n.commonSuffix.length&&console.log(` Common suffix: ${n.commonSuffix.join(" \u2192 ")}`),console.log(" Divergence points (consolidation targets):");for(let r of n.divergencePoints)console.log(` [${r.index}] ${r.nodeA} \u2194 ${r.nodeB}`)}console.log(`
463
- ${e.length} similar chain pair(s) found.`)}}),fg=Ee("drift",{query:({db:e,args:t,opts:n,budget:r})=>bc(e,{scope:z(t,0),minDeviation:T(n,"minDeviation",5),semantic:r.semantic,includePatternDeviations:b(n,"patterns"),includeArchitecture:b(n,"architecture"),limit:F(n,"limit",50)}),emptyMessage:e=>e.results.length===0&&!e.architecture?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{if(console.log(""),L.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="architecture-violation"||t.kind==="layer-violation"?"ARCH":"UNIQUE",r=t.policyBasis?`, policy: ${t.policyBasis}`:"",i=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${r}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&i.push(` ${t.detail}`),i.join(`
464
- `)},t=>t.file),e.architecture){let t=e.architecture,n=t.edges.filter(r=>r.policyStatus==="undeclared").length;if(console.log(`
465
- Architecture context: ${t.coverage.mappedFiles}/${t.coverage.totalFiles} file(s) mapped; ${t.policyCoverage.declaredRows}/${t.policyCoverage.totalBoundaries} dependency row(s) declared; ${n} undeclared boundary edge(s).`),t.reciprocalPairs.length>0){console.log(` Reciprocal pairs (${t.reciprocalPairs.length}):`);for(let r of t.reciprocalPairs)console.log(` ${r.boundaries[0]} <-> ${r.boundaries[1]}`)}if(t.cycles.length>0){console.log(` Connected boundary groups (${t.cycles.length}):`);for(let r of t.cycles){let i=r.violatesPolicy?" [violates requireAcyclic]":" [signal]";console.log(` { ${r.boundaries.join(", ")} }${i}`)}}}console.log(`
466
- ${e.unusedImports} unused import(s), ${e.architectureViolations} declared architecture violation(s), ${e.patternDeviations} pattern deviation(s)${e.totalResults?` \u2014 showing ${e.results.length} of ${e.totalResults} (use -n to change)`:""}`)}}),gg=Ee("convergence",{query:({db:e,args:t,budget:n})=>Qc(e,O(t,0),O(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols did not resolve, or the pair has no fingerprint evidence (small helpers with few callees fall below the similarity threshold; try --min-callees 1).",render:e=>{if(e){console.log("\nDeprecated: use `similar <symbol1> <symbol2> --plan` for the same weighted similarity basis."),console.log(`
467
- ${Math.round(e.similarity*100)}% callee overlap
468
- `),console.log(` A: ${e.symbolA.shortName} (${e.symbolA.file}, ${e.symbolA.loc} LOC)`),console.log(` B: ${e.symbolB.shortName} (${e.symbolB.file}, ${e.symbolB.loc} LOC)
469
- `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
470
- Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
471
- Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
472
- Strategy: ${e.consolidationStrategy}`)}}}),hg=Se("similar-signatures",{query:({db:e,opts:t,budget:n})=>tl(e,{scope:$(t,"scope"),minLoc:T(t,"minLoc",3),maxShapeFrequency:T(t,"maxShapeFrequency",12),limit:F(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
473
- Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,r=e.functions.map(i=>` ${J(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
474
- `);return`${n}
475
- ${r}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
476
- ${e.length} group(s) found.`)}),yg=Se("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>hc(e,{scope:$(t,"scope"),maxLoc:T(t,"maxLoc",15),minLoc:T(t,"minLoc",3),limit:F(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
477
- Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((r,i)=>` ${(i===0?"canonical":"duplicate").padEnd(9)} ${J(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
478
- `);return`${t}
479
- ${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>console.log(`
480
- ${e.length} group(s) found.`)}),bg=Se("twin-drift",{query:({db:e,opts:t,budget:n})=>yc(e,{scope:$(t,"scope"),minSimilarity:T(t,"minSimilarity",.3),includeHomonyms:b(t,"includeHomonyms"),limit:F(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
481
- ${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(i=>` ${J(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
482
- `),r=e.firstDivergentTokens?`
483
- first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
484
- ${n}${r}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
485
- ${e.length} group(s) found.`)}),Sg=Se("not-implemented",{query:({db:e,opts:t,budget:n})=>Oc(e,{scope:$(t,"scope"),limit:F(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${J(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
486
- ${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
487
- ${e.length} reachable placeholder stub(s).`)}),vg=Se("decorative-checkers",{query:({db:e,opts:t,budget:n})=>Mc(e,{scope:$(t,"scope"),limit:F(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${J(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.nameKind}, resolved: ${e.resolvedVia}${e.delegateTarget?` -> ${e.delegateTarget}`:""})`,emptyMessage:()=>"No decorative checker candidates found.",heuristicLabel:"decorative checker candidates",after:e=>console.log(`
488
- ${e.length} decorative checker candidate(s).`)}),xg=te("test-quality",({db:e,args:t,opts:n,budget:r})=>{let i=Fc(e,{scope:$(n,"scope"),limit:F(n,"limit",30),scanLimit:r.scanLimit,rotDays:Q(n,"rotDays")});if(b(n,"json")){I("test-quality",t,n,i,{analysisBudget:r.analysisBudget});return}if(Fe("test-quality findings"),i.assertionFree.length+i.skipped.length+i.mockEcho.length===0){L.empty("No test-quality findings.");return}i.assertionFree.length>0&&(console.log(`
489
- ASSERTION-FREE (${i.assertionFree.length})`),L.list(i.assertionFree,s=>` ${J(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),i.skipped.length>0&&(console.log(`
490
- SKIPPED (${i.skipped.length})`),L.list(i.skipped,s=>` ${s.file}:${s.startLine+1} "${s.title}" (${s.blockKind}.${s.skipKind}, age: ${s.ageDays??"unknown"}d, ${s.rot})`)),i.mockEcho.length>0&&(console.log(`
491
- MOCK-ECHO (${i.mockEcho.length})`),L.list(i.mockEcho,s=>` ${J(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
492
- ${i.assertionFree.length} assertion-free, ${i.skipped.length} skipped, ${i.mockEcho.length} mock-echo.`)}),Rg=it({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let r=O(t,0),i=O(t,1),o=$(n,"out")??Lc(r,i),s=ve(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=Dc(e,r,i,s);if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=EC(e.config.projectRoot,s);if(!b(n,"force")&&$C(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return CC(TC(s),{recursive:!0}),PC(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
493
- Wrote behavioral A/B scaffold: ${e.outPath}`),console.log(` A: ${e.a.shortName} (${J(e.a.file,e.a.startLine,e.a.startLine)})`),console.log(` B: ${e.b.shortName} (${J(e.b.file,e.b.startLine,e.b.startLine)})`);let t=e.signatureCompatible===null?"unknown":e.signatureCompatible?"compatible":"MISMATCH";console.log(` Signature compatibility: ${t}`),console.log(`
494
- Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),kg=te("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=Oi(e,{scope:$(n,"scope"),minLoc:T(n,"minLoc",1),maxDepth:T(n,"maxDepth",5),scanLimit:r.scanLimit}),o=re(),s=b(n,"patch"),a=b(n,"json"),c=b(n,"verify")||s;if(s&&!b(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){I("cleanup-plan",t,n,i,{analysisBudget:r.analysisBudget});return}return L.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=no(i),d=c?Zi(o,i):void 0;if(a){I("cleanup-plan",t,n,{result:i,verification:d},{analysisBudget:r.analysisBudget});return}if(s){let u=ro(d,l);if(u.length>0){for(let g of u)console.error(`error: ${g}`);process.exitCode=1;return}let m=Ed(o,l);if(m.trim()===""){console.error("error: verified cleanup plan produced an empty patch."),process.exitCode=1;return}console.error(`cleanup-plan --patch: ${l.length} verified batch(es), ${i.totalLoc} LOC.`),console.log(m);return}console.log(`Cleanup plan: ${i.totalSymbols} symbol(s), ${i.totalLoc} LOC across ${i.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
495
- `);for(let u of i.batches){let m=u.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${u.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${u.depth}: dead once batch ${u.depth-1} lands (cascade, ${u.loc} LOC) \u2500\u2500`;console.log(m);for(let g of u.entries)console.log(` ${g.file}:${g.startLine+1}-${g.endLine+1} ${g.shortName} (${g.loc} LOC)`);u.filesEmptied.length>0&&console.log(` -> empties: ${u.filesEmptied.join(", ")}`),console.log("")}if(i.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let u of i.blocked)console.log(` ${u.shortName} (${u.file}) blocked by ${u.blockingFiles.join(", ")}`)}if(d){if(console.log(`
496
- Verifying batches against the project checker (throwaway worktree at HEAD)...`),d.checkers.length===0){console.log(" No checker detected (need tsconfig.json, go.mod, Python project markers, Clojure project markers, or Cargo.toml) -- skipped.");return}for(let g of d.checkers)console.log(` Checker: ${g}`);if(d.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${d.uncoveredFiles.join(", ")}`),d.baselineErrors>0&&console.log(` Baseline has ${d.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),d.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${d.dirtyOverlap.join(", ")}`),d.dirtyWorkingTree.length>0){let g=d.dirtyWorkingTree.slice(0,5),f=d.dirtyWorkingTree.length-g.length;console.log(` WARNING: verification ran at HEAD; ${d.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${g.join(", ")}${f>0?`, ... ${f} more`:""}`)}let u=IC(d.checkers),m=AC(d.checkers);for(let g of d.batches)if(g.status==="verified")console.log(` Batch ${g.depth}: VERIFIED (${u})${m}`);else{console.log(` Batch ${g.depth}: FAILED${g.reason?` (${g.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let f of g.errors??[])console.log(` ${f}`)}}}),wg=te("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!b(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let r=b(t,"all"),i=Q(t,"batch");if(r===(i!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=Oi(e,{scope:$(t,"scope"),minLoc:T(t,"minLoc",1),maxDepth:T(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){L.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=no(o,{all:r,batch:i});if(s.length===0){console.error(`error: No cleanup batch ${i} exists.`),process.exitCode=1;return}let a=re(),c=Zi(a,o),l=ro(c,s,{allowDirty:b(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}to(a,s);let d=s.reduce((m,g)=>m+g.entries.length,0),u=s.reduce((m,g)=>m+g.loc,0);console.log(`Applied ${s.length} verified cleanup batch(es): ${d} symbol(s), ${u} LOC.`)});function IC(e){return e.join(", ")}function AC(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var $g=te("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=b(n,"full"),o=Nc(e,{windowCommits:T(n,"window",100),minSimilarity:Q(n,"minSimilarity"),limit:F(n,"limit",30),scope:$(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic,historyMode:i?"full":"bounded"});if(b(n,"json")){I("recent-duplicates",t,n,o,{analysisBudget:r.analysisBudget});return}if(!o.available)return L.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return L.empty(`No recent re-implementations found (window: last ${o.windowCommits} commits).`);Fe("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
497
- `);let s=o.rootCauseGroups?.filter(a=>a.count>1)??[];if(s.length>0){console.log(`Root-cause groups (${s.length}):`);for(let a of s)console.log(` ${a.count} pair(s) ${a.kind.toUpperCase()} ${a.domain} ${Math.round(a.maxSimilarity*100)}% max`),a.establishedFile&&a.establishedSymbol&&console.log(` established: ${a.establishedFile} ${a.establishedSymbol}`),console.log(` files: ${a.relatedFiles.slice(0,6).join(", ")}`),console.log(` -> ${a.recommendation}`);console.log("")}for(let a of o.findings){let c=a.sharedEvidence.slice(0,16).join(", ");a.kind==="echo"?(console.log(` ${Math.round(a.similarity*100)}% ECHO ${a.domain} ${a.echoFile} ${a.echoSymbol} (added ${a.echoAgeCommits} commits ago)`),console.log(` duplicates established ${a.establishedFile} ${a.establishedSymbol}`)):(console.log(` ${Math.round(a.similarity*100)}% TWIN ${a.domain} ${a.echoFile} ${a.echoSymbol}`),console.log(` and ${a.establishedFile} ${a.establishedSymbol} (both new \u2014 consolidate before they diverge)`)),console.log(` basis: ${a.basis}`),c.length>0&&console.log(` shared: ${c}`)}console.log(`
498
- ${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Cg=be(({db:e,args:t,opts:n})=>{let r=b(n,"full"),i=gc(e,{doc:t[0]===void 0?void 0:O(t,0),limit:F(n,"limit",20),minCoupling:T(n,"minCoupling",3),includeSnapshotExcluded:r,historyMode:r?"full":"bounded"});if(b(n,"json")){I("doc-drift",t,n,i);return}if(!i.available)return L.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return L.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);Fe("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
499
- `);for(let o of i.findings){let s=o.snapshotExcluded?" [snapshot (excluded by policy)]":"",a=o.docLastChangedAtEstimated?" [docLastChangedAt estimated from file mtime]":"";console.log(` staleness ${o.staleness} ${o.doc}${s}${a}`);for(let c of o.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${c} \u2014 that file no longer exists`);for(let c of o.subjects.slice(0,4)){let l=c.evidence==="both"?`referenced by doc + coupled ${c.coChanges}x`:c.evidence==="reference"?"referenced by doc":`coupled ${c.coChanges}x historically`;console.log(` ${c.changesSinceDocUpdate} change(s) since doc update ${c.file} (${l}; ${c.actionTier}/${c.docIntent})`);let d=c.docIntentReasons[0];d&&console.log(` intent: ${d}`);let u=c.citationContexts?.[0];u&&console.log(` cited claim: ${hr(u)}`)}}console.log(`
500
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),Pg=Se("unused-params",{query:({db:e,opts:t,budget:n})=>$c(e,{scope:$(t,"scope"),limit:F(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${J(e.file,e.startLine,e.endLine)} ${e.shortName}
501
- trailing unused: ${e.unusedTrailing.join(", ")} (${e.unusedTrailing.length} of ${e.paramCount} params -- type-safe to remove at the signature; check call sites for side-effectful arguments)`,emptyMessage:()=>"No trailing unused parameters found.",heuristicLabel:"unused trailing parameter candidates",after:e=>console.log(`
502
- ${e.length} function(s) with trailing unused parameters.`)});var Tg=Ee("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>tc(e,{minSimilarity:T(n,"minSimilarity",.62),minTokens:T(n,"minTokens",8),limit:F(n,"limit",20),scope:$(n,"scope"),scanLimit:r.scanLimit,filePattern:z(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{L.list(e,t=>{let n=[`
503
- ${Math.round(t.similarity*100)}% similar React structure:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedNativeTags.length&&n.push(` Shared native tags: ${t.sharedNativeTags.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),n.join(`
504
- `)}),console.log(`
505
- ${e.length} duplicated React component pair(s) found.`)}}),Eg=Ee("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>nc(e,{minSimilarity:T(n,"minSimilarity",.45),minSharedBehaviors:T(n,"minSharedBehaviors",6),limit:F(n,"limit",20),scope:$(n,"scope"),scanLimit:r.scanLimit,filePattern:z(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{L.list(e,t=>{let n=[`
506
- ${Math.round(t.similarity*100)}% similar React behavior:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedHooks.length&&n.push(` Shared hooks: ${t.sharedHooks.join(", ")}`),t.sharedReactHooks.length&&n.push(` Shared React hooks: ${t.sharedReactHooks.join(", ")}`),t.sharedEffects.length&&n.push(` Shared effects: ${t.sharedEffects.join(", ")}`),t.sharedState.length&&n.push(` Shared state: ${t.sharedState.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedHandlers.length&&n.push(` Shared handlers: ${t.sharedHandlers.slice(0,12).join(", ")}`),t.sharedHandlerVerbs.length&&n.push(` Shared action verbs: ${t.sharedHandlerVerbs.slice(0,12).join(", ")}`),n.join(`
507
- `)}),console.log(`
508
- ${e.length} React hook candidate pair(s) found.`)}}),Ig=Ee("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>rc(e,{minComponentLines:T(n,"minComponentLines",300),minFileLines:T(n,"minFileLines",800),minJsxTokens:T(n,"minJsxTokens",80),minBehaviorTokens:T(n,"minBehaviorTokens",40),limit:F(n,"limit",20),scope:$(n,"scope"),scanLimit:r.scanLimit,filePattern:z(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{L.list(e,t=>[`
509
- ${t.componentLines} component line(s): ${t.component} (${t.file})`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` File lines: ${t.fileLines}; JSX tokens: ${t.jsxTokens}; behavior tokens: ${t.behaviorTokens}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`,` Reasons: ${t.reasons.join("; ")}`].join(`
510
- `)),console.log(`
511
- ${e.length} large React component(s) found.`)}}),Ag=Ee("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>ic(e,{minSimilarity:T(n,"minSimilarity",.62),minTokens:T(n,"minTokens",8),limit:F(n,"limit",20),scope:$(n,"scope"),scanLimit:r.scanLimit,filePattern:z(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{L.list(e,t=>{let n=[`
512
- ${Math.round(t.similarity*100)}% similar Vue structure:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedDirectives.length&&n.push(` Shared directives: ${t.sharedDirectives.join(", ")}`),t.sharedSlots.length&&n.push(` Shared slots: ${t.sharedSlots.join(", ")}`),t.sharedIdentifiers.length&&n.push(` Shared identifiers: ${t.sharedIdentifiers.slice(0,20).join(", ")}`),n.join(`
513
- `)}),console.log(`
514
- ${e.length} duplicated Vue component pair(s) found.`)}}),jg=Ee("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>oc(e,{minSimilarity:T(n,"minSimilarity",.45),minSharedBehaviors:T(n,"minSharedBehaviors",6),limit:F(n,"limit",20),scope:$(n,"scope"),scanLimit:r.scanLimit,filePattern:z(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{L.list(e,t=>{let n=[`
515
- ${Math.round(t.similarity*100)}% similar Vue behavior:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComposables.length&&n.push(` Shared composables: ${t.sharedComposables.join(", ")}`),t.sharedStores.length&&n.push(` Shared stores: ${t.sharedStores.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedLifecycle.length&&n.push(` Shared lifecycle: ${t.sharedLifecycle.join(", ")}`),t.sharedFunctions.length&&n.push(` Shared functions: ${t.sharedFunctions.slice(0,12).join(", ")}`),t.sharedFunctionVerbs.length&&n.push(` Shared action verbs: ${t.sharedFunctionVerbs.slice(0,12).join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),t.sharedTemplateEvents.length&&n.push(` Shared template events: ${t.sharedTemplateEvents.slice(0,20).join(", ")}`),n.join(`
516
- `)}),console.log(`
517
- ${e.length} Vue composable candidate pair(s) found.`)}}),Lg=Ee("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>sc(e,{minTotalLines:b(n,"reviewThresholds")&&Gl(n,"minTotalLines")==="default"?300:T(n,"minTotalLines",800),minTemplateLines:T(n,"minTemplateLines",300),minScriptLines:T(n,"minScriptLines",300),minStyleLines:T(n,"minStyleLines",500),limit:F(n,"limit",20),scope:$(n,"scope"),scanLimit:r.scanLimit,filePattern:z(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{L.list(e,t=>{let n=[`
518
- ${t.totalLines} total line(s): ${t.file}`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` Blocks: template ${t.templateLines}, script ${t.scriptLines}, style ${t.styleLines}, external script ${t.externalScriptLines}, custom ${t.customBlockLines}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`];return t.externalScriptPaths.length&&n.push(` External scripts: ${t.externalScriptPaths.join(", ")}`),n.push(` Reasons: ${t.reasons.join("; ")}`),n.join(`
519
- `)}),console.log(`
520
- ${e.length} large Vue view pressure file(s) found.`)}});function le(e){return{docs:C("Cleanup"),...e}}function ie({heuristicLabel:e,...t}){return le({...t,heuristic:{label:e}})}var fi=[le({id:"unused-params",command:"unused-params",agent:k("Which trailing parameters are never read by their bodies?","candidate parameters with callable and file identities",[],"bounded","repository"),description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:E([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings",x,30),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:C("Cleanup",["scip-query unused-params -s src/services"]),handler:Pg}),le({id:"cleanup-plan",command:"cleanup-plan",agent:k("What code can be deleted safely, and in what dependency order?","ordered cleanup batches, evidence, and optional verification outcomes",[],"bounded","repository"),description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",x,1),p("--max-depth <n>","Maximum cascade depth",x,5),p("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),p("--patch","With --verify, print the compiler-verified deletion patch to stdout"),p("--json","Output as JSON for programmatic consumption"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:C("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:kg}),le({id:"cleanup-apply",command:"cleanup-apply",agent:k("Can a compiler-verified cleanup batch be applied to this working tree?","applied files, deletions, verification, and refusal reasons",[],"bounded","repository"),description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",x,1),p("--max-depth <n>","Maximum cascade depth",x,5),p("--verified","Required: verify the selected cleanup batch before applying it"),p("--batch <n>","Apply one batch depth",x),p("--all","Apply every compiler-verified batch in the plan"),p("--force-dirty","Allow applying when plan files already have working-tree edits"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:C("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:wg}),le({id:"recent-duplicates",command:"recent-duplicates",agent:k("Did recent code reimplement established code?","recent and established symbol pairs with similarity evidence",[],"bounded","repository"),description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:E([p("--window <n>",'How many commits back counts as "recent"',x,100),p("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",we),p("-n, --limit <n>","Maximum findings",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:C("Cleanup",["scip-query recent-duplicates --window 50"]),handler:$g}),le({id:"doc-drift",command:"doc-drift [doc]",agent:k("Which documentation may be stale relative to changing code?","document paths, coupled code subjects, and history evidence",["path"],"bounded","repository"),description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:E([p("-n, --limit <n>","Maximum docs to report",x,20),p("--min-coupling <n>","Minimum historical co-changes to track a subject",x,3),p("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:C("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Cg}),le({id:"dead",command:"dead [scope]",agent:k("Which symbols have no repository use or only file-internal use?","symbol identities, ranges, liveness classes, and evidence",["path"],"bounded","repository"),description:"Find repository-dead code, file-internal symbols, and implicit-usage signals",options:E([p("--min-loc <n>","Only show symbols >= N lines",x,1),p("--include-tests","Include definitions from test files (test references always count)"),p("--skip-barrels","Ignore refs from barrel re-export files"),p("--include-members","Include class members"),p("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),p("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:C("Cleanup",["scip-query dead --min-loc 10"]),handler:ng}),le({id:"unused-imports",command:"unused-imports <file>",agent:k("Which imports in this file are unused?","import symbol identities and source ranges",["file"],"bounded"),description:"Find imports not referenced in the same file",options:E([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:rg}),le({id:"isolated",command:"isolated",agent:k("Which symbols are disconnected from the repository reference graph?","isolated symbol identities and files",[],"bounded","repository"),description:"Find completely orphaned symbols (no references at all)",options:E([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum lines of code",x,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:ig}),ie({id:"similar",command:"similar [symbol] [other]",agent:k("Which callable resembles this one, or how similar are these two?","symbol pairs, similarity scores, and shared evidence",["symbol","symbol"],"bounded","repository"),description:"Find heuristic function similarity candidates from callee fingerprints",options:E([p("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",we,.4),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-callees <n>","Minimum callees to consider",x,4),p("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),p("--plan","Render a consolidation preview for two symbols"),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:ug}),ie({id:"similar-files",command:"similar-files [file]",agent:k("Which files have similar callable structure?","file pairs with similarity scores and shared symbols",["file"],"bounded","repository"),description:"Find heuristic similar-file candidates from dependency profiles",options:E([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",we,.5),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-deps <n>","Minimum dependencies to consider",x),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:pg}),ie({id:"react-component-duplicates",command:"react-component-duplicates [file]",agent:k("Which React components appear to duplicate one another?","component pairs with structural similarity evidence",["file"],"bounded","repository"),description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:E([p("--min-similarity <n>","Minimum JSX structure similarity (0-1)",we,.62),p("--min-tokens <n>","Minimum structural tokens to consider",x,8),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Tg}),ie({id:"react-hook-candidates",command:"react-hook-candidates [file]",agent:k("Which repeated React logic could become a custom hook?","component groups and shared hook-shaped behavior",["file"],"bounded","repository"),description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:E([p("--min-similarity <n>","Minimum behavior similarity (0-1)",we,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Eg}),ie({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",agent:k("Which React components have evidence of being too large or overloaded?","component identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:E([p("--min-component-lines <n>","Minimum component lines",x,300),p("--min-file-lines <n>","Minimum file lines",x,800),p("--min-jsx-tokens <n>","Minimum JSX structure tokens",x,80),p("--min-behavior-tokens <n>","Minimum behavior tokens",x,40),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Ig}),ie({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",agent:k("Which Vue components appear to duplicate one another?","component pairs with structural similarity evidence",["file"],"bounded","repository"),description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:E([p("--min-similarity <n>","Minimum template similarity (0-1)",we,.62),p("--min-tokens <n>","Minimum structural tokens to consider",x,8),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Ag}),ie({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",agent:k("Which repeated Vue logic could become a composable?","component groups and shared composable-shaped behavior",["file"],"bounded","repository"),description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:E([p("--min-similarity <n>","Minimum behavior similarity (0-1)",we,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:jg}),ie({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",agent:k("Which Vue views have evidence of being too large or overloaded?","view identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:E([p("--min-total-lines <n>","Minimum total component lines",x,800),p("--min-template-lines <n>","Minimum template lines",x,300),p("--min-script-lines <n>","Minimum script lines",x,300),p("--min-style-lines <n>","Minimum style lines",x,500),p("--review-thresholds","Use lower review thresholds without changing health scoring"),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Lg}),ie({id:"similar-chains",command:"similar-chains",agent:k("Which transitive chains of similar symbols suggest repeated designs?","similarity-connected symbol chains and scores",[],"bounded","repository"),description:"Find heuristic similar-chain candidates from dependency flows",options:E([p("--min-similarity <n>","Minimum chain similarity (0-1)",we,.5),p("-n, --limit <n>","Number of results",x,15),p("-s, --scope <path>","Limit to files matching path"),p("--min-length <n>","Minimum chain length",x,3),p("--max-length <n>","Maximum chain length",x,8),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:mg}),ie({id:"extract-candidates",command:"extract-candidates",agent:k("Which cohesive code regions are strong extraction candidates?","symbol identities with cohesion, reuse, and extraction evidence",[],"bounded","repository"),description:"Find heuristic extraction candidates from isolated callee clusters",options:E([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum function LOC",x,10),p("--min-callees <n>","Minimum callees to analyze",x,6),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:og}),ie({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",agent:k("Which definitions live far from most of their consumers?","symbols, current homes, consumer locality, and suggested homes",[["symbol","file"]],"bounded","repository"),description:"Find directory-locality and ancestry candidates from consumer ownership",options:E([p("-s, --scope <path>","Limit scan mode to files matching path"),p("--min-consumers <n>","Minimum consumers in scan mode",x,1),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:C("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:sg}),ie({id:"drift",command:"drift [module]",agent:k("Where has a module or abstraction drifted across parallel implementations?","drifted symbol families, files, and evidence",["module"],"bounded","repository"),description:"Detect drift candidates: unused imports and declared architecture violations; pass --architecture for boundary context",options:E([p("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",Ke,5),p("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),p("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),p("-n, --limit <n>","Number of results",x,50),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:fg}),ie({id:"wrapper-candidates",command:"wrapper-candidates",agent:k("Which callables are unnecessary forwarding wrappers?","wrapper identities, targets, and forwarding evidence",[],"bounded","repository"),description:"Find heuristic wrapper candidates only called by one consumer (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:E([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",x,15),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:ag}),ie({id:"passthrough-candidates",command:"passthrough-candidates",agent:k("Which parameters are passed through layers without local use?","parameter paths across call chains",[],"bounded","repository"),description:"Find heuristic passthrough candidates that forward to one callee",options:E([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",x,15),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:cg}),ie({id:"stale-abstractions",command:"stale-abstractions",agent:k("Which abstractions no longer earn their indirection?","abstraction identities with usage, change, and replacement evidence",[],"bounded","repository"),description:"Find heuristic stale abstraction candidates with 0-1 consumers (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:E([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",x,3),p("-n, --limit <n>","Number of results",x,30),p("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:lg}),ie({id:"complexity-hotspots",command:"complexity-hotspots",agent:k("Which symbols combine high complexity with high change pressure?","ranked symbols with complexity and churn evidence",[],"bounded","repository"),description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:E([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",x,10),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:dg}),le({id:"convergence",command:"convergence <symbol1> <symbol2>",agent:k("How should these two similar symbols converge?","deprecated alias result for a two-symbol similarity plan",["symbol","symbol"],"bounded"),evidence:"heuristic",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:E([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:gg}),Ff({id:"redundant-reexports",command:"redundant-reexports",agent:k("Which re-exports add no useful API boundary?","re-export sites, original definitions, and consumer evidence",[],"bounded","repository"),description:"Find barrel re-exports that nobody imports through",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded analysis on large indexes")],docs:C("Cleanup"),query:({db:e,opts:t})=>Zc(e,{scope:$(t,"scope"),limit:F(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
521
- barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
522
- Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
523
- Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
524
- ${e.length} redundant re-export(s).`)}),le({id:"duplicate-bodies",command:"duplicate-bodies",agent:k("Which callable bodies are exact duplicates?","callable groups with exact normalized-body identity",[],"bounded","repository"),description:"Find exact duplicate small-body candidates across files",options:E([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC per function body",x,15),p("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",x,3),p("-n, --limit <n>","Number of groups",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:yg}),le({id:"twin-drift",command:"twin-drift",agent:k("Which same-concept twin implementations have drifted?","twin symbol pairs, history, and divergence evidence",[],"bounded","repository"),description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:E([p("-s, --scope <path>","Limit to files matching path"),p("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",we,.3),p("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),p("-n, --limit <n>","Number of groups",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:bg}),ie({id:"not-implemented",command:"not-implemented",agent:k("Which callables are placeholders rather than real implementations?","callable identities and placeholder evidence",[],"bounded","repository"),description:"Reachable placeholder stub candidates (throw-stub, TODO+return-default, empty body) \u2014 production callers can actually reach these; an unreachable stub is dead's job, not this one's",options:E([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"reachable placeholder stubs",budget:"candidate-scan",renderShape:"list",docs:C("Cleanup",["scip-query not-implemented -s src/services"]),handler:Sg}),ie({id:"decorative-checkers",command:"decorative-checkers",agent:k("Which validation checks cannot meaningfully fail?","checker identities, call sites, and decorative behavior evidence",[],"bounded","repository"),description:"Decorative checker candidates: validate*/verify*/check*/assert*/is*/has* callables with no reachable failure exit anywhere in their body",options:E([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"decorative checker candidates",budget:"candidate-scan",renderShape:"list",docs:C("Cleanup",["scip-query decorative-checkers -s src/services"]),handler:vg}),le({id:"test-quality",command:"test-quality",agent:k("Which tests have weak assertions or poor production-code reach?","test identities with assertion and reachability evidence",[],"bounded","repository"),description:"Test-quality candidates: assertion-free it/test bodies, a skipped-test ledger with git-blame age, and mock-echo tests that assert the same literal they stubbed into a mock",options:E([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings per sub-check",x,30),p("--rot-days <n>","Skips older than this many days are reported as rot",x,60),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"test-quality findings"},renderShape:"custom",docs:C("Cleanup",["scip-query test-quality -s tests/queries"]),handler:xg}),le({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",agent:k("How do these two twin implementations differ in structure and behavior?","side-by-side symbol evidence and divergence classification",["symbol","symbol"],"complete"),description:"Generate a behavioral A/B scaffold comparing two same-concept twins (scip-audit integrity scenario) \u2014 a ready-to-fill vitest file, not an auto-executor",options:E([p("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),p("--force","Overwrite an existing scaffold file at the output path")]),evidence:"heuristic",renderShape:"custom",docs:C("Cleanup",["scip-query twin-ab src/a.ts/escapeRegex src/b.ts/escapeRegExp"]),handler:Rg}),le({id:"similar-signatures",command:"similar-signatures",agent:k("Which callables have suspiciously similar signatures?","callable pairs with signature similarity evidence",[],"bounded","repository"),description:"Find functions with near-identical type signatures (same shape)",options:E([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC per function",x,3),p("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",x,12),p("-n, --limit <n>","Number of groups",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:hg})];var jC=be(({db:e,args:t,opts:n})=>{let r=Dt(e);if(b(n,"json")){I("stats",t,n,r);return}console.log(`Documents: ${r.documents}`),console.log(`Symbols: ${r.symbols}`),console.log(`Definitions: ${r.definitions}`),console.log(`References: ${r.references}`),console.log(`Index size: ${Ue(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Dg=[{id:"stats",command:"stats",description:"Show index statistics",agent:k("How large and fresh is the current index?","document, symbol, definition, reference, size, and build-time totals",[],"complete","repository"),options:[Fl()],renderShape:"custom",docs:C("Core"),handler:jC}];var LC=br("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Ga(e,{limit:F(t,"limit",20),scope:$(t,"scope"),minFanIn:T(t,"minFanIn",2),minFanOut:T(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.actionTier.padEnd(6)} ${e.riskKind.padEnd(20)} ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),DC=be(({db:e,args:t,opts:n})=>{let r=z(t,0),i=F(n,"limit",30);if(r){let c=Fa(e,r);if(b(n,"json")){I("fan-in",t,n,{mode:"symbol",symbol:r,rows:c});return}if(c.length===0)return L.empty(`No fan-in for ${r}.`);L.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let o=_a(e,{limit:i,scope:$(n,"scope")});if(b(n,"json")){I("fan-in",t,n,{mode:"top",rows:o});return}let s=new Map;for(let c of o)s.set(c.name,(s.get(c.name)??0)+1);let a=new Set([...s].filter(([,c])=>c>1).map(([c])=>c));L.table(["files","symbol"],o.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),OC=be(({db:e,args:t,opts:n})=>{let r=z(t,0),i=F(n,"limit",30);if(r){let s=Na(e,r);if(b(n,"json")){I("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return L.empty(`No fan-out for ${r}.`);L.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Ba(e,{limit:i,scope:$(n,"scope")});if(b(n,"json")){I("fan-out",t,n,{mode:"top",rows:o});return}L.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),MC=be(({db:e,args:t,opts:n})=>{let r=z(t,0),i=z(t,1),o=F(n,"limit",20);if(r&&i){let a=qa(e,r,i);if(b(n,"json")){I("coupling",t,n,{mode:"pair",result:a});return}console.log(`${a.file1} \u2194 ${a.file2}: ${a.sharedSymbols} shared symbols (${a.actionTier})`),console.log(` Risk: ${a.couplingKind}`),console.log(` Recommendation: ${a.recommendation}`);return}let s=Va(e,{limit:o,scope:$(n,"scope")});if(b(n,"json")){I("coupling",t,n,{mode:"top",rows:s});return}L.table(["tier","risk","shared","file1 \u2192 file2"],s.map(a=>` ${a.actionTier.padEnd(6)} ${a.couplingKind.padEnd(22)} ${String(a.sharedSymbols).padStart(6)} ${a.file1} \u2192 ${a.file2}`))}),FC=it({commandName:"cycles",query:({db:e,opts:t})=>Wa(e,{scope:$(t,"scope"),maxDepth:T(t,"maxDepth",10)}),emptyMessage:e=>e.cycles.length===0?e.truncated?`No circular dependencies found. Search truncated at depth ${e.maxDepth}; deeper cycles may exist.`:"No circular dependencies found.":void 0,toJson:e=>e,render:e=>{let t=e.cycles.filter(r=>r.kind==="real"),n=e.cycles.filter(r=>r.kind==="module-hierarchy");for(let r=0;r<t.length;r++){console.log(`
525
- Cycle ${r+1} (${t[r].path.length-1} files):`);for(let i=0;i<t[r].path.length;i++){let o=i<t[r].path.length-1?" \u2192":" (cycle)";console.log(` ${t[r].path[i]}${o}`)}}t.length===0?console.log("No real circular dependencies found."):console.log(`
526
- ${t.length} real cycle(s) found.`),e.truncated&&console.log(`(search truncated at depth ${e.maxDepth} \u2014 deeper cycles may exist)`),n.length>0&&console.log(`(${n.length} module-hierarchy cycle(s) hidden \u2014 barrel files participating in normal parent/child re-export patterns. Pass --include-module-hierarchy to see them.)`)}}),NC=it({commandName:"architecture",query:({db:e,opts:t})=>Ha(e,{scope:$(t,"scope")}),emptyMessage:e=>e.configured?void 0:"No architecture boundaries configured. Add architecture.boundaries to .scipquery.json.",render:e=>{if(console.log(`Mapped ${e.coverage.mappedFiles}/${e.coverage.totalFiles} indexed file(s) across ${e.boundaries.length} boundary(ies); ${e.policyCoverage.declaredRows}/${e.policyCoverage.totalBoundaries} dependency row(s) declared.`),e.policyCoverage.missingRows.length>0){let t=e.policyCoverage.requiresCompletePolicy?" [violates requireCompletePolicy]":"";console.log(`Missing dependency rows: ${e.policyCoverage.missingRows.join(", ")}${t}`)}if(e.coverage.unmappedFiles.length>0&&console.log(`Unmapped files: ${e.coverage.unmappedFiles.length}`),e.coverage.ambiguousFiles.length>0){console.log(`Ambiguous files: ${e.coverage.ambiguousFiles.length}`);for(let t of e.coverage.ambiguousFiles.slice(0,5))console.log(` ${t.file} -> ${t.boundaries.join(", ")}`)}if(e.forbiddenEdges.length>0){console.log(`
527
- Forbidden boundary edges (${e.forbiddenEdges.length}):`);for(let t of e.forbiddenEdges){console.log(` ${t.from} -> ${t.to}: ${t.fileEdgeCount} file edge(s), ${t.importerCount} importer(s), ${t.importedFileCount} imported file(s)`);for(let n of t.examples)console.log(` ${n.fromFile} -> ${n.toFile}`)}}else console.log(`
528
- No declared boundary violations found.`);if(e.staleAllowances.length>0){console.log(`
529
- Stale dependency allowances (${e.staleAllowances.length}): declared but unused, so the policy is wider than the code requires.`);for(let t of e.staleAllowances)console.log(` ${t.from} -> ${t.to}`)}if(e.boundaryLimits.length>0){console.log(`
530
- Boundaries over configured limits (${e.boundaryLimits.length}):`);for(let t of e.boundaryLimits)console.log(` ${t.boundary}: ${t.kind} ${t.observed} exceeds limit ${t.limit}`)}if(e.testBoundaryViolations.length>0){console.log(`
531
- Test boundary violations (${e.testBoundaryViolations.length}): a test reaches further than the boundary of the code it covers is allowed to reach.`);for(let t of e.testBoundaryViolations.slice(0,20)){let n=t.ownerBoundary??"(no subject found)";console.log(` ${t.testFile} [${n}] -> ${t.importedBoundary} (${t.importedFile})`)}e.testBoundaryViolations.length>20&&console.log(` ... +${e.testBoundaryViolations.length-20} more`)}if(e.fragileEdges.length>0){console.log(`
532
- Single-import boundary edges (${e.fragileEdges.length} of ${e.edges.length}): the whole boundary dependency is carried by one file-level import. Breadth alone does not establish importance -- inspect before concluding either way.`);for(let t of e.fragileEdges.slice(0,10)){let n=t.examples[0];console.log(` ${t.from} -> ${t.to}${n?` (${n.fromFile} -> ${n.toFile})`:""}`)}e.fragileEdges.length>10&&console.log(` ... +${e.fragileEdges.length-10} more`)}if(e.coarseBoundaries.length>0){console.log(`
533
- Boundaries too coarse to check (${e.coarseBoundaries.length}): these own an internal dependency cycle that the boundary graph cannot express, so requireAcyclic reports nothing about the code inside them.`);for(let t of e.coarseBoundaries){console.log(` ${t.boundary}: ${t.subUnits.join(" <-> ")}`);for(let n of t.narrowestEdges){console.log(` narrowest: ${n.from} -> ${n.to} (${n.fileEdgeCount} file edge(s))`);for(let r of n.examples.slice(0,3))console.log(` ${r.fromFile} -> ${r.toFile}`)}}}if(e.edges.length>0){console.log(`
534
- Boundary graph (${e.edges.length} directed edge(s)):`);for(let t of e.edges)console.log(` ${t.from} -> ${t.to} ${t.policyStatus.padEnd(10)} ${t.fileEdgeCount} file edge(s)`)}if(e.reciprocalPairs.length>0){console.log(`
535
- Reciprocal boundary pairs (${e.reciprocalPairs.length}):`);for(let t of e.reciprocalPairs)console.log(` ${t.boundaries[0]} <-> ${t.boundaries[1]} ${t.forward.fileEdgeCount}/${t.reverse.fileEdgeCount} file edge(s)`)}if(e.cycles.length>0){console.log(`
536
- Strongly connected boundary groups (${e.cycles.length}):`);for(let t of e.cycles){let n=t.violatesPolicy?" [violates requireAcyclic]":"";console.log(` { ${t.boundaries.join(", ")} }${n}`);for(let r of t.narrowestEdges)console.log(` inspect ${r.from} -> ${r.to}: ${r.fileEdgeCount} file edge(s)`)}}}}),_C=it({commandName:"deep-chains",query:({db:e,opts:t})=>za(e,{limit:F(t,"limit",10),scope:$(t,"scope"),minDepth:T(t,"minDepth",3)}),emptyMessage:e=>e.length===0?"No deep chains found.":void 0,render:e=>{for(let t=0;t<e.length;t++){console.log(`
537
- Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].components){let r=n.length===1?n[0]:`{ ${n.join(", ")} } (cycle)`;console.log(` \u2192 ${r}`)}console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),Og=[ai({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",agent:k("Which symbols are the largest reference choke points?","ranked symbol identities with reference and file counts",[],"bounded","repository"),options:[p("-n, --limit <n>","Number of results",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")],docs:C("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>ja(e,{limit:F(t,"limit",30),scope:$(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",agent:k("How many files reference this symbol, or which symbols have highest fan-in?","exact symbols with referencing-file counts",["symbol"],"bounded","repository"),options:E([p("-n, --limit <n>","Number of results for top mode",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:C("Graph"),handler:DC},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",agent:k("How many external symbols does this file use, or which files have highest fan-out?","files with external-symbol counts",["file"],"bounded","repository"),options:E([p("-n, --limit <n>","Number of results for top mode",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:C("Graph"),handler:OC},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",agent:k("How strongly are these files coupled, or which pairs are most coupled?","file pairs with coupling evidence and scores",["file","file"],"bounded","repository"),options:E([p("-n, --limit <n>","Number of results for top mode",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:C("Graph"),handler:MC},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",agent:k("Which file dependency cycles exist?","dependency-cycle file chains",[],"bounded","repository"),options:E([p("-s, --scope <path>","Limit to files matching path"),p("--max-depth <n>","Bound DFS search depth",x,10)]),renderShape:"custom",docs:C("Graph"),handler:FC},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",agent:k("Does the repository obey its declared architecture boundaries?","boundary coverage and dependency-rule violations",[],"complete","repository"),options:E([p("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",renderShape:"custom",docs:C("Graph",["scip-query architecture --json"]),handler:NC},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",agent:k("Which files are high-connectivity coupling hubs?","ranked files with fan-in and fan-out counts",[],"bounded","repository"),options:E([p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-fan-in <n>","Minimum fan-in",x,2),p("--min-fan-out <n>","Minimum fan-out",x,2),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:C("Graph"),handler:LC},{id:"deep-chains",command:"deep-chains",description:"Find the longest condensed dependency-component chains",agent:k("Which dependency chains are deepest and riskiest?","ranked component chains with depth, risk, and recommendation",[],"bounded","repository"),options:E([p("-n, --limit <n>","Number of chains to show",x,10),p("-s, --scope <path>","Limit to files matching path"),p("--min-depth <n>","Minimum chain depth",x,3),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:C("Graph"),handler:_C},ci({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",agent:k("Who calls this symbol and what does it call?","caller and callee symbol identities with files",["symbol"],"bounded"),options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:C("Graph"),query:({db:e,args:t,budget:n})=>fn(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:fe(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(me(t,String(n[0])),console.log(`Symbol: ${e.shortName}
538
- `))},toJson:(e,{db:t,args:n})=>Ie(t,String(n[0]),e,"callGraph"),sections:e=>e?[{title:`CALLERS (${e.callers.length})`,rows:e.callers.map(t=>` ${t.file} ${t.shortName}`)},{title:`CALLEES (${e.callees.length})`,rows:e.callees.map(t=>` ${t.file} ${t.shortName}`)}]:[]})];var BC=te("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=O(t,0),o=_c(e,i,{semantic:r.semantic});if(b(n,"json")){I("complexity",t,n,Ie(e,i,o,"complexity"),{analysisBudget:r.analysisBudget});return}if(!o)return L.empty(fe(e,i,"Symbol not found."));me(e,i),console.log(`${J(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
539
- `),console.log(` LOC: ${o.loc}`),console.log(` Branches: ${o.branches}`),console.log(` Cyclomatic estimate: ${o.cyclomaticEstimate}`),console.log(` Callees: ${o.calleeCount}`),console.log(` Fan-in: ${o.fanIn}`),console.log(` Fan-out: ${o.fanOut}`)}),qC=be(({db:e,args:t,opts:n})=>{let r=el(e,{samples:T(n,"samples",50),scope:$(n,"scope")});if(b(n,"json")){I("self-audit",t,n,r);return}if(!r.available)return L.empty("No semantic or source-backed oracle available to audit against.");let i=r.oracleKind==="source"?"source facts":"compiler semantics";console.log(`Sampled ${r.sampleSize} symbols; ${i} oracle answered ${Math.round(r.oracleCoverage*100)}%.
540
- `),console.log(`Agreement with ${i} (file-level):`);for(let o of r.scores){let s=o.precision===null?`unverified ${o.unverified} (oracle partial \u2014 no precision claim)`:`precision ${o.precision}`;console.log(` ${o.question.padEnd(11)} ${s} recall ${o.recall} (${o.comparedSymbols} compared, ${o.skippedOraclePartial} skipped: oracle-partial)`)}if(r.topDisagreements.length>0){console.log(`
541
- Top disagreements (debugging targets):`);for(let o of r.topDisagreements)console.log(` ${o.symbol} [${o.question}]`),o.cheapOnly.length>0&&console.log(` cheap-only: ${o.cheapOnly.join(", ")}`),o.oracleOnly.length>0&&console.log(` oracle-only: ${o.oracleOnly.join(", ")}`)}}),Mg=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",agent:k("How accurate are the fast evidence paths on a sample?","sample coverage, agreement scores, and disagreements",[],"sampled","repository"),options:E([p("--samples <n>","Number of symbols to sample",x,50),p("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:C("Health",["scip-query self-audit --samples 100"]),handler:qC},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",agent:k("How structurally complex and connected is this symbol?","LOC, branch, complexity, callee, fan-in, and fan-out counts",["symbol"],"bounded"),options:E([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:C("Health"),handler:BC}];import{dirname as VC}from"path";var WC=be(({db:e,args:t,opts:n})=>{let r=O(t,0),i=dc(e,r,{maxDepth:T(n,"maxDepth",5),scope:$(n,"scope")});if(b(n,"json")){I("affected",t,n,Ie(e,r,i,"affected"));return}if(i.length===0)return L.empty(fe(e,r,"No affected symbols found."));me(e,r);let o=-1;for(let s of i)s.depth!==o&&(console.log(`
542
- \u2500\u2500 Depth ${s.depth} \u2500\u2500`),o=s.depth),console.log(` ${s.file} ${s.shortName}`);console.log(`
543
- ${i.length} affected symbol(s) across ${new Set(i.map(s=>s.file)).size} files.`)}),HC=te("co-change",({db:e,args:t,opts:n,budget:r})=>{let i=t[0]===void 0?void 0:O(t,0),o=b(n,"full"),s=pc(e,i,{minTogether:T(n,"minTogether",4),limit:F(n,"limit",30),includeLinked:n.all===!0,scanLimit:r.scanLimit,historyMode:o?"full":"bounded"});if(b(n,"json")){I("co-change",t,n,s,{analysisBudget:r.analysisBudget});return}if(!s.available)return L.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return L.empty(i?`No co-change partners found for ${i} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);Fe("co-change candidates"),console.log(i?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
544
- `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
545
- `),i&&s.findings.some(a=>a.structurallyLinked||a.declaredCouplingSuggestion)&&console.log(`note: file mode lists all historical partners; [dep edge]/[declared] pairs are excluded from hidden-coupling findings.
546
- `);for(let a of s.findings){let c=a.structurallyLinked?" [dep edge]":"",l=` [${a.partnerClass}]`,d=` [${a.commitScope}/${a.recency}]`;console.log(` ${a.together}x (${Math.round(a.confidence*100)}%) ${a.fileA} <-> ${a.fileB}${l}${d}${c}`),console.log(` history: ${a.focusedTogether} focused, ${a.broadTogether} broad-sweep (${Math.round(a.broadCommitRatio*100)}% broad), ${a.recentTogether} recent; last ${GC(a.lastTogetherAt)}`),console.log(` subjects: ${UC(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
547
- ${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function GC(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function UC(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}var JC=te("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=uc(e,O(t,0),{semantic:r.semantic});if(b(n,"json")){I("change-surface",t,n,i,{analysisBudget:r.analysisBudget});return}if(!i)return L.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
548
- `),L.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${pe(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),KC=te("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=wc(e,{base:$(n,"base"),minContainment:T(n,"minContainment",.7),maxHelpers:Q(n,"maxHelpers"),limit:F(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("incomplete-migration",t,n,i,{analysisBudget:r.analysisBudget}),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return L.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return L.empty(`No changes vs ${i.base}.`);console.log(`Incomplete migrations vs ${i.base}: ${i.changedFiles.length} changed file(s), ${i.helpersChecked} new helper(s) scored.`),i.note&&console.log(` note: ${i.note}`);for(let o of i.skipped)console.log(` skipped ${o.helperShortName} (${o.helperFile}): ${o.reason}`);if(i.findings.length===0){console.log(`
549
- No incomplete migrations detected.`);return}Fe("incomplete migration candidates");for(let o of i.findings){console.log(`
550
- ${o.helperShortName} (${o.helperFile})`),console.log(` helper shape: ${o.helperShape} (${o.specificHelperCalleeCount}/${o.helperCalleeCount} specific callees)`),console.log(` wired into: ${o.migratedFiles.join(", ")}`);for(let s of o.leftovers)console.log(` un-migrated: ${Math.round(s.containment*100)}% helper / ${Math.round(s.siteCoverage*100)}% site [${s.migrationScope}] ${s.shortName} (${s.file})`),console.log(` scope: ${s.migrationScopeReasons.join("; ")}`),s.uniqueSiteCalleeCount>0&&console.log(` extra site callees: ${s.uniqueSiteCalleeCount}`),console.log(` shared: ${s.sharedCallees.join(", ")}`)}console.log(`
551
- ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function zC(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!rt.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${rt.join(", ")}`),process.exit(1)),t}var YC=be(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Tr(Vt()))return;let r=b(t,"full"),i;try{i=$r({base:$(t,"base"),minTogether:T(t,"minTogether",6),maxEchoChecks:Q(t,"maxEchoChecks"),maxHelpers:Q(t,"maxHelpers"),includeBaseline:b(t,"baseline"),includeOutcomeLedger:n,full:r,skip:zC(t.skip)},{projectRoot:e.config.projectRoot,cacheDir:VC(e.config.dbPath)})}catch(f){let h=f instanceof Error?f.message:String(f);if(n){console.error(`diff gate FAILED CLOSED: ${h}`),process.exitCode=2;return}b(t,"json")?I("diff-gate",[],t,{exitCode:1,gateError:h,advisoryFindingCount:0,base:$(t,"base")??"HEAD",changedFiles:[],changedSymbols:0,checksRun:[],skipped:[],suppressed:[],findings:[],attributionNotes:[]},{coverage:{complete:!1,totalKnown:!1,returned:0},agentResult:{outcome:"fail",exitCode:1,gateError:h,changedFileCount:0,changedSymbolCount:0,checksRun:[],skippedChecks:[],blockingFindings:[],advisoryFindingCount:0}}):console.error(`FAIL (gate error): ${h}`),process.exitCode=1;return}let{result:o,outcomes:s,analysisBudget:a}=i,c=ar(o.findings),l=sr(o),d=o.recordCompatibility?nt("Committed suppression",o.recordCompatibility.suppressions):void 0;if(s.warning&&console.error(`note: ${s.warning}`),!n&&b(t,"json")){let f=c.length>0||l?1:0;I("diff-gate",[],t,{exitCode:f,...l?{gateError:"git diff unavailable - zero checks ran; the gate fails closed"}:{},advisoryFindingCount:o.findings.length-c.length,...a?{analysisBudget:a}:{},...o},{analysisBudget:a,coverage:r&&!l?{complete:!0,totalKnown:!0,returned:o.findings.length,total:o.findings.length,omitted:0}:{complete:!1,totalKnown:!1,returned:o.findings.length},agentResult:{outcome:f===0?"pass":"fail",exitCode:f,changedFileCount:o.changedFiles.length,changedSymbolCount:o.changedSymbols,checksRun:o.checksRun,skippedChecks:o.skipped,blockingFindings:c.map(h=>({id:h.id,check:h.check,severity:h.severity,file:h.file,symbol:h.symbol,message:h.message,remediation:h.remediation})),advisoryFindingCount:o.findings.length-c.length}}),(c.length>0||l)&&(process.exitCode=1);return}if(n){let{observed:f,now:h}=s,S=s.ledger??[];if(l){console.error("diff gate FAILED CLOSED: could not compute the git diff (diff too large, bad --base, or git error) - zero checks ran. Investigate with: scip-query diff-gate"),process.exitCode=2;return}if(d&&console.error(`note: ${d}`),c.length===0)return;let y=Gc(S,f,h),v=Uc(S,o.checksRun),w=Ll(a),R=[...y?[y]:[],xn(o),...v,...w?[w]:[]];console.error(R.join(`
552
- `)),process.exitCode=2;return}if(l){console.error("FAIL (gate error): could not compute the git diff - zero checks ran; the gate fails closed. Check --base and repository state."),process.exitCode=1;return}if(d&&console.log(`WARN: ${d}`),o.changedFiles.length===0)return L.empty(o.note??`No changes vs ${o.base}.`);console.log(`Diff gate vs ${o.base}: ${o.changedFiles.length} file(s), ${o.changedSymbols} symbol(s) changed.`);let u=o.attributionNotes.filter(f=>f.method==="unattributed");if(u.length>0)for(let f of[...new Set(u.map(h=>h.file))]){let h=u.filter(S=>S.file===f).length;console.log(`note: ${h} changed line-range(s) in ${f} belong to no indexed symbol`)}console.log(`Checks: ${o.checksRun.join(", ")}
553
- `);for(let f of o.skipped)console.log(` skipped ${f.check}: ${f.reason}`);if(o.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}Fe("diff gate candidates");let m=o.rootCauseGroups?.filter(f=>f.count>1)??[];if(m.length>0){console.log(`Root-cause groups (${m.length}):`);for(let f of m){console.log(` [${f.check}] ${f.count} finding(s), ${f.severity}${f.actionTier?`, tier: ${f.actionTier}`:""}`),(f.sourceAnalyzer||f.rootCauseKey)&&console.log(` source: ${f.sourceAnalyzer??f.check}${f.rootCauseKey?` root cause: ${f.rootCauseKey}`:""}`);let h=[...new Set([...f.files,...f.relatedFiles])].slice(0,6);h.length>0&&console.log(` files: ${h.join(", ")}`),console.log(` -> ${f.remediation}`)}console.log("")}for(let f of o.findings){if(console.log(` [${f.check}]${f.advisory?" (advisory)":""} ${f.message}`),f.partnerClass){console.log(` partner class: ${f.partnerClass}`);for(let h of f.partnerClassReasons??[])console.log(` reason: ${h}`)}f.citationKind&&console.log(` citation kind: ${f.citationKind}${f.actionTier?` (tier: ${f.actionTier})`:""}`);for(let h of f.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${hr(h)}`);f.declaredCouplingSuggestion&&console.log(` declare coupling: ${f.declaredCouplingSuggestion.name} (${f.declaredCouplingSuggestion.reason})`),console.log(` -> ${f.remediation}`)}if(c.length===0){console.log(`
554
- PASS (advisory only): ${o.findings.length} advisory finding(s) recorded \u2014 none block this diff.`);return}let g=o.findings.length-c.length;console.log(`
555
- FAIL: ${c.length} finding(s)${g>0?` (+${g} advisory)`:""}, ${o.rootCauseGroups?.length??o.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),Fg=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",agent:k("Which downstream symbols could break if this symbol changes?","affected symbol identities, files, and traversal depths",["symbol"],"bounded"),options:E([p("--max-depth <n>","Maximum traversal depth",x,5),p("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:C("Impact"),handler:WC},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",agent:k("What public surface and consumers make this file risky to change?","defined symbols, external consumer counts, and risk levels",["file"],"bounded"),options:E([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:C("Impact"),handler:JC},{id:"diff-gate",command:"diff-gate",description:"Runtime-bounded, single-flight gate for the current diff: architecture regressions plus echo, migration, coordination, doc-drift, unused-param, and new-dead candidates; exit 1 on blocking findings",options:[p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-together <n>","Minimum historical co-changes for the partner check",x,6),p("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",x),p("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",x),p("--baseline","Also run the full health-baseline ratchet"),p("--full","Run unbounded semantic and git-history analysis on large indexes"),p("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, twin-partner, coverage-contract, architecture, doc-reference, unused-params, new-dead, baseline",St,[]),p("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),p("--json","Output as JSON for programmatic consumption"),p("--compact","Emit minified one-line JSON (use with --json)")],heuristic:{label:"diff gate candidates"},agent:{answers:["Does my current diff introduce something this repo blocks on?","What must I fix or explicitly accept before reporting the work done?"],returns:["blocking findings with check id, message, and remediation","advisory findings","root-cause groups","changed file and symbol counts","process exit status (1 when blocking findings exist)"],inputs:[],scope:"diff",coverage:"bounded",contrasts:[{command:"diff-impact",distinction:"diff-impact reports what the diff touches downstream; diff-gate judges the diff against repo policy and exits non-zero."}]},renderShape:"custom",docs:C("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:YC},{id:"incomplete-migration",command:"incomplete-migration",description:"Partially-completed extraction candidates: new helpers in the diff wired into some sites while similar un-migrated sites remain",agent:k("Did this diff leave a helper extraction only partly migrated?","new helpers and similar unmigrated call sites",[],"bounded","diff"),options:E([p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",we,.7),p("--max-helpers <n>","Maximum new helpers to score (default: all)",x),p("-n, --limit <n>","Maximum findings to report",x,20),p("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:C("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:KC},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",agent:k("Which files repeatedly change together without a declared dependency?","file pairs, co-change counts, confidence, and history context",["file"],"bounded","repository"),options:E([p("--min-together <n>","Minimum commits where both files changed",x,4),p("-n, --limit <n>","Maximum pairs to report",x,30),p("--all","Include pairs that already have a dependency edge"),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:C("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:HC}];function XC(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${J(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
556
- `).map((s,a)=>` ${Je(i.startLine+a)} ${s}`).join(`
557
- `))}let n=[],r="";for(let i of e.referencedBy)i.relativePath!==r&&(r&&n.push(""),n.push(` ${i.relativePath}`),r=i.relativePath),n.push(` line ${Je(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var QC=Se("imports",{query:({db:e,args:t,budget:n})=>La(e,O(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} \u2190 ${e.fromFile}`,emptyMessage:()=>"No imports found (indexer may not emit role=2 for this language)."}),ZC=te("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=O(t,0),o=Bc(e,i,{semantic:r.semantic});if(b(n,"json")){I("dataflow",t,n,Ie(e,i,o,"dataflow"),{analysisBudget:r.analysisBudget});return}if(!o)return L.empty(fe(e,i,"No dataflow found."));if(me(e,i),console.log(`${o.shortName} (${o.relativePath})
558
- `),o.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of o.definitionSites)console.log(` ${s.file}:${Je(s.line)}`)}if(o.usageSites.length>0){console.log(`
559
- \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of o.usageSites)console.log(` ${s.file}:${Je(s.line)} in ${s.enclosingShort}`)}if(o.producers.length>0){console.log(`
560
- \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let s of o.producers)console.log(` ${s.file} ${s.shortName}`)}if(o.consumers.length>0){console.log(`
561
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),eP=te("slice",({db:e,args:t,opts:n,budget:r})=>{let i=O(t,0),o=b(n,"forward")?"forward":"backward",s=qc(e,i,{direction:o,maxDepth:T(n,"depth",3),semantic:r.semantic});if(b(n,"json")){I("slice",t,n,Ie(e,i,s,"slice"),{analysisBudget:r.analysisBudget});return}if(!s)return L.empty(fe(e,i,"No slice found."));if(me(e,i),console.log(`${s.direction} slice of ${s.shortName}
562
- `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}L.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
563
- ${a.relationship}`),console.log(`
564
- ${s.connectedSymbols.length} connected symbol(s).`)}),Ng=[...Jl,_e({id:"files",command:"files <pattern>",description:"Find files matching a pattern",agent:k("Which indexed files match this text pattern?","matching file paths",["pattern"],"complete"),docs:C("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>wa(e,O(t,0)),format:e=>e.relativePath}),_e({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",agent:k("Which methods belong to this class?","method names and line ranges",["symbol"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>$a(e,O(t,0)),format:e=>` ${pe(e.startLine,e.endLine)} ${e.name}`}),ci({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[p("--full","Run unbounded semantic analysis on large indexes"),Hi()],budget:"semantic",agent:{answers:["Where is this symbol defined, and everywhere is it referenced?"],returns:["definition sites with source and signature","referencing files with line numbers"],inputs:["symbol"],coverage:"bounded",contrasts:[{command:"refs",distinction:"refs returns reference sites only; trace adds the definition and its source."},{command:"call-graph",distinction:"trace lists reference sites flat; call-graph separates incoming callers from outgoing callees."}]},docs:C("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Ca(e,O(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?fe(t,O(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>me(t,O(n,0)),toJson:(e,{db:t,args:n})=>({...bn(t,O(n,0)),...e}),coverage:(e,{budget:t})=>{let n=e.definitions.length+e.referencedBy.length;return t.analysisBudget?{complete:!1,totalKnown:!1,returned:n}:{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}},agentResult:e=>({definitionCount:e.definitions.length,referenceCount:e.referencedBy.length,definitionIdentities:e.definitions.map(t=>`${t.relativePath}:${t.startLine}-${t.endLine}`),referenceIdentities:e.referencedBy.map(t=>`${t.relativePath}:${t.line}`)}),sections:XC}),_e({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",agent:k("Which internal files does this file depend on?","dependency file paths",["file"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>Pa(e,O(t,0)),format:e=>e.relativePath}),_e({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",agent:k("Which internal files depend on this file?","reverse-dependency file paths",["file"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>Ta(e,O(t,0)),format:e=>e.relativePath}),Nf({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",options:[Hi()],agent:{answers:["What is in this module?","What does this module depend on, and what depends on it?"],returns:["module file paths","exported symbols with line ranges","internal dependencies","reverse dependencies"],inputs:["module"],coverage:"complete",contrasts:[{command:"surface",distinction:"system lists everything the module exports; surface lists only what consumers actually use."},{command:"outline",distinction:"system is module-scoped; outline covers a single file."}]},docs:C("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Ea(e,O(t,0)),coverage:e=>{let t=e.files.length+e.symbols.length+e.dependsOn.length+e.dependedOnBy.length;return{complete:!0,totalKnown:!0,returned:t,total:t,omitted:0}},agentResult:e=>({counts:{files:e.files.length,symbols:e.symbols.length,dependencies:e.dependsOn.length,consumers:e.dependedOnBy.length},files:e.files,dependsOn:e.dependsOn,dependedOnBy:e.dependedOnBy,detail:{location:"result",symbolUnits:"result.symbols contains every exported symbol with its line range"}}),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${pe(t.startLine,t.endLine)} ${t.shortName}`)},{title:"DEPENDS ON (internal)",rows:e.dependsOn.map(t=>` ${t}`)},{title:"DEPENDED ON BY",rows:e.dependedOnBy.map(t=>` ${t}`)}]}),_e({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",agent:k("Which exported symbols do external consumers actually use?","consumer paths and consumed symbol identities",["module"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>Ia(e,O(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",agent:k("Which symbols does this file import?","imported symbol identities and source files",["file"],"bounded"),options:[p("--full","Run unbounded semantic analysis on large indexes"),p("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:C("Navigation"),handler:QC},_e({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",agent:k("Which files import this symbol?","importing file paths",["symbol"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>Da(e,O(t,0)),format:e=>` ${e.fromFile}`}),_e({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",agent:k("Which members or nested symbols belong to this symbol?","child symbol identities, kinds, and ranges",["symbol"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>Ma(e,O(t,0)),format:e=>` ${pe(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>me(t,O(n,0)),emptyMessage:({db:e,args:t})=>fe(e,O(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>Ie(t,O(n,0),e,"members")}),_e({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",agent:k("Which symbols have this SCIP kind?","symbol identities, kinds, files, and ranges",["pattern"],"bounded"),options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,100),p("--full","Run unbounded analysis on large indexes")],docs:C("Navigation"),query:({db:e,args:t,opts:n})=>Ja(e,O(t,0),{scope:$(n,"scope"),limit:F(n,"limit",100)}),format:e=>` ${J(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${O(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
565
- ${e.length} symbol(s)`)}),ai({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",agent:k("How many indexed symbols exist for each kind?","symbol-kind counts",[],"complete","repository"),options:[p("-s, --scope <path>","Limit to files matching path")],docs:C("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>Ka(e,{scope:$(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),_e({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",agent:k("What lexical ownership chain contains this symbol?","ancestor symbol identities and depths",["symbol"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>Ya(e,O(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>me(t,O(n,0)),emptyMessage:({db:e,args:t})=>fe(e,O(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>Ie(t,O(n,0),e,"hierarchy")}),{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",agent:k("What defines, uses, produces, and consumes this symbol?","definition sites, usage sites, producer symbols, and consumer symbols",["symbol"],"bounded"),options:E([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:C("Navigation"),handler:ZC},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",agent:k("What transitively affects this symbol, or what does it affect?","connected symbols with relationship and depth",["symbol"],"bounded"),options:E([p("--forward","Forward slice (what does this affect). Default is backward."),p("--depth <n>","Max transitive depth for backward slice",x,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:C("Navigation"),handler:eP}];var tP=te("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=F(n,"limit",20),o=Ge(e.config.projectRoot).gitContext?.headCommit,s=Vc(e,O(t,0),{semantic:r.semantic,impactDepth:T(n,"impactDepth",3),sliceDepth:T(n,"sliceDepth",3),scope:$(n,"scope"),...o?{gitHead:o}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(b(n,"json")){I("plan-context",t,n,{...bn(e,O(t,0)),...s},{analysisBudget:r.analysisBudget,coverage:_g(s),agentResult:Bg(s)});return}return L.empty(fe(e,O(t,0)))}if(b(n,"json")){I("plan-context",t,n,s.matched.symbol?{...bn(e,O(t,0)),...s}:s,{analysisBudget:r.analysisBudget,coverage:_g(s),agentResult:Bg(s)});return}s.matched.symbol&&me(e,O(t,0));let a=[{title:"TARGET",rows:rP(s)},{title:"DEFINITIONS",rows:iP(s,i),skipIfEmpty:!0},{title:"REFERENCES",rows:oP(s,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:sP(s,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:aP(s,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:cP(s,i),skipIfEmpty:!0},{title:"SURFACE",rows:lP(s,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:dP(s,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:uP(s,i),skipIfEmpty:!0},{title:"HISTORY",rows:pP(s),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:mP(s),skipIfEmpty:!0}];L.sectionedReport(a)}),qg=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:Nl([p("--impact-depth <n>","Maximum affected traversal depth",x,3),p("--slice-depth <n>","Maximum backward slice depth",x,3),p("-s, --scope <path>","Limit downstream impact to files matching path"),p("-n, --limit <n>","Rows per section",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",agent:{answers:["What must I know before editing this target?","Who consumes it, and what breaks if I change it?","Has this target historically changed together with anything else?"],returns:["definitions and references","callers and callees","dataflow producers and consumers","backward and forward slices","affected symbols","change-surface risk","dependencies and reverse dependencies","module files and exports","external surface use","complexity","churn","co-change partners","active suppressions"],inputs:[["symbol","file","module"]],coverage:"bounded",contrasts:[{command:"change-surface",distinction:"change-surface is the exports/consumers/risk briefing alone; plan-context embeds it alongside flow, slices, history, and reuse signals."}]},renderShape:"custom",docs:C("Planning",["scip-query plan-context parseSymbol"]),handler:tP}];function _g(e){return{complete:!1,totalKnown:!1,returned:nP(e)}}function nP(e){return e.trace.definitions.length+e.trace.referencedBy.length+(e.callGraph?.callers.length??0)+(e.callGraph?.callees.length??0)+(e.dataflow?.producers.length??0)+(e.dataflow?.consumers.length??0)+(e.dataflow?.usageSites.length??0)+(e.backwardSlice?.connectedSymbols.length??0)+(e.forwardSlice?.connectedSymbols.length??0)+e.affected.length+e.deps.length+e.rdeps.length+e.system.files.length+e.system.symbols.length+e.system.dependsOn.length+e.system.dependedOnBy.length+e.surface.length}function Bg(e){return{target:e.target,matched:e.matched,counts:{definitions:e.trace.definitions.length,references:e.trace.referencedBy.length,callers:e.callGraph?.callers.length??0,callees:e.callGraph?.callees.length??0,producers:e.dataflow?.producers.length??0,consumers:e.dataflow?.consumers.length??0,backwardSlice:e.backwardSlice?.connectedSymbols.length??0,forwardSlice:e.forwardSlice?.connectedSymbols.length??0,affected:e.affected.length,dependencies:e.deps.length,reverseDependencies:e.rdeps.length,moduleFiles:e.system.files.length,externalSurfaceUses:e.surface.length,coChangePartners:e.history.coChangePartners.length},warnings:e.warnings,changeSurface:e.changeSurface?{file:e.changeSurface.file,totalExternalConsumers:e.changeSurface.totalExternalConsumers,riskCounts:{high:e.changeSurface.symbols.filter(t=>t.riskLevel==="high").length,medium:e.changeSurface.symbols.filter(t=>t.riskLevel==="medium").length,low:e.changeSurface.symbols.filter(t=>t.riskLevel==="low").length}}:null,history:e.history}}function rP(e){return[`Target: ${e.target}`,`Matched: symbol=${Ss(e.matched.symbol)} file=${Ss(e.matched.file)} module=${Ss(e.matched.module)}`]}function iP(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${J(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
566
- `).map((o,s)=>` ${String(Je(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${pe(r.startLine,r.endLine)} ${r.shortName}`)),dt(n,t).rows}function oP(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${Je(r.line)} in ${r.enclosingShort}`);return Pt(dt(n,t))}function sP(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(i=>` caller ${i.file} ${i.shortName}`),r=e.callGraph.callees.map(i=>` callee ${i.file} ${i.shortName}`);return Pt(dt([...n,...r],t))}function aP(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(o=>` producer ${o.file} ${o.shortName}`),r=e.dataflow.consumers.map(o=>` consumer ${o.file} ${o.shortName}`),i=e.dataflow.usageSites.map(o=>` usage ${o.file}:${Je(o.line)} in ${o.enclosingShort}`);return Pt(dt([...n,...r,...i],t))}function cP(e,t){let n=[...e.deps.map(r=>` file depends on ${r.relativePath}`),...e.rdeps.map(r=>` file depended on by ${r.relativePath}`),...e.system.dependsOn.map(r=>` module depends on ${r}`),...e.system.dependedOnBy.map(r=>` module used by ${r}`)];return Pt(dt(n,t))}function lP(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${pe(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return Pt(dt(n,t))}function dP(e,t){let n=[],r=-1;for(let i of e.affected)i.depth!==r&&(n.push(` -- Depth ${i.depth} --`),r=i.depth),n.push(` ${i.file} ${i.shortName}`);return Pt(dt(n,t))}function uP(e,t){let n=[];return e.changeSurface&&(n.push(` File: ${e.changeSurface.file}`),n.push(` External consumers: ${e.changeSurface.totalExternalConsumers}`),n.push(...e.changeSurface.symbols.map(r=>{let i=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"";return` ${pe(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${J(e.complexity.relativePath,e.complexity.startLine,e.complexity.endLine)} ${e.complexity.shortName}`),n.push(` LOC: ${e.complexity.loc}`),n.push(` Branches: ${e.complexity.branches}`),n.push(` Cyclomatic estimate: ${e.complexity.cyclomaticEstimate}`),n.push(` Callees: ${e.complexity.calleeCount}`),n.push(` Fan-in: ${e.complexity.fanIn}`),n.push(` Fan-out: ${e.complexity.fanOut}`)),Pt(dt(n,t))}function pP(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let r=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${r}`)}for(let r of t.coChangePartners)n.push(` Usually changes with: ${r.file} (${r.together}x, ${Math.round(r.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function mP(e){let t=e.warnings.map(r=>` ${r}`);return e.history.coChangePartners.length>0&&t.push(" Check the HISTORY co-change partners \u2014 editing this file usually means editing them too."),(e.changeSurface?.symbols.filter(r=>r.riskLevel==="high")??[]).length>0&&t.push(" Inspect high-risk consumers before editing public behavior."),e.affected.length>0&&t.push(" Validate downstream consumers at the shallowest affected depths first."),t}function dt(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Pt(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function Ss(e){return e?"yes":"no"}import{existsSync as Vn}from"fs";import{existsSync as jP,mkdtempSync as LP,rmSync as DP}from"fs";import{tmpdir as OP}from"os";import{dirname as Rs,join as MP}from"path";import{performance as zg}from"perf_hooks";import{spawnSync as FP}from"child_process";import{createHash as Hg,randomUUID as fP}from"crypto";import{closeSync as gi,createReadStream as gP,existsSync as hP,fsyncSync as yP,mkdirSync as bP,openSync as xs,renameSync as SP,unlinkSync as vP,writeSync as xP}from"fs";import{homedir as RP}from"os";import{dirname as Gg,join as vs}from"path";var kP=3e5,wP=256*1024*1024;function Ug(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?vs(t.XDG_CACHE_HOME,"scip-query"):vs(RP(),".cache","scip-query"));return vs(n,e)}var ee=class extends Error{constructor(n,r,i={}){super(r,i.cause===void 0?void 0:{cause:i.cause});this.kind=n;this.name="VerifiedBinaryFetchError"}kind};async function Jg(e){let{cachePath:t,url:n,expectedSha256:r}=e,i=e.timeoutMs??kP,o=e.maxBytes??wP,s=e.lockWaitMs??i;$P(i,o,s);let a=CP(n,i,e.signal);try{let c=await Vg(t,r,o,a.controller.signal);if(c)return{status:"cached",path:t,sha256:c};bP(Gg(t),{recursive:!0});let l=await ml(`${t}.fetch.lock`,{waitMs:s,pollMs:25,signal:a.controller.signal});if(!l)throw new ee("lock-timeout",`timed out waiting ${s}ms for verified binary cache ownership at ${t}`);try{let d=await Vg(t,r,o,a.controller.signal);return d?{status:"cached",path:t,sha256:d}:await PP(e,a.controller,o)}finally{l.release()}}catch(c){throw a.controller.signal.aborted?Zt(a.controller.signal,n):c instanceof ee?c:new ee("stream",`failed to download ${n}: ${Kg(c)}`,{cause:c})}finally{clearTimeout(a.timeout),a.detachExternalAbort(),a.controller.signal.aborted||a.controller.abort()}}function $P(e,t,n){if(!Number.isFinite(e)||e<=0)throw new TypeError("timeoutMs must be a positive finite number.");if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("maxBytes must be a positive safe integer.");if(!Number.isFinite(n)||n<0)throw new TypeError("lockWaitMs must be a non-negative finite number.")}function CP(e,t,n){let r=new AbortController,i=()=>{r.abort(new ee("aborted",`download of ${e} was aborted`,{cause:n?.reason}))};n?.addEventListener("abort",i,{once:!0}),n?.aborted&&i();let o=setTimeout(()=>{r.abort(new ee("timeout",`download of ${e} timed out after ${t}ms`))},t);return o.unref(),{controller:r,timeout:o,detachExternalAbort:()=>n?.removeEventListener("abort",i)}}async function Vg(e,t,n,r){if(!hP(e))return null;let i=Hg("sha256"),o=0;try{for await(let a of gP(e,{signal:r})){let c=Buffer.isBuffer(a)?a:Buffer.from(a);if(o+=c.length,o>n)return null;i.update(c)}}catch{if(r.aborted)throw Zt(r,e);return null}let s=i.digest("hex");return s===t?s:null}async function PP(e,t,n){let r=e.fetchImpl??fetch,i;try{i=await Wg(r(e.url,{signal:t.signal}),t.signal)}catch(l){throw t.signal.aborted?Zt(t.signal,e.url):new ee("stream",`failed to download ${e.url}: ${Kg(l)}`,{cause:l})}if(!i.ok){let l=new ee("http",`failed to download ${e.url}: HTTP ${i.status}`);throw t.abort(l),l}let o=TP(i,n,e.url);if(!i.body)throw new ee("stream",`downloaded ${e.url} response has no readable body`);let s=`${e.cachePath}.tmp-${process.pid}-${fP()}`,a,c=!1;try{a=xs(s,"wx",384),c=!0;let l=i.body.getReader(),d=Hg("sha256"),u=0;for(;;){let{done:g,value:f}=await Wg(l.read(),t.signal);if(g)break;if(!(f instanceof Uint8Array))throw new ee("stream",`downloaded ${e.url} produced a non-byte stream chunk`);if(u+=f.byteLength,u>n||o!==void 0&&u>o){let S=new ee("length",`downloaded ${e.url} exceeded its ${o??n} byte limit`);throw t.abort(S),S}let h=Buffer.from(f.buffer,f.byteOffset,f.byteLength);d.update(h),ca(a,h,{writeFile:e.writeImpl??xP},"verified binary staging")}if(o!==void 0&&u!==o)throw new ee("length",`downloaded ${e.url} length mismatch: declared ${o} bytes, received ${u}`);let m=d.digest("hex");if(m!==e.expectedSha256)throw new ee("checksum",`downloaded ${e.url} checksum mismatch: expected ${e.expectedSha256}, got ${m}`);gi(a),a=void 0;try{EP(s,e.cachePath,e.renameImpl??SP,e.syncImpl??yP)}catch(g){throw new ee("install",`failed to install verified binary at ${e.cachePath}`,{cause:g})}return c=!1,{status:"downloaded",path:e.cachePath,sha256:m}}catch(l){throw t.signal.aborted?Zt(t.signal,e.url):l instanceof ee?l:new ee("install",`failed to stage verified binary at ${e.cachePath}`,{cause:l})}finally{if(a!==void 0)try{gi(a)}catch{}if(c)try{vP(s)}catch{}}}function TP(e,t,n){let r=e.headers?.get("content-length");if(r==null)return;if(!/^\d+$/.test(r))throw new ee("length",`downloaded ${n} has an invalid Content-Length header`);let i=Number(r);if(!Number.isSafeInteger(i)||i<0)throw new ee("length",`downloaded ${n} has an invalid Content-Length header`);if(i>t)throw new ee("length",`downloaded ${n} declares ${i} bytes, above the ${t} byte limit`);return i}function EP(e,t,n,r){IP(e,r),n(e,t),AP(Gg(t),r)}function IP(e,t){let n=xs(e,"r");try{t(n)}finally{gi(n)}}function AP(e,t){let n;try{n=xs(e,"r")}catch(r){if(Ii(r,process.platform))return;throw r}try{t(n)}catch(r){if(!Ii(r,process.platform))throw r}finally{gi(n)}}function Wg(e,t){return t.aborted?Promise.reject(Zt(t,"operation")):new Promise((n,r)=>{let i=()=>{t.removeEventListener("abort",i),r(Zt(t,"operation"))};t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),n(o)},o=>{t.removeEventListener("abort",i),r(o)})})}function Zt(e,t){return e.reason instanceof Error?e.reason:new ee("aborted",`verified binary operation for ${t} was aborted`)}function Kg(e){return e instanceof Error?e.message:String(e)}var NP=12e4,Qg="v1.8.0",_P=`https://github.com/tlaplus/tlaplus/releases/download/${Qg}/tla2tools.jar`,BP="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function yi(e){let t=e.spawn??FP,n=qP(e,t);if(n.missing)return{checker:n.checker,status:"skipped",command:n.command,durationMs:0,exitCode:null,signal:null,timedOut:!1,diagnostics:[{severity:"warning",message:n.missing}],stdout:"",stderr:""};let r=e.timeoutMs??NP,i=zg.now(),o;try{o=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:r,killSignal:"SIGKILL",maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])DP(l,{recursive:!0,force:!0})}let s=Math.round(zg.now()-i),a=o.error?.name==="ETIMEDOUT"||o.signal==="SIGTERM"&&s>=r,c=a?"timed-out":o.status===0?"passed":"failed";return{checker:n.checker,status:c,command:n.command,durationMs:s,exitCode:o.status,signal:o.signal,timedOut:a,diagnostics:VP(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function qP(e,t){let n=e.checker;if(n==="none")return{checker:"none",command:["<none>"],cwd:e.projectRoot,missing:"model checker skipped by --checker none"};if(n==="apalache"||n==="auto"&&We(Yg(e),t)){let o=Yg(e);return We(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:Rs(e.specPath)}:hi("apalache",`Apalache binary is not available: ${o}`)}let r=ks(e),i=We("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return hi(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return hi(n==="sany"?"sany":"tlc","java is not available on PATH");let o=n==="sany"?"sany":n==="tlc"||e.configPath?"tlc":"sany";if(o==="sany")return{checker:o,command:["java","-cp",r,"tla2sany.SANY",e.specPath],cwd:Rs(e.specPath)};let s=e.metaDir??LP(MP(OP(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:Rs(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return hi("none",`unknown checker mode: ${n}`)}function Yg(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function ks(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Zg(t)].filter(r=>typeof r=="string"&&r.length>0).find(r=>jP(r))??null}function Zg(e=process.env){return Ug("tla2tools.jar",e)}async function eh(e={}){let t=e.cachePath??Zg(e.env),n=e.expectedSha256??BP,r=e.version??Qg,i=e.url??_P;return{...await Jg({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,maxBytes:e.maxBytes,signal:e.signal}),version:r,url:i}}function VP(e,t,n){if(e==="passed")return[{severity:"info",message:"model checker completed successfully"}];if(e==="timed-out")return[{severity:"error",message:"model checker timed out"}];let r=[...Xg(n),...Xg(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function Xg(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function hi(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as WP}from"crypto";var nh=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),rh=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),ih=new Set(["readFileSync","existsSync","statSync"]),HP=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,GP=/^\s*SELECT\b/i;function oh(e){return HP.test(e)?"write":GP.test(e)?"read":null}var UP=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function JP(e,t){let n=e.match(UP);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${Ve(t)}\\b`).test(r)}function sh(e,t,n,r=[],i=[]){let o=[],s=YP(e,t,o),a=s.aliases,c=XP(t),l=QP(t),d=ZP(t),u=nT(e,t,o),m=iT(e,t,o);n&&oT(t,n,i,o);let g=new Map((n?.actions??[]).map(v=>[v.name,v])),f=new Set(u.flatMap(v=>v.referents.map(w=>w.match?.symbol).filter(Boolean))),h=new Set((m?.referents??[]).map(v=>v.match?.symbol).filter(Boolean)),S=sT(e,t,u,a,c,l,d,f,h,o,g),y=lT(e,u,a,c,l,d,o,g);return uT(e,u,o),pT(t,r,o),{modelParse:n?.modelParse??"unavailable",modelVariables:n?.variables??[],modelOperators:n?.operators??[],modelActionFacts:n?.actions??[],mappedVariables:Object.keys(t.variables).length,mappedActions:Object.keys(t.actions).length,resolvedReferents:$s(u.flatMap(v=>v.referents))+$s(s.referents)+$s(m?.referents??[]),staticWrites:S,staticReads:y,waivers:jT(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:KP(o)}}function KP(e){let t=new Map;for(let n of e){let r=`${n.category}:${n.modelElement??"-"}`,i=t.get(r);i||(i={groupKey:r,category:n.category,modelElement:n.modelElement,severity:n.severity,count:0,findingIds:[]},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=zP(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||bi(r.severity)-bi(n.severity)||n.groupKey.localeCompare(r.groupKey))}function zP(e,t){return bi(t)>bi(e)?t:e}function bi(e){return e==="error"?2:e==="warning"?1:0}function YP(e,t,n){let r=[],i=[];for(let[o,s]of Object.entries(t.variables)){let a=new Set(s.aliases),c=!!s.waive;for(let l of s.code){let d=xi(e,l,n,o);i.push(d);let u=d.match;if(!u){c||n.push(Y("missing-referent","error","compiler-symbol",{modelElement:o,codeRef:l,message:`TLA+ variable ${o} maps to missing TypeScript referent ${l}.`,why:["The mapping contract must point at live compiler-indexed code before conformance can be checked."],remediation:`Update variables.${o}.code to a live symbol, or remove the variable from the model mapping.`}));continue}CT(e,o,l,u,n,c),s.aliases.length===0&&a.add(zs(u.symbol))}for(let l of a)r.push({variable:o,alias:l})}return{aliases:AT(r),referents:i}}function XP(e){let t=[];for(let[n,r]of Object.entries(e.variables))r.resource&&t.push({variable:n,path:r.resource.path});return t}function QP(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.statements??[])t.push({variable:n,pattern:i.pattern,regex:Hn(i.pattern,`variables.${n}.statements pattern`)});return t}function ZP(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=fs(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function eT(e,t,n,r,i,o){return ah(e,t,(s,a,c)=>Tt(e,s,a,c,n,r,i,o))}function tT(e,t,n,r,i,o){return ah(e,t,(s,a,c)=>vi(e,s,a,c,n,r,i,o))}function ah(e,t,n){let r=fn(e,t,{semantic:!1});if(!r)return[];let i=[],o=new Set;for(let s of r.callees){if(o.has(s.symbol))continue;o.add(s.symbol);let a=Qn(e,s.symbol).match;if(a)for(let c of n(a.relativePath,a.startLine,a.endLine))i.push({...c,via:s.shortName})}return i}function nT(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=gs(s),c="error"in a?s:a.ref,d=xi(e,c,n,r).match;return d?(PT(e,r,s,d,n),"error"in a||!a.window?{ref:s,match:d}:rT(a.window,d)?(n.push(Y("invalid-line-window","error","compiler-symbol",{modelElement:r,codeRef:s,file:d.relativePath,startLine:d.startLine,endLine:d.endLine,message:`TLA+ action ${r} codeRef line window L${a.window.startLine}-L${a.window.endLine} falls outside ${ne(d.symbol)}'s actual span L${d.startLine+1}-L${d.endLine+1} in ${d.relativePath}.`,why:[`${s} resolves to ${ne(d.symbol)} at ${d.relativePath}:${d.startLine+1}-${d.endLine+1}.`,"The requested window does not fall entirely inside that span."],remediation:`Update the @L${a.window.startLine}-L${a.window.endLine} window in actions.${r}.code to fall within L${d.startLine+1}-L${d.endLine+1}, or drop the window to cover the whole function.`})),{ref:s,match:null}):{ref:s,match:d,window:{startLine:a.window.startLine-1,endLine:a.window.endLine-1}}):(n.push(Y("missing-referent","error","compiler-symbol",{modelElement:r,codeRef:s,message:`TLA+ action ${r} maps to missing TypeScript referent ${s}.`,why:["The action cannot be compared to code because the mapped symbol did not resolve in the SCIP index."],remediation:`Update actions.${r}.code to a live function or method symbol.`})),{ref:s,match:null})});return{name:r,mapping:i,referents:o}})}function rT(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function iT(e,t,n){let r=t.init;if(!r)return;let i=!!r.waive,o=r.codeRefs.map(s=>{let a=xi(e,s,n,"Init"),c=a.match;return c?TT(e,s,c,n,i):i||n.push(Y("missing-referent","error","compiler-symbol",{modelElement:"Init",codeRef:s,message:`TLA+ Init maps to missing TypeScript referent ${s}.`,why:["The Init mapping must point at live compiler-indexed code before conformance can be checked."],remediation:"Update init.codeRefs to a live function or method symbol, or remove the stale entry."})),a});return{mapping:r,referents:o}}function oT(e,t,n,r){let i=new Set(t.variables),o=new Set(t.operators),s=new Set(n);for(let a of Object.keys(e.variables))i.has(a)||r.push(Y("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ variable ${a} is not declared in the module.`,why:["The mapping names a model variable, but the TLA+ module text does not declare it with VARIABLE(S)."],remediation:`Declare ${a} in the TLA+ module or remove it from the mapping.`}));for(let a of Object.keys(e.actions))o.has(a)||r.push(Y("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ action ${a} is not defined in the module.`,why:["The mapping names a model action, but the TLA+ module text has no matching operator definition."],remediation:`Define ${a} == ... in the TLA+ module or update the mapping action name.`}));for(let a of t.actions){let c=e.actions[a.name];c&&(th({action:a.name,field:"writes",modelValues:a.writes,mappingValues:c.writes,missingInMappingCategory:"model-mapping-write",missingInModelCategory:"model-mapping-write",findings:r,file:t.path,isWaived:l=>!!c.waive?.writes.includes(l)}),th({action:a.name,field:"reads",modelValues:a.reads,mappingValues:c.reads,missingInMappingCategory:"model-mapping-read",missingInModelCategory:"model-mapping-read",findings:r,file:t.path}))}for(let a of e.invariants)s.has(a)||r.push(Y("missing-invariant","warning","model-text",{modelElement:a,file:t.path,message:`Mapping lists invariant ${a}, but the checker config does not include it.`,why:["The model mapping names an invariant that was not found in INVARIANT lines of the selected config."],remediation:`Add INVARIANT ${a} to the config used for this run, or remove it from the mapping invariants list.`}))}function th(e){let t=new Set(e.modelValues),n=new Set(e.mappingValues),r=e.isWaived??(()=>!1);for(let i of t)n.has(i)||r(i)||e.findings.push(Y(e.missingInMappingCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`TLA+ action ${e.action} ${e.field==="writes"?"writes":"reads"} ${i}, but the mapping does not declare that ${e.field.slice(0,-1)}.`,why:[`SANY-derived model facts list ${i} in ${e.action}.${e.field}, while the mapping omits it.`],remediation:`Add ${i} to actions.${e.action}.${e.field}, or update the TLA+ model if the ${e.field.slice(0,-1)} is unintended.`}));for(let i of n)t.has(i)||r(i)||e.findings.push(Y(e.missingInModelCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`Mapping declares ${e.action}.${e.field} includes ${i}, but the SANY model facts do not.`,why:[`The mapping says ${e.action} ${e.field==="writes"?"writes":"reads"} ${i}, but the parsed TLA+ action does not show that model-side fact.`],remediation:`Update the TLA+ action to ${e.field==="writes"?"prime":"reference"} ${i}, remove the mapping declaration, or add a waiver if static evidence cannot represent the model boundary.`}))}function sT(e,t,n,r,i,o,s,a,c,l,d){let u=[];for(let g of n){let f=[];for(let h of g.referents){if(!h.match)continue;let S=h.window??{startLine:h.match.startLine,endLine:h.match.endLine},y=Tt(e,h.match.relativePath,S.startLine,S.endLine,r,i,o,s);f.push(...y),u.push(...y);let v=new Set(g.mapping.writes),w=eT(e,h.match.symbol,r,i,o,s).filter(R=>v.has(R.variable));f.push(...w),u.push(...w)}cT(g,f,l,d.get(g.name))}let m=t.unmappedWriteScope==="actions"?[]:kT(e,t);for(let g of m)for(let f of Tt(e,g,0,Number.POSITIVE_INFINITY,r,i,o,s))u.push(f),aT(f)&&(f.enclosingSymbol&&(a.has(f.enclosingSymbol)||c.has(f.enclosingSymbol))||l.push(Y("unmapped-write","error","static-action",{modelElement:f.variable,codeRef:f.enclosingSymbol??`${f.file}:${f.line+1}`,file:f.file,startLine:f.line,endLine:f.line,message:`Modeled variable ${f.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${f.target} at ${f.file}:${f.line+1}.`,f.enclosingShort?`The write is inside ${f.enclosingShort}, which is not mapped as a model action.`:"The write is outside an indexed callable definition."],remediation:`Map the enclosing code to a TLA+ action, remove the write, or remove ${f.variable} from the modeled slice if it is intentionally out of scope.`})));return Ts(u)}function aT(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function cT(e,t,n,r){let i=new Set(e.mapping.writes),o=new Set(t.map(a=>a.variable)),s=new Set(r?.writes??[]);for(let a of t)r&&!s.has(a.variable)&&!Bn(e,"write",a.variable)&&n.push(Y("model-code-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} writes ${a.variable}, but the SANY model action does not prime it.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Si(a.via)}.`,`SANY-derived model facts for ${e.name} list writes: ${r.writes.join(", ")||"none"}.`],remediation:`Prime ${a.variable} in the TLA+ action, remove the code write from this action, or remap the code to the correct action.`})),!i.has(a.variable)&&!Bn(e,"write",a.variable)&&n.push(Y("undeclared-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} writes modeled variable ${a.variable}, but the mapping does not declare that write.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Si(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.writes, update the model action, or change the code so it no longer mutates that modeled variable.`}));for(let a of i)!o.has(a)&&!Bn(e,"write",a)&&n.push(Y("missing-write-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a write to ${a}, but no direct source write was found.`,why:["The write may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the write sink as a mapped action referent, provide a trace, or waive actions.${e.name}.writes.${a} with a specific reason.`}))}function lT(e,t,n,r,i,o,s,a){let c=[];for(let l of t){let d=[];for(let u of l.referents){if(!u.match)continue;let m=u.window??{startLine:u.match.startLine,endLine:u.match.endLine},g=vi(e,u.match.relativePath,m.startLine,m.endLine,n,r,i,o);d.push(...g),c.push(...g);let f=new Set(l.mapping.reads),h=tT(e,u.match.symbol,n,r,i,o).filter(S=>f.has(S.variable));d.push(...h),c.push(...h)}dT(l,d,s,a.get(l.name))}return Es(c)}function dT(e,t,n,r){let i=new Set(e.mapping.reads),o=new Set(t.map(a=>a.variable)),s=new Set(r?.reads??[]);for(let a of t)r&&!s.has(a.variable)&&n.push(Y("model-code-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} reads ${a.variable}, but the SANY model action does not reference it.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Si(a.via)}.`,`SANY-derived model facts for ${e.name} list reads: ${r.reads.join(", ")||"none"}.`],remediation:`Reference ${a.variable} in the TLA+ action, remove the code read from this action, or remap the code to the correct action.`})),!i.has(a.variable)&&!Bn(e,"read",a.variable)&&n.push(Y("undeclared-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} reads modeled variable ${a.variable}, but the mapping does not declare that read.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Si(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.reads, update the model action, or waive the read with a specific reason if it is intentionally outside the model step.`}));for(let a of i)!o.has(a)&&!Bn(e,"read",a)&&n.push(Y("missing-read-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a read of ${a}, but no direct source read was found.`,why:["The read may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the read source as a mapped action referent, provide a trace, or waive actions.${e.name}.reads.${a} with a specific reason.`}))}function uT(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>xi(e,s,n,r.name));for(let s of i)s.match||n.push(Y("missing-referent","error","compiler-symbol",{modelElement:r.name,codeRef:s.ref,message:`actions.${r.name}.calls contains missing TypeScript referent ${s.ref}.`,why:["Declared call checks require the expected callee to resolve in the SCIP index."],remediation:`Update actions.${r.name}.calls to a live symbol or remove the stale call expectation.`}));let o=new Set(i.map(s=>s.match?.symbol).filter(Boolean));for(let s of r.referents){if(!s.match)continue;let a=fn(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of o)c.has(l)||n.push(Y("missing-call","error","compiler-symbol",{modelElement:r.name,codeRef:s.ref,file:s.match.relativePath,startLine:s.match.startLine,endLine:s.match.endLine,message:`TLA+ action ${r.name} no longer calls ${ne(l)} from ${s.ref}.`,why:["The mapping declares a call dependency that is absent from the current compiler-resolved call graph."],remediation:`Update actions.${r.name}.calls, update the TLA+ action, or restore the code path if the call is required.`}))}}}function pT(e,t,n){for(let[r,i]of t.entries()){let o=e.actions[i.action];if(!o){n.push(Y("trace","error","trace",{modelElement:i.action,codeRef:i.code,message:`Trace step ${r} uses action ${i.action}, which is not mapped.`,why:["Every observed trace action must map to a TLA+ action before trace conformance can be checked."],remediation:`Add actions.${i.action} to the mapping, or fix the trace action name.`}));continue}let s=IT(i),a=new Set(o.writes);for(let c of s)a.has(c)||n.push(Y("trace","error","trace",{modelElement:i.action,codeRef:i.code,message:`Trace step ${r} changed ${c}, but action ${i.action} does not declare that write.`,why:["The runtime trace observed a state change outside the action write set."],remediation:`Update actions.${i.action}.writes, update the TLA+ model, or investigate the code path that changed ${c}.`}))}}function Tt(e,t,n,r,i,o=[],s=[],a=[]){let c=mT(e,t,n,r,i,o,s,a);return c||xT(e,t,n,r,i,o,s,a)}function vi(e,t,n,r,i,o=[],s=[],a=[]){let c=fT(e,t,n,r,i,o,s,a);return c||RT(e,t,n,r,i,o,s,a)}function mT(e,t,n,r,i,o=[],s=[],a=[]){let c=Ei(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){gT(e,t,u,i,l),ch(e,t,u,o,"write",l),lh(e,t,u,s,"write",l),dh(e,t,u,a,"write",l);for(let m of u.children)d(m)}};return d(c.rootNode),Ts(l)}function fT(e,t,n,r,i,o=[],s=[],a=[]){let c=Ei(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){bT(e,t,u,i,l),ch(e,t,u,o,"read",l),lh(e,t,u,s,"read",l),dh(e,t,u,a,"read",l);for(let m of u.children)d(m)}};return d(c.rootNode),Es(l)}function gT(e,t,n,r,i){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&_n(e,t,o,"assignment",r,i);return}if(n.type!=="variable_declarator"){if(n.type==="pair"){let o=n.childForFieldName("key")??n.namedChild(0);o&&_n(e,t,o,"object-field",r,i);return}if(n.type==="update_expression"){let o=n.namedChildren.find(s=>s.type!=="++"&&s.type!=="--")??n.namedChild(0);o&&_n(e,t,o,"update",r,i);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&_n(e,t,o,"delete",r,i);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!ph(o))return;_n(e,t,o,"mutation-call",r,i)}}}function ch(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?Cs(s):null;if(!a||!(i==="write"?rh:ih).has(a))return;let d=n.childForFieldName("arguments")?.namedChild(0);if(!d)return;let u=d.text;for(let m of r){if(!u.includes(m.path))continue;let g=Be(e,t,n.startPosition.row);o.push({variable:m.variable,alias:m.path,file:t,line:n.startPosition.row,target:`${a}(${u})`,kind:"resource",enclosingSymbol:g?.symbol,enclosingShort:g?ne(g.symbol):void 0})}}function Cs(e){if(e.type==="identifier")return e.text;if(e.type==="member_expression"){let t=e.namedChild(e.namedChildCount-1);return t?t.text:null}return null}function lh(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("arguments");if(s)for(let a of s.namedChildren){let c=hT(a);if(c!==null&&oh(c)===i)for(let l of r){if(!l.regex.test(c))continue;let d=Be(e,t,n.startPosition.row),u=n.childForFieldName("function")??n.namedChild(0),m=(u&&Cs(u))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${m}(${yT(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?ne(d.symbol):void 0})}}}function hT(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function yT(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function dh(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?Cs(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let d=l.text.trim();for(let u of r){if(!uh(u,a,d,i))continue;let m=Be(e,t,n.startPosition.row);o.push({variable:u.variable,alias:u.table,file:t,line:n.startPosition.row,target:`${a}(${d})`,kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?ne(m.symbol):void 0})}}function uh(e,t,n,r){return n!==e.table?!1:r==="write"?e.writeMethods.has(t):e.readMethods.has(t)||t==="from"&&e.readMethods.has("select")}function bT(e,t,n,r,i){if(!(!ST(n)||vT(n)))for(let o of r){if(n.text!==o.alias)continue;let s=Be(e,t,n.startPosition.row);i.push({variable:o.variable,alias:o.alias,file:t,line:n.startPosition.row,target:n.text,kind:"identifier",enclosingSymbol:s?.symbol,enclosingShort:s?ne(s.symbol):void 0})}}function ST(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function vT(e){let t=e.parent;for(;t;){if(t.type==="assignment_expression"||t.type==="augmented_assignment_expression"){let n=t.childForFieldName("left")??t.namedChild(0);return!!(n&&ws(n,e))}if(t.type==="update_expression"||t.type==="unary_expression"&&/^\s*delete\b/.test(t.text))return!0;if(t.type==="pair"){let n=t.childForFieldName("key")??t.namedChild(0);return!!(n&&ws(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&ph(n)&&ws(n,e))return!0}if(t.type.endsWith("statement")||t.type==="function_declaration"||t.type==="method_definition")return!1;t=t.parent}return!1}function ws(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function ph(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&nh.has(t.text))}function _n(e,t,n,r,i,o){for(let s of i){if(!ET(s.alias,n.text))continue;let a=Be(e,t,n.startPosition.row);o.push({variable:s.variable,alias:s.alias,file:t,line:n.startPosition.row,target:n.text,kind:r,enclosingSymbol:a?.symbol,enclosingShort:a?ne(a.symbol):void 0})}}function xT(e,t,n,r,i,o=[],s=[],a=[]){let l=pt(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),d=[],u=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=u;m+=1){let g=l[m]??"";for(let f of i){if(JP(g,f.alias))continue;let h=Ve(f.alias);if(!new RegExp(`(?:\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${h}\\b\\s*\\.\\s*(?:${[...nh].join("|")})\\s*\\(|\\b${h}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(g))continue;let y=Be(e,t,m);d.push({variable:f.variable,alias:f.alias,file:t,line:m,target:g.trim(),kind:"source-scan",enclosingSymbol:y?.symbol,enclosingShort:y?ne(y.symbol):void 0})}mh(e,t,m,g,o,rh,d),fh(e,t,m,g,s,"write",d),gh(e,t,m,g,a,"write",d)}return Ts(d)}function RT(e,t,n,r,i,o=[],s=[],a=[]){let l=pt(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),d=[],u=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=u;m+=1){let g=l[m]??"";for(let f of i){let h=Ve(f.alias);if(!new RegExp(`\\b${h}\\b`).test(g)||new RegExp(`\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(g))continue;let S=Be(e,t,m);d.push({variable:f.variable,alias:f.alias,file:t,line:m,target:g.trim(),kind:"source-scan",enclosingSymbol:S?.symbol,enclosingShort:S?ne(S.symbol):void 0})}mh(e,t,m,g,o,ih,d),fh(e,t,m,g,s,"read",d),gh(e,t,m,g,a,"read",d)}return Es(d)}function mh(e,t,n,r,i,o,s){if(i.length!==0)for(let a of o){let c=r.indexOf(`${a}(`);if(c===-1)continue;let l=r.slice(c+a.length);for(let d of i){if(!l.includes(d.path))continue;let u=Be(e,t,n);s.push({variable:d.variable,alias:d.path,file:t,line:n,target:r.trim(),kind:"resource",enclosingSymbol:u?.symbol,enclosingShort:u?ne(u.symbol):void 0})}}}function fh(e,t,n,r,i,o,s){if(i.length!==0&&oh(r)===o)for(let a of i){if(!a.regex.test(r))continue;let c=Be(e,t,n);s.push({variable:a.variable,alias:a.pattern,file:t,line:n,target:r.trim(),kind:"statement",enclosingSymbol:c?.symbol,enclosingShort:c?ne(c.symbol):void 0})}}function gh(e,t,n,r,i,o,s){if(i.length!==0)for(let a of r.matchAll(/\.([A-Za-z_$][\w$]*)\s*\(\s*([^,)\s][^,)]*?)\s*\)/g)){let c=a[1],l=a[2].trim();for(let d of i){if(!uh(d,c,l,o))continue;let u=Be(e,t,n);s.push({variable:d.variable,alias:d.table,file:t,line:n,target:r.trim(),kind:"orm-call",enclosingSymbol:u?.symbol,enclosingShort:u?ne(u.symbol):void 0})}}}function kT(e,t){let n=t.scope??[];return n.length===0?[]:e.all("SELECT relative_path FROM documents ORDER BY relative_path").map(i=>i.relative_path).filter(i=>n.some(o=>i.includes(o)))}function xi(e,t,n,r){let i=Qn(e,t),o=i.match??(t.includes("#")?Qn(e,t.replace("#","/")).match:null);return i.match&&i.total>1&&!wT(t)&&n.push(Y("ambiguous-referent","warning","compiler-symbol",{modelElement:r,codeRef:t,file:i.match.relativePath,startLine:i.match.startLine,endLine:i.match.endLine,message:`Mapping referent ${t} resolved ambiguously to ${ne(i.match.symbol)}.`,why:[`${i.total} indexed definitions share this lookup shape.`,$T(i.candidates)].filter(Boolean),remediation:`Qualify ${t} with a path or fuller symbol name so the mapping cannot drift to another definition.`})),{ref:t,match:o}}function wT(e){return/[/#:]/.test(e)}function $T(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function CT(e,t,n,r,i,o=!1){let s=Ps(e,r);if(s===null||LT.has(s)||o)return;let a=Is.has(s);i.push(Y("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${ln(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${ne(r.symbol)} with SCIP kind ${ln(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function PT(e,t,n,r,i){let o=Ps(e,r);o===null||hh.has(o)||Is.has(o)&&i.push(Y("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${ne(r.symbol)} with SCIP kind ${ln(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function TT(e,t,n,r,i){let o=Ps(e,n);o===null||hh.has(o)||i||Is.has(o)&&r.push(Y("invalid-referent-kind","error","compiler-symbol",{modelElement:"Init",codeRef:t,file:n.relativePath,startLine:n.startLine,endLine:n.endLine,message:"TLA+ Init referent is a type; map the runtime initialization code it describes.",why:[`${t} resolves to ${ne(n.symbol)} with SCIP kind ${ln(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function Ps(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function Be(e,t,n){return Xn(e,t).filter(i=>i.startLine<=n&&i.endLine>=n).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine))[0]??null}function ET(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Ve(e)}([^A-Za-z0-9_$]|$)`).test(t)}function IT(e){return!e.before||!e.after?[]:[...new Set([...Object.keys(e.before),...Object.keys(e.after)])].filter(n=>JSON.stringify(e.before?.[n])!==JSON.stringify(e.after?.[n]))}function Ts(e){let t=new Set,n=[];for(let r of e){let i=`${r.variable}:${r.file}:${r.line}:${r.target}:${r.enclosingSymbol??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function Es(e){let t=new Set,n=[];for(let r of e){let i=`${r.variable}:${r.file}:${r.line}:${r.target}:${r.enclosingSymbol??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function AT(e){let t=new Set;return e.filter(n=>{let r=`${n.variable}:${n.alias}`;return t.has(r)?!1:(t.add(r),!0)})}function $s(e){return e.filter(t=>t.match).length}function Si(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function Bn(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function jT(e){let t=Object.entries(e.actions).flatMap(([o,s])=>{let a=s.waive;return a?[...(a.reads??[]).map(c=>({action:o,kind:"read",variable:c,reason:a.reason,legacy:a.legacy===!0})),...(a.writes??[]).map(c=>({action:o,kind:"write",variable:c,reason:a.reason,legacy:a.legacy===!0}))]:[]}),n=Object.entries(e.variables).flatMap(([o,s])=>{let a=s.waive;return a?[{kind:"referent",variable:o,reason:a.reason,legacy:!1}]:[]}),r=e.init?.waive,i=r?[{kind:"referent",variable:"Init",reason:r.reason,legacy:!1}]:[];return[...t,...n,...i]}var Is=new Set(Zs()),hh=new Set(Qs()),LT=new Set(ea());function Y(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${WP("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{basename as DT,join as OT}from"path";var As=/^[A-Za-z_][A-Za-z0-9_]*$/;function yh(e,t,n={}){let r=[],i=Xn(e,t,{includeClassMemberFallbacks:!0});if(i.length===0)throw new Error(`no indexed definitions found for ${t}; run 'scip-query reindex' or check the path`);let s=pt(e.config.projectRoot,t,{inputKind:"indexed TLA scaffold source file"}).split(/\r?\n/),a=A=>A.symbol.trimEnd().endsWith("()."),c=i.filter(A=>!a(A)&&!A.isTypeLike&&A.parentTypeName===null&&As.test(A.leaf)),l=c.map(A=>({variable:A.leaf,alias:A.leaf})),d=l.length>0?Tt(e,t,0,Number.POSITIVE_INFINITY,l):[],u=new Set(d.map(A=>A.variable)),m=c.filter(A=>u.has(A.leaf)?!0:NT(s,A)),g=null,f;if(m.length>0)f=i.filter(A=>a(A)&&A.parentTypeName===null);else{if(g=MT(e,t,i,a),!g){let A=i.some(M=>!a(M)&&!M.isTypeLike&&M.parentTypeName!==null&&As.test(M.leaf));throw new Error(`no mutable state discovered in ${t} \u2014 the static write scan found no writes to top-level variables, no top-level let declarations exist, and `+(A?"no class in this file has an instance field the write scan can confirm is mutated by one of its own methods.":"no class instance-field definitions were exposed for this file at all \u2014 the indexer emitted no member rows (neither a primary defn_enclosing_ranges row nor a role=1 mention) for any class in this file, so there is nothing for getDefinitionsForFile to surface even with class-member fallbacks included (docs/plans/2026-07-02-catalog-class-members.md).")+" Pick a file that owns runtime state.")}m=g.fields,f=g.methods,r.push(`state scoped to class ${g.className} (${t}): scaffolded actions are drawn only from its own methods \u2014 other classes or top-level functions in this file are not considered.`)}let h=m.map(A=>_T(A,s,t,r,g?.className)),S=h.map(A=>({variable:A.name,alias:A.leaf})),y=[],v=new Set;for(let A of f){let M=Tt(e,t,A.startLine,A.endLine,S);if(M.length===0)continue;let _=vi(e,t,A.startLine,A.endLine,S),N=WT(bh(A.leaf),v);y.push({name:N,leaf:A.leaf,codeRef:FT(t,A,g?.className),startLine:A.startLine,writes:[...new Set(M.map(H=>H.variable))].sort(),reads:[...new Set(_.map(H=>H.variable))].sort()})}y.length===0&&r.push("no top-level callable writes the discovered state; the generated Next relation is empty and the model cannot step. State may be mutated through methods, callbacks, or other files \u2014 narrow or widen the target.");let w=n.moduleName??HT(t),R=n.specDir??OT("specs",w),j=GT(w,h,y,t),P=UT(),G=JT(w,R,t,h,y);return{moduleName:w,file:t,variables:h,actions:y,warnings:r,spec:j,cfg:P,map:G}}function MT(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!As.test(s.leaf))continue;let a=i.get(s.parentTypeName);a?a.push(s):i.set(s.parentTypeName,[s])}let o=null;for(let[s,a]of i){let c=n.filter(m=>r(m)&&m.parentTypeName===s),l=a.map(m=>({variable:m.leaf,alias:m.leaf})),d=new Set;for(let m of c)for(let g of Tt(e,t,m.startLine,m.endLine,l))d.add(g.variable);let u=a.filter(m=>d.has(m.leaf));u.length!==0&&(!o||u.length>o.fields.length)&&(o={className:s,fields:u,methods:c})}return o}function FT(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function NT(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function _T(e,t,n,r,i){let o=BT(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=qT(e.leaf,o);return a||r.push(`variable ${e.leaf} (${n}:${e.startLine+1}): domain not inferable from the declared type \u2014 fill in the TODO domain before model checking.`),l||r.push(`variable ${e.leaf} (${n}:${e.startLine+1}): initial value not inferable \u2014 fill in the TODO in Init.`),{name:s,leaf:e.leaf,codeRef:i?`${n}/${i}#${e.leaf}`:`${n}/${e.leaf}`,declarationLine:e.startLine,initTla:l,domainTla:a,domainBasis:c}}function BT(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function qT(e,t){let r=t.match(new RegExp(`\\b${KT(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=VT(r);l?(s=`{${l.map(d=>`"${d}"`).join(", ")}}`,a="union-literal"):/^boolean\b/.test(r)?(s="BOOLEAN",a="boolean"):(/\[\]\s*$/.test(r)||/^(Array|ReadonlyArray)</.test(r))&&(a="sequence",s=null)}let c=null;if(o){let l=o.match(/^['"]([^'"]*)['"]/);l?c=`"${l[1]}"`:/^(true|false)\b/.test(o)?c=o.startsWith("true")?"TRUE":"FALSE":/^-?\d+\b/.test(o)?c=o.match(/^-?\d+/)[0]:/^\[\s*\]/.test(o)&&(c="<<>>")}return{domainTla:s,domainBasis:a,initTla:c}}function VT(e){let t=e.split("|").map(r=>r.trim());if(t.length<2)return null;let n=[];for(let r of t){let i=r.match(/^['"]([^'"]*)['"]$/);if(!i)return null;n.push(i[1])}return n}function bh(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function WT(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function HT(e){let n=DT(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return bh(n||"Model")}function GT(e,t,n,r){let i=t.map(s=>s.name),o=[];o.push(`---- MODULE ${e} ----`),o.push(`\\* Scaffolded by 'scip-query tla scaffold ${r}'.`),o.push("\\* Draft evidence tier: state from the static write scan, domains from"),o.push("\\* declared types, actions from top-level callables that write state."),o.push("\\* Review every TODO before trusting a green model-check run."),o.push("EXTENDS Naturals, Sequences, TLC"),o.push(""),o.push(`VARIABLES ${i.join(", ")}`),o.push(""),o.push(`vars == <<${i.join(", ")}>>`),o.push("");for(let s of t){if(s.domainBasis==="sequence")continue;let a=s.domainTla??'{ "TODO" } \\* TODO: declare the domain';o.push(`${s.name}Domain == ${a}`)}o.push(""),o.push("Init ==");for(let s of t){let a=s.initTla??`${s.name}Domain \\* TODO: replace with the concrete initial value (\\in used)`;o.push(s.initTla!==null?` /\\ ${s.name} = ${s.initTla}`:` /\\ ${s.name} \\in ${a}`)}o.push("");for(let s of n){let a=i.filter(c=>!s.writes.includes(c));o.push(`\\* Derived from ${s.codeRef} (writes: ${s.writes.join(", ")||"none"})`),o.push(`${s.name} ==`),o.push(` /\\ TRUE \\* TODO guard: encode the enabling condition of ${s.leaf}()`);for(let c of s.writes){let d=t.find(u=>u.name===c)?.domainBasis==="sequence"?'Seq({"TODO"})':`${c}Domain`;o.push(` /\\ ${c}' \\in ${d} \\* TODO: tighten to the concrete transition`)}a.length>0&&o.push(` /\\ UNCHANGED <<${a.join(", ")}>>`),o.push("")}if(o.push("Next =="),n.length===0)o.push(" FALSE \\* TODO: no state-writing callables were discovered");else for(let[s,a]of n.entries())o.push(` \\/ ${a.name}`);o.push(""),o.push("Spec == Init /\\ [][Next]_vars"),o.push(""),o.push("TypeOK ==");for(let s of t)s.domainBasis==="sequence"?o.push(` /\\ ${s.name} \\in Seq({"TODO"}) \\* TODO: element domain`):o.push(` /\\ ${s.name} \\in ${s.name}Domain`);return o.push("===="),o.push(""),o.join(`
567
- `)}function UT(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
568
- `)}function JT(e,t,n,r,i){let o={module:`${t}/${e}.tla`,config:`${t}/${e}.cfg`,scope:[n],derived:{generatedBy:"scip-query tla scaffold",basis:"static-scan",generatedFrom:n},variables:Object.fromEntries(r.map(s=>[s.name,{code:[s.codeRef],aliases:[s.leaf]}])),actions:Object.fromEntries(i.map(s=>[s.name,{code:[s.codeRef],reads:s.reads,writes:s.writes,calls:[]}])),invariants:["TypeOK"],traces:[]};return`${JSON.stringify(o,null,2)}
569
- `}function KT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sh(e,t){let n=Object.keys(t.variables),r=Object.entries(t.actions).map(([i,o])=>{let s=o.code[0]??"",a=s?Xs(e,s):null;return{action:i,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:zT(n),wiring:r,variables:n}}function zT(e){return`/**
570
- * Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
571
- *
572
- * Usage inside a mapped action (record the model-visible slice around the
573
- * mutation):
574
- *
575
- * import { tlaRecord } from './scip-tla-recorder.js';
576
- * export function enqueue(job: string) {
577
- * const before = snapshot();
578
- * queue.push(job);
579
- * tlaRecord('Enqueue', before, snapshot());
580
- * }
581
- *
582
- * where snapshot() projects the mapped variables to JSON scalars \u2014 fill in
583
- * each field with the real runtime value, e.g.
584
- * const snapshot = () => ({ ${e.map(t=>`${t}: undefined`).join(", ")} }); // fill in each field
585
- *
586
- * Recording is enabled only when SCIP_TLA_TRACE names an output path, so the
587
- * wiring is safe to leave in place. The output is a JSON array compatible
588
- * with 'scip-query tla trace-check --trace <path>'.
589
- */
590
- import { readFileSync, statSync, writeFileSync } from 'node:fs';
591
-
592
- interface TlaTraceStep {
593
- action: string;
594
- before: Record<string, unknown>;
595
- after: Record<string, unknown>;
596
- }
597
-
598
- const tracePath = process.env['SCIP_TLA_TRACE'];
599
- const TRACE_MAX_BYTES = 16 * 1024 * 1024;
600
- const TRACE_MAX_STEPS = 100_000;
601
-
602
- export function tlaRecord(action: string, before: Record<string, unknown>, after: Record<string, unknown>): void {
603
- if (!tracePath) return;
604
- let steps: TlaTraceStep[] = [];
605
- try {
606
- const size = statSync(tracePath).size;
607
- if (size > TRACE_MAX_BYTES) throw new Error(\`TLA trace exceeds \${TRACE_MAX_BYTES} bytes\`);
608
- steps = JSON.parse(readFileSync(tracePath, 'utf8')) as TlaTraceStep[];
609
- if (!Array.isArray(steps)) steps = [];
610
- } catch (error) {
611
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
612
- }
613
- if (steps.length >= TRACE_MAX_STEPS) throw new Error(\`TLA trace exceeds \${TRACE_MAX_STEPS} steps\`);
614
- steps.push({ action, before, after });
615
- const payload = JSON.stringify(steps, null, 2);
616
- const payloadBytes = Buffer.byteLength(payload);
617
- if (payloadBytes > TRACE_MAX_BYTES) throw new Error(\`TLA trace would exceed \${TRACE_MAX_BYTES} bytes\`);
618
- writeFileSync(tracePath, payload);
619
- }
620
- `}import{copyFileSync as YT,mkdtempSync as XT,readdirSync as QT,rmSync as ZT,writeFileSync as vh}from"fs";import{tmpdir as eE}from"os";import{basename as tE,dirname as nE,join as qn}from"path";function Ri(e,t){let n=new Map;for(let r of t)n.set(r.action,(n.get(r.action)??0)+1);return e.map(r=>({action:r,stepsObserved:n.get(r)??0}))}function rE(e,t,n,r="Next"){if(n.length===0)return{error:"trace has no steps"};let i=[],o=n[0];if(!o.before)return{error:"trace step 0 must include a full `before` state"};let s=[],a={...o.before},c=h=>{let S={};for(let[y,v]of Object.entries(h)){if(!t.includes(y))continue;let w=oE(v);w!==void 0&&(S[y]=w)}return S};s.push(c(a));for(let h of n){if(h.before)for(let[S,y]of Object.entries(h.before))S in a||(a[S]=y);Object.assign(a,h.after??{}),s.push(c(a))}let l=t.filter(h=>s.every(S=>h in S)),d=t.filter(h=>!l.includes(h));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};d.length>0&&i.push(`variables not pinned by the trace (missing or non-scalar values): ${d.join(", ")} \u2014 divergence in these variables is NOT checked.`);let u=`${e}Trace`,m=s.map(h=>` [${l.map(S=>`${S} |-> ${Rh(h[S])}`).join(", ")}]`).join(`,
621
- `),g=[`---- MODULE ${u} ----`,"\\* Generated trace-validation harness. Checks that the recorded execution",`\\* is a behavior of ${e}!${r}. TLC deadlocks at the first`,"\\* divergent step; a clean run means the model accepts the trace.",`EXTENDS ${e}, Naturals, Sequences`,"","VARIABLE traceIdx","","TraceStates ==","<<",m,">>","","TraceInit =="," /\\ traceIdx = 1",...l.map(h=>` /\\ ${h} = TraceStates[1].${h}`),"","TraceStep =="," /\\ traceIdx < Len(TraceStates)"," /\\ traceIdx' = traceIdx + 1",` /\\ ${r}`,...l.map(h=>` /\\ ${h}' = TraceStates[traceIdx + 1].${h}`),"","TraceDone =="," /\\ traceIdx = Len(TraceStates)"," /\\ UNCHANGED <<vars, traceIdx>>","","TraceNext == TraceStep \\/ TraceDone","","TraceSpec == TraceInit /\\ [][TraceNext]_<<vars, traceIdx>>","","\\* Reaching the last pinned state means the model accepted every step.","TraceProgress == traceIdx \\in 1..Len(TraceStates)","====",""].join(`
622
- `),f=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
623
- `);return{moduleName:u,moduleText:g,cfgText:f,variables:l,skippedVariables:d,states:s.length,warnings:i}}function xh(e){let t=e.mappedActions??[],n=rE(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:Ri(t,[])};let r=XT(qn(eE(),"scip-tla-trace-"));try{let i=nE(e.specPath);for(let d of QT(i))d.endsWith(".tla")&&YT(qn(i,d),qn(r,d));let o=qn(r,`${n.moduleName}.tla`),s=qn(r,`${n.moduleName}.cfg`);vh(o,n.moduleText),vh(s,n.cfgText);let a=yi({...e.toolOptions,specPath:o,configPath:s,checker:"tlc"});if(a.status==="skipped")return{status:"unavailable",states:n.states,detail:a.diagnostics[0]?.message??"model checker unavailable",checker:a,generation:n,actionCoverage:Ri(t,[])};if(a.status==="passed")return{status:"accepted",states:n.states,detail:`TLC accepted all ${n.states} pinned states under ${e.baseModuleName}!${e.nextOperator??"Next"}.`,checker:a,generation:n,actionCoverage:Ri(t,e.steps)};let c=iE(a.stdout,e.steps),l=c?e.steps.slice(0,c.divergedStep.index):[];return{status:"diverged",states:n.states,...c??{},detail:c?`trace diverges entering state ${c.divergedAtState+1} (step ${c.divergedStep.index}: ${c.divergedStep.action}) \u2014 the model's ${e.nextOperator??"Next"} relation does not accept the recorded transition.`:"TLC rejected the trace but the divergent step could not be parsed from its output; see checker stdout.",checker:a,generation:n,actionCoverage:Ri(t,l)}}finally{ZT(r,{recursive:!0,force:!0})}}function iE(e,t){let n=null;for(let o of e.matchAll(/\btraceIdx = (\d+)/g)){let s=Number.parseInt(o[1],10);(n===null||s>n)&&(n=s)}if(n===null||!/deadlock/i.test(e))return null;let r=n-1,i=t[r];return{divergedAtState:n,divergedStep:{index:r,action:i?.action??"unknown"}}}function oE(e){if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isInteger(e))return e;if(Array.isArray(e)){let t=[];for(let n of e)if(typeof n=="string"||typeof n=="boolean")t.push(n);else if(typeof n=="number"&&Number.isInteger(n))t.push(n);else return;return t}}function Rh(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>Rh(t)).join(", ")}>>`}function kh(e){return tE(e).replace(/\.tla$/i,"")}import{mkdirSync as $h,writeFileSync as Ch}from"fs";import{dirname as sE,join as en}from"path";var aE=async(...e)=>{let{args:t,opts:n}=Ul(e),r=O(t,0);if(r==="fetch-tools"){let o=await eh();if(b(n,"json")){I("tla",t,n,o);return}console.log(`tla2tools.jar ${o.status}: ${o.path}`),console.log(`Version: ${o.version}`),console.log(`SHA-256: ${o.sha256}`);return}if(r==="scaffold"){let o=z(t,1);if(!o)throw new Error("tla scaffold requires a target source file");ue(s=>cE(s,t,n,o));return}if(r==="instrument"){let o=z(t,1);ue(s=>lE(s,t,n,o));return}if(r==="trace-check"){let o=z(t,1);if(!o)throw new Error("tla trace-check requires a spec path");ue(s=>dE(s,t,n,o));return}if(r!=="verify")throw new Error(`unknown tla operation: ${r}. Supported operations: verify, scaffold, instrument, trace-check, fetch-tools`);let i=z(t,1);if(!i)throw new Error("tla verify requires a spec path");ue(o=>mE(o,t,n,i))};function cE(e,t,n,r){let i=e.config.projectRoot,o=yh(e,r,{moduleName:$(n,"moduleName"),specDir:$(n,"out")}),s=$(n,"out")??en("specs",o.moduleName),a=ve(i,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=b(n,"force"),l=[{path:en(a,`${o.moduleName}.tla`),body:o.spec},{path:en(a,`${o.moduleName}.cfg`),body:o.cfg},{path:en(a,`${o.moduleName}.scip-tla.json`),body:o.map}];for(let d of l)if(!c&&Vn(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);$h(a,{recursive:!0});for(let d of l)Ch(d.path,d.body);if(b(n,"json")){I("tla",t,n,{operation:"scaffold",moduleName:o.moduleName,target:r,written:l.map(d=>d.path),variables:o.variables,actions:o.actions,warnings:o.warnings});return}console.log(`Scaffolded ${o.moduleName} from ${r} (draft \u2014 review every TODO):`);for(let d of l)console.log(` wrote ${d.path}`);console.log(`Variables (${o.variables.length}): ${o.variables.map(d=>`${d.name}${d.domainTla?"":" [TODO domain]"}`).join(", ")}`),console.log(`Actions (${o.actions.length}): ${o.actions.map(d=>`${d.name}(writes: ${d.writes.join(",")||"-"})`).join("; ")}`);for(let d of o.warnings)console.log(`WARNING: ${d}`);console.log(`Next: fill the TODO guards/domains, then run 'scip-query tla verify ${en(s,`${o.moduleName}.tla`)}'.`)}function lE(e,t,n,r){let i=e.config.projectRoot,o=$(n,"map")??(r?pi(r):void 0);if(!o)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=ui(i,o);if(!s.loaded)throw new Error(s.errors.join(`
624
- `));let{contract:a,mapDir:c}=s.loaded,l=Sh(e,a),d=$(n,"out")??en(c,"scip-tla-recorder.ts"),u=ve(i,d);if(!u)throw new Error(`instrument output escapes the project root: ${d}`);if(!b(n,"force")&&Vn(u))throw new Error(`refusing to overwrite ${u} (pass --force to replace the recorder)`);if($h(sE(u),{recursive:!0}),Ch(u,l.recorderSource),b(n,"json")){I("tla",t,n,{operation:"instrument",recorder:u,variables:l.variables,wiring:l.wiring});return}console.log(`Wrote trace recorder: ${u}`),console.log("Wire tlaRecord(...) into each mapped action (1 line per action), then run your tests with"),console.log("SCIP_TLA_TRACE=<trace.json> set, and check the result with 'scip-query tla trace-check'."),console.log("Wiring sites:");for(let m of l.wiring){let g=m.file?`${m.file}:${m.line}`:`UNRESOLVED (${m.codeRef})`;console.log(` - ${m.action} -> ${g} writes: ${m.writes.join(", ")||"-"}`)}}function dE(e,t,n,r){let i=e.config.projectRoot,o=ve(i,r);if(!o||!Vn(o))throw new Error(`TLA+ spec not found: ${r}`);let s=$(n,"map")??pi(r),a=ui(i,s);if(!a.loaded)throw new Error(a.errors.join(`
625
- `));let{contract:c}=a.loaded,l=_t(n,"trace"),u=ys(i,[...c.traces,...l]).flatMap(f=>hs(i,f).steps);if(u.length===0)throw new Error("no trace steps found: pass --trace <file> (repeatable) or list traces in the mapping contract");let m=xh({specPath:o,baseModuleName:kh(o),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:u,nextOperator:$(n,"next"),toolOptions:{projectRoot:i,tlaToolsJar:$(n,"tlaTools"),timeoutMs:Q(n,"timeoutMs")}}),g=m.status==="accepted"||m.status==="unavailable"&&b(n,"allowUnknown")?0:1;if(b(n,"json")){I("tla",t,n,{operation:"trace-check",...m,exitCode:g}),process.exitCode=g;return}if(console.log(`TLA+ trace-check: ${o}`),console.log(`Trace: ${u.length} step(s) -> ${m.states} pinned state(s)`),m.generation){console.log(`Pinned variables: ${m.generation.variables.join(", ")}`);for(let f of m.generation.warnings)console.log(`WARNING: ${f}`)}console.log(`${m.status.toUpperCase()}: ${m.detail}`),b(n,"coverage")&&uE(m.actionCoverage),process.exitCode=g}function uE(e){if(e.length===0)return;let t=e.filter(r=>r.stepsObserved>0),n=e.filter(r=>r.stepsObserved===0);console.log(`Action coverage: ${t.length}/${e.length} mapped action(s) exercised by this trace.`);for(let r of t)console.log(` - ${r.action}: ${r.stepsObserved} step(s)`);n.length>0&&console.log(` Unexercised: ${n.map(r=>r.action).join(", ")} \u2014 classify each as a pure modeling abstraction (no code twin, expected) or a real coverage gap (record another trace).`)}function pE(e,t,n,r){let i=$(r,"map");if(i)return{mapArg:i};let o=pi(t),s=ve(e,o);if(s&&Vn(s))return{mapArg:o};let a=tg(e,n);if(a.status==="ambiguous")throw new Error(`multiple *.scip-tla.json files declare module "${a.moduleName}": ${a.candidates.join(", ")} \u2014 pass --map to disambiguate`);return a.status==="found"?{mapArg:a.mapPath,mappingDiscoveredBy:"module-field"}:{mapArg:o}}function mE(e,t,n,r){let i=e.config.projectRoot,o=ve(i,r);if(!o||!Vn(o))throw new Error(`TLA+ spec not found: ${r}`);let{mapArg:s,mappingDiscoveredBy:a}=pE(i,r,o,n),c=ui(i,s);if(!c.loaded)throw new Error(c.errors.join(`
626
- `));let{contract:l,mapPath:d,mapDir:u}=c.loaded,m=$(n,"config")??l.config,g=Yf(i,u,m),f=gE($(n,"checker")??"auto"),h=$(n,"tlaTools"),S=fE(i,r,o,h)??Xf(i,r),y=Zf(g),v=_t(n,"trace"),R=ys(i,[...l.traces,...v]).map(N=>({tracePath:N,...hs(i,N)})),j=R.flatMap(N=>N.steps),P=new Set(v),G=R.filter(N=>P.has(N.tracePath)).flatMap(N=>N.errors),A=sh(e,l,S,j,y);for(let N of[...c.errors,...G])A.findings.push({id:`TLA-CONTRACT-${A.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:N,why:["The verifier can only make accurate claims after the mapping and trace inputs are valid."],remediation:"Fix the mapping or trace input and rerun scip-query tla verify."});let M=yi({projectRoot:i,specPath:o,configPath:g??void 0,checker:f,tlaToolsJar:h,apalacheBin:$(n,"apalache"),length:T(n,"length",10),timeoutMs:Q(n,"timeoutMs")});M.status==="skipped"&&f!=="none"&&A.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:M.diagnostics.map(N=>N.message).join("; "),why:["The TLA+ model was not checked by SANY, TLC, or Apalache in this run."],remediation:"Install the requested checker, run 'scip-query tla fetch-tools', set TLA_TOOLS_JAR, pass --apalache, or rerun with --checker none intentionally."});let _={operation:"verify",specPath:o,mapPath:d,...a?{mappingDiscoveredBy:a}:{},...g?{configPath:g}:{},checker:M,conformance:A,exitCode:hE(M,A,b(n,"allowUnknown"))};if(b(n,"json")){I("tla",t,n,_),process.exitCode=_.exitCode;return}yE(_,b(n,"full")),process.exitCode=_.exitCode}function fE(e,t,n,r){let i=ks({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=Bf({specPath:n,jarPath:i});return o?Qf(e,t,o):null}var Ph=[{id:"tla",command:"tla <operation> [spec]",description:"TLA+ model workflow: verify a model and mapping contract, scaffold a draft model from indexed code, generate a trace recorder, or check a recorded trace against the next-state relation",agent:k("Does this TLA+ model and code mapping agree, or can the requested model artifact be generated?","checker status, conformance findings, trace coverage, or generated artifact paths",["action","path"],"bounded","repository"),options:E([p("--map <file>","scip-query TLA mapping JSON file"),p("--config <file>","TLA+ checker config file"),p("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),p("--tla-tools <jar>","Path to tla2tools.jar"),p("--apalache <binary>","Path to apalache-mc binary"),p("--length <n>","Bounded checker length for Apalache",x,10),p("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",Ke),p("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",St,[]),p("--next <operator>","trace-check: next-state operator the harness requires between states (default Next; use for dual-spec models, e.g. NextCurrent)",void 0,"Next"),p("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),p("--allow-unknown","Exit zero when only unknown findings remain"),p("--out <path>","Output directory (scaffold) or file (instrument)"),p("--module-name <name>","Module name for scaffolded specs"),p("--force","Overwrite existing scaffold/instrument output"),p("--full","verify: print every finding ungrouped instead of (category, modelElement) groups with 3 exemplars each")]),renderShape:"custom",docs:C("Formal Models",["scip-query tla verify specs/Queue.tla --map specs/Queue.scip-tla.json","scip-query tla scaffold src/queue/store.ts","scip-query tla trace-check specs/Queue.tla --trace traces/run1.json --coverage","scip-query tla trace-check specs/Queue.tla --trace traces/run1.json --trace traces/run2.json --coverage","scip-query tla trace-check specs/DualSpec.tla --trace traces/run1.json --next NextCurrent","scip-query tla verify specs/Queue.tla --timeout-ms 300000","scip-query tla verify specs/Queue.tla --full","scip-query tla fetch-tools"]),handler:aE}];function gE(e){if(!zf(e))throw new Error(`unknown checker mode: ${e}`);return e}function hE(e,t,n){return e.status==="failed"||e.status==="timed-out"||t.findings.some(r=>r.severity==="error")||!n&&t.findings.some(r=>r.evidence==="unknown")?1:0}var wh=3;function yE(e,t){console.log(`TLA+ verify: ${e.specPath}`),console.log(`Mapping: ${e.mapPath}${e.mappingDiscoveredBy==="module-field"?" (matched by module field)":""}`),e.configPath&&console.log(`Config: ${e.configPath}`),console.log(`Checker: ${e.checker.checker} ${e.checker.status} (${e.checker.durationMs}ms, exit ${e.checker.exitCode??e.checker.signal??"n/a"})`);for(let o of e.checker.diagnostics)console.log(` [${o.severity}] ${o.message}`);let n=e.conformance.findings.filter(o=>o.severity==="error"),r=e.conformance.findings.filter(o=>o.evidence==="unknown"),i=SE(e);console.log(`
627
- Conformance: ${e.conformance.mappedVariables} variable(s), ${e.conformance.mappedActions} action(s), ${e.conformance.resolvedReferents} resolved referent(s).`),console.log(`Proof: ${i}`);for(let o of vE(e))console.log(`WARNING: ${o}`);if(e.conformance.waivers.length>0){console.log("Waivers:");for(let o of e.conformance.waivers){let s=o.legacy?" legacy":"",a=o.action?`${o.action} ${o.kind}`:`variable ${o.kind}`;console.log(` - ${a} ${o.variable}:${s} ${o.reason}`)}}if(e.conformance.findings.length===0){console.log(e.conformance.waivers.length===0?`PASS: model, mapping, and checked code evidence agree (model parsed by: ${e.conformance.modelParse}).`:`PASS: model checker and unwaived conformance checks passed (model parsed by: ${e.conformance.modelParse}); see waived facts above.`);return}if(console.log(`Findings: ${n.length} error(s), ${r.length} unknown(s), ${e.conformance.findings.length} total.`),t){for(let o of e.conformance.findings)Th(o);return}bE(e.conformance)}function bE(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
628
- Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
629
- [${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let i of n.findingIds.slice(0,wh)){let o=t.get(i);o&&Th(o)}let r=n.count-wh;r>0&&console.log(` ... and ${r} more in this group (use --full to show all)`)}}function SE(e){let t=`${e.checker.checker} ${e.checker.status==="passed"?"PASS":e.checker.status.toUpperCase()}`,n=e.conformance.waivers.filter(s=>s.kind==="write").length,r=e.conformance.waivers.filter(s=>s.kind==="read").length,i=e.conformance.waivers.filter(s=>s.kind==="referent").length,o=e.conformance.findings.filter(s=>s.category==="missing-call").length;return[`checker: ${t}`,`model parsed by: ${e.conformance.modelParse}`,`writes: ${e.conformance.staticWrites.length} verified, ${n} waived`,`reads: ${e.conformance.staticReads.length} verified, ${r} waived`,`calls: ${o===0?"checked":`${o} missing`}`,`traces: ${e.conformance.traceStepsChecked} steps (key-diff; 'tla trace-check' proves acceptance)`,...i>0?[`referents: ${i} waived`]:[]].join(" | ")}function vE(e){let t=[],n=e.conformance.waivers.filter(i=>i.kind==="write").length,r=e.conformance.waivers.filter(i=>i.kind==="read").length;return n>0&&e.conformance.staticWrites.length===0&&t.push("NOTHING PROVEN ABOUT WRITES: every write fact found in this run was waived or unobserved."),r>0&&e.conformance.staticReads.length===0&&t.push("NOTHING PROVEN ABOUT READS: every read fact found in this run was waived or unobserved."),t}function Th(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${J(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
630
- [${e.severity}] ${e.category} (${e.evidence})${t}`),console.log(` ${e.message}`);for(let n of e.why)console.log(` why: ${n}`);console.log(` fix: ${e.remediation}`)}var Eh=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","architecture","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","similar-chains","extract-candidates","locality-candidates","affected","change-surface","cleanup-plan","cleanup-apply","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","incomplete-migration","tla","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","duplicate-bodies","twin-drift","twin-ab","not-implemented","decorative-checkers","test-quality","similar-signatures"],xE=[Dg,Ng,Og,fi,Fg,qg,Ph,Mg],Ih=xE.flat(),RE=new Map(Ih.map(e=>[e.id,e]));for(let e of Ih)if(!Eh.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var tn=Eh.map(e=>kE(e));function kE(e){let t=RE.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var wE=tn.slice(0,js("plan-context")),$E=tn.slice(ki("drift"),js("self-audit")),CE=tn.slice(ki("convergence"),js("slice")),PE=tn.slice(ki("redundant-reexports")),DN=[{id:"reindex",command:"reindex",agent:k("Can the repository index be refreshed, and which language shards succeeded?","index generation, shard statuses, reuse diagnostics, and failures",[],"complete","repository"),description:"Index the codebase and convert to SQLite",options:[p("-l, --language <lang>","Index only this language (can be repeated)",St,[]),p("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),p("--force","Rebuild even if source inputs are unchanged"),p("--allow-partial","Write an incomplete index when one or more detected languages fail"),p("--trust-project-tools","Permit reviewed indexers from this repository for this run"),p("--install-missing","Install missing global tools at reviewed immutable versions for this run"),p("--indexer-concurrency <n>","Number of language indexers to run at once",Ke),p("--json","Output as JSON, including per-shard reuse diagnostics")],renderShape:"custom",docs:C("Indexing",["scip-query reindex"]),handler:ef},{id:"augment-sources",command:"augment-sources",agent:k("Can source files omitted by upstream indexers be added to the index?","added document counts and augmentation status",[],"complete","repository"),description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:C("Indexing"),handler:tf},{id:"augment-vue",command:"augment-vue",agent:k("Can Vue SFC references be compiler-resolved and added to the index?","Vue augmentation counts, project, and diagnostics",[],"complete","repository"),description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[p("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:C("Indexing"),handler:nf},...wE,{id:Rt,command:Rt,description:"Internal bounded diff-gate worker",hidden:!0,options:[p("--json","Emit the private worker envelope without transport pagination")],renderShape:"custom",handler:of},{id:yn,command:yn,description:"Internal diff-impact batch worker",hidden:!0,options:[p("--json","Emit the private worker envelope without transport pagination"),p("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:rf},{id:"diff-impact",command:"diff-impact",agent:k("Which symbols changed in this diff and which downstream consumers are affected?","changed symbols, downstream consumer identities, and impact paths",[],"bounded","diff"),description:"Compute changed symbols and downstream consumers from current git diff",options:E([p("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:C("Impact"),handler:sf},...$E,{id:hn,command:hn,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[p("--json","Emit the private worker envelope without transport pagination"),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:af},{id:"health",command:"health",agent:k("What are the highest-priority verified health problems in this codebase?","health score, findings, priorities, baselines, and coverage notes",[],"bounded","repository"),description:"Composite codebase health report with prioritized action list",options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes"),p("--json","Output as JSON for programmatic consumption"),p("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),p("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:C("Health",["scip-query health --json","scip-query health --baseline"]),handler:cf},{id:"bench",command:"bench",agent:k("How fast are indexing and selected commands under this benchmark matrix?","timings, command outcomes, environment, and optional profiles",[],"sampled","repository"),description:"Benchmark indexing and command runtimes for this repository",options:[p("--json","Output as JSON for programmatic consumption"),p("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),p("--include-heavy","Include expensive full-detector commands in the command matrix"),p("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",St,[]),p("--timeout-ms <n>","Per-command timeout in milliseconds",Ke,18e4),p("--progress","Print benchmark command start/finish progress to stderr"),p("--profile","Enable low-overhead phase profiling in benchmarked commands"),p("--profile-out <path>","Append benchmark and phase profile events as JSONL")],renderShape:"custom",docs:C("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:lf},{id:"work-audit",command:"work-audit <profile>",agent:k("Which repeated computations in this profile waste the most measured time?","ranked repeated-work groups, counts, and avoidable duration",["path"],"bounded"),description:"Rank exact repeated computations in a profiling JSONL file by measured avoidable time",options:[p("--top <n>","Maximum repeated-work groups to show",Ke,20),p("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",docs:C("Maintenance",["scip-query work-audit profile.jsonl","scip-query work-audit profile.jsonl --json"]),handler:df},{id:"typescript-semantic-compare",command:"typescript-semantic-compare",description:"Compare tsserver reference answers against the ts-morph baseline",hidden:!0,options:[p("-s, --scope <path>","Limit compared definitions to files matching path"),p("--limit <n>","Maximum definitions to compare unless --full is set",Ke),p("--max-mismatches <n>","Maximum mismatch details to include in output",Nt),p("--full","Compare every indexed TypeScript-like definition"),p("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:uf},...CE,{id:"install-skills",command:"install-skills",agent:k("Which scip-query skills were installed, updated, skipped, or conflicted?","skill target paths and install outcomes",[],"complete","repository"),description:`Install skills (${Dr.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:C("Maintenance"),handler:gf},{id:"setup-hooks",command:"setup-hooks",agent:k("Were project-local agent hooks installed or removed safely?","hook config targets, changes, skips, and warnings",[],"complete","repository"),description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[p("--shared","Deprecated compatibility flag; hooks remain checkout-local and untracked"),p("--remove","Remove managed project hooks and remember the opt-out"),p("--force","Reinstall hooks even after a previous --remove opt-out"),p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:C("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:hf},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:iu},{id:"hook-pretool",command:"hook-pretool",description:"Internal Claude PreToolUse evidence-integrity guard",hidden:!0,renderShape:"custom",handler:ou},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:au},{id:"check-deps",command:"check-deps",agent:k("Which scip-query and language-indexer dependencies are runnable?","dependency readiness statuses and remediation",[],"complete","repository"),description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:C("Maintenance"),handler:yf},{id:"capabilities",command:"capabilities",agent:k("Which evidence and verification capabilities are available here?","capability matrix with availability and reasons",[],"complete","repository"),description:"Report which evidence and verification capabilities are available in this project",options:[p("--matrix","Render the project capability matrix (default output)"),p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:C("Maintenance"),handler:bf},{id:"capability-matrix",command:"capability-matrix",agent:k("Which evidence and verification capabilities are available here?","deprecated alias of the capability matrix",[],"complete","repository"),description:"Deprecated alias for capabilities --matrix",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:C("Maintenance"),handler:Sf},...PE,{id:"init",command:"init",agent:k("Can a starter scip-query configuration be created for this project?","configuration path and creation outcome",[],"complete","repository"),description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:C("Maintenance"),handler:xf},{id:"config-validate",command:"config-validate",agent:k("Is this project configuration valid and internally consistent?","validation diagnostics with config paths",[],"complete","repository"),description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:C("Maintenance",["scip-query config-validate"]),handler:Rf},{id:"suppress",command:"suppress <id>",agent:k("Can this accepted finding be recorded with an auditable reason?","suppression identity, path, scope, and expiry",["finding"],"complete"),description:"Record an accepted finding as a file under .scipquery/suppressions/ with a required reason",options:E([p("--reason <text>","Required human reason for accepting the finding"),p("--check <check>","Optional detector/check name to narrow the suppression"),p("--file <path>","Optional file path to narrow the suppression"),p("--expires-at <iso>","Optional ISO date after which the suppression expires"),p("--replace <revision>","Replace a different existing decision only when it still has this reported SHA-256 revision")]),renderShape:"custom",docs:C("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:kf},{id:"effectiveness",command:"effectiveness",agent:k("Which diff-gate checks catch actionable findings with verified outcomes?","per-check caught, fixed, suppressed, unresolved, and precision counts",[],"complete","repository"),description:"Per-check effectiveness from the committed outcome ledger: caught, comparison-verified fixes, suppressed, unverified disappearances, and precision",options:E([p("--since <window>","Only count findings first caught in this window (30d, 12w, or an ISO date)"),p("--check <check>","Restrict to one diff-gate check")]),renderShape:"custom",docs:C("Maintenance",["scip-query effectiveness --since 30d","scip-query effectiveness --check echo --json"]),handler:wf},{id:"doctor",command:"doctor",agent:k("Why is scip-query unhealthy or unavailable in this project?","config, freshness, dependency, and capability diagnostics",[],"complete","repository"),description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:C("Maintenance"),handler:$f},{id:"setup",command:"setup",agent:k("Can scip-query be bootstrapped end to end in this project?","setup step outcomes, files, capabilities, smoke tests, and warnings",[],"complete","repository"),description:"Bootstrap this project: enable automatic indexing, install agent skills, refresh the index, verify capabilities, and report health",options:E([p("--guided","Open the interactive checklist (the default in a terminal)"),p("--yes","Accept recommended setup defaults without prompting"),p("--git-hook","Also install a git pre-commit hook that runs diff-gate"),p("--no-hooks","Skip Codex and Claude Code lifecycle hook installation"),p("--no-skills","Skip user-level agent skill installation"),p("--no-parsers","Skip Tree-sitter AST parser installation and repair"),p("--install-missing","Install missing global tools at reviewed immutable versions"),p("--no-health","Skip the optional full health audit and dossier"),p("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:C("Maintenance",["scip-query setup","scip-query setup --install-missing","scip-query setup --json"]),handler:Tf},{id:"setup-agent",command:"setup-agent",agent:k("Can project agent guidance and optional git enforcement be seeded?","written, unchanged, and skipped agent files or hooks",[],"complete","repository"),description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[p("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:C("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:Pf},{id:"setup-ci",command:"setup-ci",agent:k("Can a CI workflow enforce reindex and diff-gate on pull requests?","workflow path, rendered content, and write outcome",[],"complete","repository"),description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[p("--force","Overwrite an existing workflow"),p("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:C("Maintenance",["scip-query setup-ci"]),handler:Ef},{id:"uninstall",command:"uninstall",agent:k("Which scip-query-owned integrations can be removed without touching user-owned files?","removed, retained, skipped, and dry-run targets",[],"complete","repository"),description:"Remove scip-query-owned skill links, project hooks, and managed agent setup blocks",options:E([p("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),p("--project","Remove project-local hooks and managed AGENTS.md/CLAUDE.md blocks"),p("--dry-run","List what would be removed without changing files")]),renderShape:"custom",docs:C("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:If},{id:"watch",command:"watch",agent:k("What is the watcher doing, or can its background service be started or stopped?","watcher/service state, generation, activity, and errors",[],"complete","repository"),description:"Watch in the foreground or manage the per-project background refresh service",options:E([p("--daemon","Ensure the demand-started background service is running"),p("--status","Show background/foreground watcher state"),p("--stop","Stop the watcher or background service for this project"),p("--debounce <ms>","Ms to wait after last change (default: 250)",Nt),p("--cooldown <ms>","Min ms between reindexes; 0 disables spacing (default: 0)",Nt),p("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",Nt),p("--idle-timeout <ms>","Ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",Nt)]),renderShape:"custom",docs:C("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:Af},{id:"status",command:"status",agent:k("Is the index fresh, complete, and usable for this project?","freshness, generation, language shards, watcher, and optional capabilities",[],"complete","repository"),description:"Show index status for this project",options:[p("--json","Output as JSON for programmatic consumption"),p("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:C("Maintenance"),handler:Df}];function ki(e){let t=tn.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function js(e){return ki(e)+1}export{DN as commandDescriptors};
631
- //# sourceMappingURL=command-descriptors-ZW5J4ZEM.js.map