scip-query 0.23.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (650) hide show
  1. package/CHANGELOG.md +491 -2
  2. package/README.md +111 -122
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-PRVFAGTQ.js +2 -0
  5. package/dist/call-graph-DVPAQV2F.js +2 -0
  6. package/dist/call-graph-evidence-CUtj8V2I.d.ts +19 -0
  7. package/dist/chunk-2FSBGL5P.js +2 -0
  8. package/dist/chunk-2HLAFUCY.js +2 -0
  9. package/dist/chunk-2IWUT6CJ.js +3 -0
  10. package/dist/chunk-2KNN7GTQ.js +2 -0
  11. package/dist/chunk-2LHXRE2B.js +8 -0
  12. package/dist/{chunk-EG2CPZMJ.js → chunk-2YXE77TJ.js} +2 -2
  13. package/dist/chunk-36SGVCGX.js +2 -0
  14. package/dist/chunk-3ABBFPTP.js +2 -0
  15. package/dist/chunk-3IVFU4FD.js +3 -0
  16. package/dist/chunk-3JIQS44J.js +7 -0
  17. package/dist/chunk-3ZRB6DNK.js +7 -0
  18. package/dist/{chunk-6YTSKJJ3.js → chunk-42EOW5VI.js} +1 -1
  19. package/dist/{chunk-6I6L7Z62.js → chunk-4BHGBMNO.js} +2 -2
  20. package/dist/chunk-4BP3UBDG.js +2 -0
  21. package/dist/chunk-4D6RO7G4.js +2 -0
  22. package/dist/chunk-4FEWQ6RH.js +2 -0
  23. package/dist/chunk-4IGEOBG7.js +2 -0
  24. package/dist/chunk-4QZXBUKC.js +2 -0
  25. package/dist/chunk-4WBDEVX2.js +4 -0
  26. package/dist/chunk-4WCUBZU3.js +8 -0
  27. package/dist/chunk-4WTUBQ36.js +40 -0
  28. package/dist/chunk-4XQ4O6IM.js +3 -0
  29. package/dist/chunk-55UQAMZO.js +4 -0
  30. package/dist/chunk-5D2LVK7O.js +125 -0
  31. package/dist/chunk-5IYJ56TT.js +2 -0
  32. package/dist/chunk-5PLMJC7Q.js +2 -0
  33. package/dist/chunk-5TNQJUR2.js +5 -0
  34. package/dist/chunk-62BDNPMI.js +2 -0
  35. package/dist/chunk-64DZ5TXR.js +7 -0
  36. package/dist/chunk-65245JCM.js +2 -0
  37. package/dist/chunk-6FFVZZL4.js +2 -0
  38. package/dist/chunk-6KO5JHAR.js +2 -0
  39. package/dist/chunk-6LRXOOSX.js +2 -0
  40. package/dist/chunk-6LSEIIF7.js +2 -0
  41. package/dist/chunk-6YMNWD3H.js +6 -0
  42. package/dist/chunk-72AD6ZRR.js +5 -0
  43. package/dist/chunk-73AAKPUC.js +4 -0
  44. package/dist/chunk-76CZ77DF.js +2 -0
  45. package/dist/chunk-7VPEEAAG.js +2 -0
  46. package/dist/chunk-7WTPQ4NX.js +14 -0
  47. package/dist/chunk-7Y5T6XDP.js +2 -0
  48. package/dist/chunk-A2IIGFMJ.js +5 -0
  49. package/dist/chunk-AB5KCTEV.js +2 -0
  50. package/dist/chunk-AC566WBP.js +6 -0
  51. package/dist/chunk-AGWFSTXC.js +3 -0
  52. package/dist/chunk-AOSIYPTA.js +2 -0
  53. package/dist/chunk-AUVEWPIF.js +2 -0
  54. package/dist/chunk-B56T42J3.js +25 -0
  55. package/dist/chunk-BIQEF5NE.js +2 -0
  56. package/dist/chunk-BL6XJKTA.js +3 -0
  57. package/dist/chunk-BMKOQJRI.js +2 -0
  58. package/dist/chunk-BOZ4EXBB.js +3 -0
  59. package/dist/chunk-BUTWYEPH.js +2 -0
  60. package/dist/chunk-BZB4QPIP.js +2 -0
  61. package/dist/{chunk-ILTDAWEF.js → chunk-CE357GEE.js} +4 -4
  62. package/dist/chunk-CFN45HFP.js +2 -0
  63. package/dist/chunk-CFYMZFXT.js +368 -0
  64. package/dist/chunk-CN5EH7O3.js +2 -0
  65. package/dist/chunk-D254DNNQ.js +4 -0
  66. package/dist/chunk-D3FDISIC.js +2 -0
  67. package/dist/chunk-D3NX5XIE.js +3 -0
  68. package/dist/chunk-DA7RPPDF.js +3 -0
  69. package/dist/chunk-DDMC3FON.js +3 -0
  70. package/dist/chunk-DIO3FUSG.js +2 -0
  71. package/dist/chunk-DJ2NNSUK.js +3 -0
  72. package/dist/chunk-DKYQIM3C.js +18 -0
  73. package/dist/{chunk-JTQVMR42.js → chunk-DOOEL2IV.js} +2 -2
  74. package/dist/chunk-DVFP6PZI.js +2 -0
  75. package/dist/chunk-E3FDPXZK.js +2 -0
  76. package/dist/chunk-E7YNJLCB.js +2 -0
  77. package/dist/chunk-EFGW5JPH.js +2 -0
  78. package/dist/chunk-EJVTR244.js +13 -0
  79. package/dist/chunk-EOV7RTRZ.js +2 -0
  80. package/dist/chunk-ETOIKRHO.js +2 -0
  81. package/dist/chunk-EYK3ZAO2.js +3 -0
  82. package/dist/chunk-F2V2LPET.js +52 -0
  83. package/dist/chunk-F4LUHJTF.js +2 -0
  84. package/dist/chunk-F4PUT6IT.js +2 -0
  85. package/dist/chunk-F56GCXXS.js +5 -0
  86. package/dist/chunk-FC2EVQRM.js +2 -0
  87. package/dist/chunk-FL7NBMHP.js +3 -0
  88. package/dist/chunk-FMRN2TRL.js +3 -0
  89. package/dist/chunk-FVULPZDF.js +20 -0
  90. package/dist/chunk-GCKCF5FL.js +43 -0
  91. package/dist/chunk-GH2PYF46.js +2 -0
  92. package/dist/chunk-GHJAGXIP.js +2 -0
  93. package/dist/{chunk-WIWY3CRX.js → chunk-GMVSHUKZ.js} +2 -2
  94. package/dist/chunk-GS6KDO4R.js +2 -0
  95. package/dist/chunk-GUUBXNN7.js +2 -0
  96. package/dist/chunk-GVWX5T43.js +80 -0
  97. package/dist/chunk-GZKFETP5.js +2 -0
  98. package/dist/chunk-H4EQHO6J.js +9 -0
  99. package/dist/chunk-H73WY2RM.js +2 -0
  100. package/dist/chunk-H75GSPRV.js +60 -0
  101. package/dist/chunk-HDR3AHSV.js +61 -0
  102. package/dist/chunk-HQBSL74Y.js +2 -0
  103. package/dist/chunk-HRRFKWPZ.js +2 -0
  104. package/dist/chunk-HXENDJC6.js +2 -0
  105. package/dist/chunk-IIBAZNSW.js +21 -0
  106. package/dist/chunk-INLMWEUU.js +12 -0
  107. package/dist/chunk-IWQPAF4F.js +2 -0
  108. package/dist/chunk-IZJ6YUKP.js +35 -0
  109. package/dist/chunk-J2TMAIN5.js +60 -0
  110. package/dist/chunk-J5FJMODQ.js +142 -0
  111. package/dist/chunk-J7HZPIO3.js +2 -0
  112. package/dist/chunk-JEVRKFRL.js +2 -0
  113. package/dist/chunk-JFXSGAEB.js +30 -0
  114. package/dist/chunk-JVRTHGFS.js +3 -0
  115. package/dist/chunk-JYWEX7RR.js +360 -0
  116. package/dist/chunk-K3YL22N6.js +2 -0
  117. package/dist/chunk-K4CN7GXK.js +12 -0
  118. package/dist/chunk-K5TBVXU4.js +30 -0
  119. package/dist/chunk-KDDIE2DP.js +9 -0
  120. package/dist/chunk-KHWRRPV4.js +2 -0
  121. package/dist/chunk-KI6NBKDY.js +14 -0
  122. package/dist/chunk-KU3QRSTH.js +2 -0
  123. package/dist/chunk-KZBJWZJB.js +2 -0
  124. package/dist/chunk-L7GFM3NP.js +3 -0
  125. package/dist/chunk-LMO6PK3V.js +35 -0
  126. package/dist/chunk-LN4YXJJU.js +2 -0
  127. package/dist/chunk-LOVIZBJ4.js +43 -0
  128. package/dist/chunk-LPCRK4A2.js +11 -0
  129. package/dist/chunk-MMHZKBFA.js +2 -0
  130. package/dist/{chunk-M2O5NY6W.js → chunk-MOQQBQRD.js} +2 -2
  131. package/dist/chunk-N2WN6I3L.js +2 -0
  132. package/dist/chunk-N3ORQT7L.js +2 -0
  133. package/dist/chunk-NAZ3RAIW.js +2 -0
  134. package/dist/chunk-NDUNO5JQ.js +2 -0
  135. package/dist/chunk-NEIWRNAZ.js +4 -0
  136. package/dist/chunk-NJJMVD65.js +2 -0
  137. package/dist/chunk-NLOQOBXI.js +20 -0
  138. package/dist/chunk-NOLZOVCU.js +2 -0
  139. package/dist/chunk-NOWINRRN.js +2 -0
  140. package/dist/chunk-NZAXKGRL.js +16 -0
  141. package/dist/chunk-O2C4UILI.js +2 -0
  142. package/dist/chunk-O3RHA6ZT.js +3 -0
  143. package/dist/chunk-O4UZSPPI.js +3 -0
  144. package/dist/chunk-OGFV2BUX.js +2 -0
  145. package/dist/chunk-OZCJXZK6.js +499 -0
  146. package/dist/chunk-P6ODM7BY.js +2 -0
  147. package/dist/{chunk-XBGWL66K.js → chunk-PAVGPRHJ.js} +2 -2
  148. package/dist/chunk-PH52RA7D.js +2 -0
  149. package/dist/chunk-PKN354TH.js +3 -0
  150. package/dist/chunk-PWOASWEG.js +11 -0
  151. package/dist/chunk-QIWXRW72.js +2 -0
  152. package/dist/chunk-QJRMOK5N.js +2 -0
  153. package/dist/{chunk-YXPUP5G2.js → chunk-QOIXNWQR.js} +2 -2
  154. package/dist/chunk-QXEUDXBT.js +3 -0
  155. package/dist/chunk-QYUVVBMR.js +6 -0
  156. package/dist/chunk-QZ7KQZRN.js +2 -0
  157. package/dist/chunk-R6LQBUDH.js +2 -0
  158. package/dist/chunk-RBS42E55.js +20 -0
  159. package/dist/chunk-RSJKPCFX.js +26 -0
  160. package/dist/chunk-S6CZA3MV.js +2 -0
  161. package/dist/chunk-STMVAHJP.js +2 -0
  162. package/dist/chunk-SYVPTTVW.js +2 -0
  163. package/dist/chunk-T3I6NHBH.js +2 -0
  164. package/dist/chunk-T6DK3ZP7.js +2 -0
  165. package/dist/chunk-TKD34PHN.js +4 -0
  166. package/dist/chunk-TNNQFH7W.js +2 -0
  167. package/dist/chunk-TNV7SSUF.js +2 -0
  168. package/dist/chunk-TO7ZR3EH.js +8 -0
  169. package/dist/chunk-TOU3CHK4.js +2 -0
  170. package/dist/chunk-TRBI4UKT.js +2 -0
  171. package/dist/chunk-TZCVNCAN.js +4 -0
  172. package/dist/chunk-U4LZA5LL.js +3 -0
  173. package/dist/chunk-U5RIG3JP.js +3 -0
  174. package/dist/chunk-UP5KXN2I.js +2 -0
  175. package/dist/chunk-UQFR3NDH.js +5 -0
  176. package/dist/chunk-UXYXF7GV.js +2 -0
  177. package/dist/chunk-VB3GOKOS.js +2 -0
  178. package/dist/chunk-VF5JZICY.js +2 -0
  179. package/dist/chunk-VTY3VK6E.js +2 -0
  180. package/dist/chunk-VX2O4RIS.js +2 -0
  181. package/dist/chunk-WKPV2TDZ.js +2 -0
  182. package/dist/chunk-WOFQ5DTB.js +2 -0
  183. package/dist/chunk-WS4C6TCK.js +2 -0
  184. package/dist/chunk-WXU3DGPU.js +2 -0
  185. package/dist/chunk-X6RMKHJQ.js +81 -0
  186. package/dist/{chunk-4ILJCCXV.js → chunk-XHMN6ZX7.js} +2 -2
  187. package/dist/chunk-XHTVFLWW.js +2 -0
  188. package/dist/chunk-XKIDJCIK.js +2 -0
  189. package/dist/chunk-XTYTYZPT.js +2 -0
  190. package/dist/chunk-Y2JHHTTA.js +2 -0
  191. package/dist/chunk-YGVRMGYN.js +4 -0
  192. package/dist/chunk-YNQCGEQE.js +2 -0
  193. package/dist/chunk-YOQVEXVE.js +14 -0
  194. package/dist/chunk-YRT2WLYY.js +2 -0
  195. package/dist/chunk-YTAP5Y2G.js +2 -0
  196. package/dist/chunk-YTYWI7VB.js +2 -0
  197. package/dist/chunk-YULZRALL.js +2 -0
  198. package/dist/chunk-Z33WQG4Q.js +2 -0
  199. package/dist/chunk-ZGTYGDMF.js +16 -0
  200. package/dist/chunk-ZHMRSZFD.js +43 -0
  201. package/dist/chunk-ZHSP366W.js +10 -0
  202. package/dist/chunk-ZIBYCYKK.js +7 -0
  203. package/dist/{chunk-GAS2LJMP.js → chunk-ZLADLUE6.js} +3 -3
  204. package/dist/chunk-ZO4YXUT6.js +4 -0
  205. package/dist/{chunk-HYO3NP5Q.js → chunk-ZR4HBC2H.js} +2 -2
  206. package/dist/cli-main.js +6 -6
  207. package/dist/cli.js +1 -1
  208. package/dist/{code-B17qEMbt.d.ts → code-BNyrCF3_.d.ts} +3 -2
  209. package/dist/code-IL5WH3NZ.js +2 -0
  210. package/dist/code-result-json-ANTBEDFP.js +4 -0
  211. package/dist/command-descriptors-HEEMDHTU.js +222 -0
  212. package/dist/deps-EOWFC6FD.js +2 -0
  213. package/dist/direct-navigation-Y5B6OSIQ.js +3 -0
  214. package/dist/{exploration-topology-BG4v30HZ.d.ts → exploration-topology-CSgEyAz-.d.ts} +3 -1
  215. package/dist/files-K4AI3JUM.js +2 -0
  216. package/dist/frontend-profile-roles-D7eCum8P.d.ts +10 -0
  217. package/dist/{health-CPp2Jf1Z.d.ts → health-BtfmNrfa.d.ts} +58 -74
  218. package/dist/hierarchy-6W5NDIFI.js +2 -0
  219. package/dist/imports-WH365QY4.js +2 -0
  220. package/dist/index.d.ts +13 -1
  221. package/dist/index.js +1 -1
  222. package/dist/members-K3PHMF5S.js +2 -0
  223. package/dist/methods-E7KVMBX4.js +2 -0
  224. package/dist/output-continuation-command-BJSY67SN.js +3 -0
  225. package/dist/output-pagination-UZJ5ACIX.js +24 -0
  226. package/dist/postinstall.js +1 -1
  227. package/dist/project-reindex-EP24WT4X.js +3 -0
  228. package/dist/queries/affected.js +1 -1
  229. package/dist/queries/architecture.d.ts +15 -4
  230. package/dist/queries/architecture.js +1 -1
  231. package/dist/queries/bottlenecks.js +1 -1
  232. package/dist/queries/by-kind.js +1 -1
  233. package/dist/queries/call-graph.d.ts +3 -1
  234. package/dist/queries/call-graph.js +1 -1
  235. package/dist/queries/change-surface.d.ts +1 -0
  236. package/dist/queries/change-surface.js +1 -1
  237. package/dist/queries/cleanup-plan.d.ts +3 -3
  238. package/dist/queries/cleanup-plan.js +1 -1
  239. package/dist/queries/co-change.d.ts +20 -2
  240. package/dist/queries/co-change.js +1 -1
  241. package/dist/queries/code.d.ts +1 -1
  242. package/dist/queries/code.js +1 -1
  243. package/dist/queries/complexity.d.ts +6 -3
  244. package/dist/queries/complexity.js +1 -1
  245. package/dist/queries/context.d.ts +1 -7
  246. package/dist/queries/context.js +1 -1
  247. package/dist/queries/coupling.js +1 -1
  248. package/dist/queries/cycles.js +1 -1
  249. package/dist/queries/dead.d.ts +2 -0
  250. package/dist/queries/dead.js +1 -1
  251. package/dist/queries/decorative-checkers.js +1 -1
  252. package/dist/queries/dependence-slice.d.ts +46 -22
  253. package/dist/queries/dependence-slice.js +1 -1
  254. package/dist/queries/dependency-depth.d.ts +1 -7
  255. package/dist/queries/dependency-depth.js +1 -1
  256. package/dist/queries/deps.js +1 -1
  257. package/dist/queries/diff-impact.d.ts +3 -1
  258. package/dist/queries/diff-impact.js +1 -1
  259. package/dist/queries/doc-drift.js +1 -1
  260. package/dist/queries/drift.d.ts +1 -1
  261. package/dist/queries/drift.js +1 -1
  262. package/dist/queries/duplicate-bodies.d.ts +29 -2
  263. package/dist/queries/duplicate-bodies.js +1 -1
  264. package/dist/queries/entry-map.d.ts +2 -4
  265. package/dist/queries/entry-map.js +1 -1
  266. package/dist/queries/evidence.d.ts +121 -61
  267. package/dist/queries/evidence.js +1 -1
  268. package/dist/queries/fan.js +1 -1
  269. package/dist/queries/files.js +1 -1
  270. package/dist/queries/health.d.ts +1 -1
  271. package/dist/queries/health.js +1 -1
  272. package/dist/queries/hierarchy.d.ts +2 -2
  273. package/dist/queries/hierarchy.js +1 -1
  274. package/dist/queries/hotspots.d.ts +1 -1
  275. package/dist/queries/hotspots.js +1 -1
  276. package/dist/queries/imports.d.ts +1 -0
  277. package/dist/queries/imports.js +1 -1
  278. package/dist/queries/incomplete-migration.d.ts +3 -3
  279. package/dist/queries/incomplete-migration.js +1 -1
  280. package/dist/queries/index.d.ts +17 -65
  281. package/dist/queries/index.js +1 -1
  282. package/dist/queries/locality-candidates.d.ts +4 -4
  283. package/dist/queries/locality-candidates.js +1 -1
  284. package/dist/queries/members.d.ts +2 -2
  285. package/dist/queries/members.js +1 -1
  286. package/dist/queries/methods.js +1 -1
  287. package/dist/queries/not-implemented.d.ts +2 -6
  288. package/dist/queries/not-implemented.js +1 -1
  289. package/dist/queries/outline.js +1 -1
  290. package/dist/queries/passthrough-candidates.d.ts +9 -1
  291. package/dist/queries/passthrough-candidates.js +1 -1
  292. package/dist/queries/react-component-duplicates.d.ts +19 -3
  293. package/dist/queries/react-component-duplicates.js +1 -1
  294. package/dist/queries/react-hook-candidates.d.ts +22 -3
  295. package/dist/queries/react-hook-candidates.js +1 -1
  296. package/dist/queries/react-large-component-pressure.d.ts +17 -3
  297. package/dist/queries/react-large-component-pressure.js +1 -1
  298. package/dist/queries/recent-duplicates.js +1 -1
  299. package/dist/queries/redundant-reexports.d.ts +4 -14
  300. package/dist/queries/redundant-reexports.js +1 -1
  301. package/dist/queries/refs.d.ts +4 -1
  302. package/dist/queries/refs.js +1 -1
  303. package/dist/queries/review.d.ts +188 -0
  304. package/dist/queries/review.js +2 -0
  305. package/dist/queries/similar-files.d.ts +7 -10
  306. package/dist/queries/similar-files.js +1 -1
  307. package/dist/queries/similar-signatures.js +1 -1
  308. package/dist/queries/similar.d.ts +19 -1
  309. package/dist/queries/similar.js +1 -1
  310. package/dist/queries/slice-cohesion.d.ts +205 -0
  311. package/dist/queries/slice-cohesion.js +2 -0
  312. package/dist/queries/source-inspection.d.ts +6 -202
  313. package/dist/queries/source-inspection.js +1 -1
  314. package/dist/queries/source-search.d.ts +2 -3
  315. package/dist/queries/source-search.js +1 -1
  316. package/dist/queries/stats.d.ts +1 -0
  317. package/dist/queries/stats.js +1 -1
  318. package/dist/queries/surface.js +1 -1
  319. package/dist/queries/symbols.js +1 -1
  320. package/dist/queries/system.d.ts +4 -2
  321. package/dist/queries/system.js +1 -1
  322. package/dist/queries/test-quality.d.ts +1 -1
  323. package/dist/queries/test-quality.js +1 -1
  324. package/dist/queries/twin-drift.d.ts +23 -7
  325. package/dist/queries/twin-drift.js +1 -1
  326. package/dist/queries/unused-imports.js +1 -1
  327. package/dist/queries/unused-params.d.ts +3 -15
  328. package/dist/queries/unused-params.js +1 -1
  329. package/dist/queries/vue-component-duplicates.js +1 -1
  330. package/dist/queries/vue-composable-candidates.js +1 -1
  331. package/dist/queries/vue-large-view-pressure.js +1 -1
  332. package/dist/query-service-fastpath.js +5 -5
  333. package/dist/query-service-server.js +4 -4
  334. package/dist/refs-CCBJG7WK.js +2 -0
  335. package/dist/refs-pagination-DRNLVU4S.js +2 -0
  336. package/dist/reindex-worker.js +79 -29
  337. package/dist/reindex.js +45 -45
  338. package/dist/repository-cache-worker.js +2 -0
  339. package/dist/runtime.d.ts +8 -8
  340. package/dist/runtime.js +3 -4
  341. package/dist/rust-semantic-session-server.js +1 -1
  342. package/dist/rust-semantic-session-worker.js +1 -1
  343. package/dist/rust-semantic-worker.js +1 -1
  344. package/dist/service-queries-2WAJI7R6.js +6 -0
  345. package/dist/source-inspection-91U9zdO3.d.ts +341 -0
  346. package/dist/{source-search-types-Dwz8KeuW.d.ts → source-search-types-DWGYNg8M.d.ts} +15 -2
  347. package/dist/stats-G7DIV6VU.js +2 -0
  348. package/dist/surface-IO55UALI.js +2 -0
  349. package/dist/system-ZBMSHJXU.js +2 -0
  350. package/dist/{queries/trace.d.ts → trace-BMjw3prn.d.ts} +1 -18
  351. package/dist/typescript-indexer.js +2 -0
  352. package/dist/typescript-mailbox-worker.js +1 -1
  353. package/dist/watch-server.js +3 -3
  354. package/docs/AGENT_GUIDE.md +19 -128
  355. package/docs/CLI_JSON_OUTPUT.md +21 -17
  356. package/docs/COMMAND_REFERENCE.md +34 -49
  357. package/docs/CURRENT_COMMANDS.md +123 -0
  358. package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +0 -40
  359. package/docs/DETECTOR_GUIDE.md +55 -12
  360. package/docs/PRODUCT_VISION.md +135 -0
  361. package/docs/PROPERTY_TESTING.md +73 -0
  362. package/docs/REVIEW.md +76 -0
  363. package/docs/SKILLS.md +51 -0
  364. package/docs/WINDOWS_SIDECAR_RELEASE.md +12 -3
  365. package/docs/accuracy-audit-checklist.md +70 -13
  366. package/docs/analyzer-inventory.md +2 -2
  367. package/docs/locality-analyzer-design.md +9 -9
  368. package/package.json +18 -80
  369. package/scripts/evidence-product-contract.mjs +7 -3
  370. package/scripts/record-review-coverage.mjs +118 -0
  371. package/scripts/scip-windows-provenance.mjs +29 -19
  372. package/skills/scip-architecture-review/SKILL.md +57 -0
  373. package/skills/scip-architecture-review/agents/openai.yaml +4 -0
  374. package/skills/scip-architecture-review/references/design-checks.md +17 -0
  375. package/skills/scip-explore/SKILL.md +15 -59
  376. package/skills/scip-explore/agents/openai.yaml +3 -3
  377. package/skills/scip-explore/references/external-evidence.md +2 -2
  378. package/skills/scip-explore/references/information-model.md +26 -29
  379. package/skills/scip-explore/scripts/capture-evidence.mjs +68 -34
  380. package/skills/scip-integrity-audit/SKILL.md +53 -181
  381. package/skills/scip-integrity-audit/agents/openai.yaml +3 -3
  382. package/skills/scip-integrity-audit/references/integrity-probes.md +27 -0
  383. package/skills/scip-plan/SKILL.md +39 -65
  384. package/skills/scip-plan/agents/openai.yaml +2 -2
  385. package/skills/scip-query/SKILL.md +28 -81
  386. package/skills/scip-query/agents/openai.yaml +2 -2
  387. package/skills/scip-query/references/command-guide.md +169 -0
  388. package/skills/scip-setup/SKILL.md +4 -2
  389. package/skills/scip-setup/agents/openai.yaml +3 -3
  390. package/dist/by-kind-XI2CSWEY.js +0 -2
  391. package/dist/call-graph-UONR6JR5.js +0 -2
  392. package/dist/call-graph-evidence-lZa2dwQA.d.ts +0 -11
  393. package/dist/chunk-26CT72HM.js +0 -2
  394. package/dist/chunk-2E7CX53V.js +0 -2
  395. package/dist/chunk-2GRUZAQF.js +0 -43
  396. package/dist/chunk-2LDBDR6J.js +0 -29
  397. package/dist/chunk-2OOY75BW.js +0 -2
  398. package/dist/chunk-2R3V3PSD.js +0 -4
  399. package/dist/chunk-2WC2OEDO.js +0 -4
  400. package/dist/chunk-35NLDRZC.js +0 -2
  401. package/dist/chunk-3AF4TUFK.js +0 -3
  402. package/dist/chunk-3D3QG236.js +0 -2
  403. package/dist/chunk-3FHOF22C.js +0 -21
  404. package/dist/chunk-3JKSW6LJ.js +0 -2
  405. package/dist/chunk-3L2ZBPEX.js +0 -133
  406. package/dist/chunk-3PJABJSU.js +0 -2
  407. package/dist/chunk-3SVF22I5.js +0 -2
  408. package/dist/chunk-3WR4E3A3.js +0 -3
  409. package/dist/chunk-4FTZ4P5G.js +0 -2
  410. package/dist/chunk-4UX2F3JX.js +0 -2
  411. package/dist/chunk-4WNW27SX.js +0 -2
  412. package/dist/chunk-5ENOG4VP.js +0 -61
  413. package/dist/chunk-64BFSI5I.js +0 -2
  414. package/dist/chunk-66DVSJQG.js +0 -455
  415. package/dist/chunk-6HFCYNYE.js +0 -9
  416. package/dist/chunk-6PQNKL3G.js +0 -3
  417. package/dist/chunk-6V5CNXL6.js +0 -2
  418. package/dist/chunk-6VVV4WRR.js +0 -4
  419. package/dist/chunk-7BWFZPPZ.js +0 -2
  420. package/dist/chunk-7CYG22FH.js +0 -2
  421. package/dist/chunk-7F45LJKI.js +0 -2
  422. package/dist/chunk-7IWV2EG3.js +0 -3
  423. package/dist/chunk-7KCZELVM.js +0 -2
  424. package/dist/chunk-AFHTBORT.js +0 -2
  425. package/dist/chunk-AVRYW5OZ.js +0 -2
  426. package/dist/chunk-B3X6KU75.js +0 -2
  427. package/dist/chunk-B5D7QPBE.js +0 -4
  428. package/dist/chunk-BBCIS4DX.js +0 -16
  429. package/dist/chunk-BDUVI7TO.js +0 -3
  430. package/dist/chunk-BE7ZZTMC.js +0 -2
  431. package/dist/chunk-BHVUJOCQ.js +0 -3
  432. package/dist/chunk-BJT7LSPK.js +0 -3
  433. package/dist/chunk-BKVWUP7Y.js +0 -2
  434. package/dist/chunk-BQGB4HBD.js +0 -2
  435. package/dist/chunk-BRV7PIFF.js +0 -2
  436. package/dist/chunk-CEEZJXEF.js +0 -2
  437. package/dist/chunk-CIYLO6SI.js +0 -7
  438. package/dist/chunk-CJZXN4NU.js +0 -2
  439. package/dist/chunk-CNO7TOKL.js +0 -2
  440. package/dist/chunk-COF23M5F.js +0 -2
  441. package/dist/chunk-CWFP7GM5.js +0 -2
  442. package/dist/chunk-D2DHWI3D.js +0 -2
  443. package/dist/chunk-D4N5SQ2M.js +0 -4
  444. package/dist/chunk-DBRSYFXR.js +0 -2
  445. package/dist/chunk-DHUIOLDT.js +0 -2
  446. package/dist/chunk-DIRJWYBM.js +0 -6
  447. package/dist/chunk-DIUFNHRJ.js +0 -35
  448. package/dist/chunk-DRENNWRG.js +0 -2
  449. package/dist/chunk-DTZCKZEU.js +0 -4
  450. package/dist/chunk-DULC3QFP.js +0 -5
  451. package/dist/chunk-DYGHBZ2N.js +0 -16
  452. package/dist/chunk-E5R6AQ73.js +0 -40
  453. package/dist/chunk-E73UNJTF.js +0 -38
  454. package/dist/chunk-EKV5HX33.js +0 -2
  455. package/dist/chunk-EQHFIL6T.js +0 -3
  456. package/dist/chunk-ESIQ66Z7.js +0 -2
  457. package/dist/chunk-EVFUMY4R.js +0 -3
  458. package/dist/chunk-F7DY272B.js +0 -2
  459. package/dist/chunk-FBN2FGXG.js +0 -2
  460. package/dist/chunk-FDLOBR6P.js +0 -4
  461. package/dist/chunk-FESCRNVV.js +0 -5
  462. package/dist/chunk-FFRKR4EQ.js +0 -2
  463. package/dist/chunk-FGA2U4OR.js +0 -8
  464. package/dist/chunk-FIQRSHVM.js +0 -2
  465. package/dist/chunk-FPYLNQPT.js +0 -2
  466. package/dist/chunk-FRUSVINH.js +0 -2
  467. package/dist/chunk-GSP44ENC.js +0 -2
  468. package/dist/chunk-GUFSG5TX.js +0 -2
  469. package/dist/chunk-GYIZ4NXB.js +0 -2
  470. package/dist/chunk-GZIUDL6G.js +0 -2
  471. package/dist/chunk-H5EXS3HM.js +0 -2
  472. package/dist/chunk-HCXEQRFF.js +0 -18
  473. package/dist/chunk-HEHOQQKH.js +0 -2
  474. package/dist/chunk-HKGFPJ4T.js +0 -4
  475. package/dist/chunk-HLZTEXRA.js +0 -2
  476. package/dist/chunk-HOENASQM.js +0 -3
  477. package/dist/chunk-HVF5VBG6.js +0 -2
  478. package/dist/chunk-I55I7XXP.js +0 -2
  479. package/dist/chunk-IDFEUFKS.js +0 -2
  480. package/dist/chunk-IHGQTTVW.js +0 -2
  481. package/dist/chunk-IICPE7B2.js +0 -20
  482. package/dist/chunk-IL676XCC.js +0 -18
  483. package/dist/chunk-IW5XQG5G.js +0 -2
  484. package/dist/chunk-IZDPJ2QI.js +0 -2
  485. package/dist/chunk-J66VOFW6.js +0 -5
  486. package/dist/chunk-JFMEXGFE.js +0 -2
  487. package/dist/chunk-JGKUET5J.js +0 -3
  488. package/dist/chunk-JS4PGXMV.js +0 -3
  489. package/dist/chunk-JWTGMPIT.js +0 -80
  490. package/dist/chunk-JYR66JN5.js +0 -5
  491. package/dist/chunk-KFOYCQAJ.js +0 -9
  492. package/dist/chunk-KLFEXGQA.js +0 -2
  493. package/dist/chunk-KMVGRIO2.js +0 -2
  494. package/dist/chunk-KYSDI3GE.js +0 -5
  495. package/dist/chunk-L6PJPETJ.js +0 -29
  496. package/dist/chunk-LDVT66YM.js +0 -2
  497. package/dist/chunk-LEECKFCJ.js +0 -2
  498. package/dist/chunk-LMZ5PRUV.js +0 -2
  499. package/dist/chunk-LQRQN2XA.js +0 -2
  500. package/dist/chunk-LXABEJX3.js +0 -2
  501. package/dist/chunk-MNV5FSBW.js +0 -3
  502. package/dist/chunk-MPQ4OTBM.js +0 -2
  503. package/dist/chunk-MTDBHTSF.js +0 -2
  504. package/dist/chunk-MV3CDXPI.js +0 -38
  505. package/dist/chunk-MWN53KRN.js +0 -60
  506. package/dist/chunk-MXNGIEPU.js +0 -3
  507. package/dist/chunk-N2ZSIIGR.js +0 -117
  508. package/dist/chunk-N5B2NILC.js +0 -5
  509. package/dist/chunk-NJITK2GP.js +0 -2
  510. package/dist/chunk-NOGJXYFO.js +0 -2
  511. package/dist/chunk-NOYBFVJA.js +0 -554
  512. package/dist/chunk-NWQXSFFU.js +0 -3
  513. package/dist/chunk-ODDUPDP7.js +0 -13
  514. package/dist/chunk-OLIWTZI3.js +0 -3
  515. package/dist/chunk-OLNV6I6U.js +0 -2
  516. package/dist/chunk-OR2E3AGZ.js +0 -2
  517. package/dist/chunk-OSR2GEHQ.js +0 -2
  518. package/dist/chunk-OSSESPDX.js +0 -3
  519. package/dist/chunk-OWOOWNJ5.js +0 -7
  520. package/dist/chunk-P42EIXTA.js +0 -2
  521. package/dist/chunk-PJFGPYTU.js +0 -2
  522. package/dist/chunk-PP7KNN7L.js +0 -2
  523. package/dist/chunk-PU7T5QYQ.js +0 -2
  524. package/dist/chunk-PWWAJSKV.js +0 -74
  525. package/dist/chunk-PZL5T7SU.js +0 -73
  526. package/dist/chunk-QBE3YX64.js +0 -23
  527. package/dist/chunk-QGVTFRY2.js +0 -7
  528. package/dist/chunk-QOJONDS7.js +0 -2
  529. package/dist/chunk-QU5XRYB5.js +0 -4
  530. package/dist/chunk-QUU5OBVK.js +0 -11
  531. package/dist/chunk-RBLQNW26.js +0 -20
  532. package/dist/chunk-RTQ7NEKG.js +0 -81
  533. package/dist/chunk-SQXRS7BG.js +0 -4
  534. package/dist/chunk-SSK6LDPC.js +0 -2
  535. package/dist/chunk-SZHGTCPP.js +0 -7
  536. package/dist/chunk-T4N4P2K5.js +0 -16
  537. package/dist/chunk-TA3QKLLU.js +0 -2
  538. package/dist/chunk-TEBQMNVI.js +0 -43
  539. package/dist/chunk-TPFHAQ2G.js +0 -2
  540. package/dist/chunk-TQPCBMWT.js +0 -5
  541. package/dist/chunk-TQZV7KV4.js +0 -2
  542. package/dist/chunk-TRNAEQ6P.js +0 -3
  543. package/dist/chunk-TY7CRN3Z.js +0 -2
  544. package/dist/chunk-UHFYCMZO.js +0 -35
  545. package/dist/chunk-UICY4GTQ.js +0 -7
  546. package/dist/chunk-UVGEWT4Y.js +0 -26
  547. package/dist/chunk-UXW33INU.js +0 -29
  548. package/dist/chunk-VMPRET3I.js +0 -5
  549. package/dist/chunk-VNLGKHS6.js +0 -6
  550. package/dist/chunk-VQILFTEH.js +0 -2
  551. package/dist/chunk-VUPHCS7Y.js +0 -57
  552. package/dist/chunk-VVZSBTSU.js +0 -23
  553. package/dist/chunk-VZRNID6A.js +0 -2
  554. package/dist/chunk-W5OXRYGE.js +0 -7
  555. package/dist/chunk-W6STWDQI.js +0 -57
  556. package/dist/chunk-W7CXK74K.js +0 -2
  557. package/dist/chunk-WB3WYIRE.js +0 -4
  558. package/dist/chunk-WDNVY4E7.js +0 -20
  559. package/dist/chunk-WK46TNUM.js +0 -3
  560. package/dist/chunk-WNTFFKAX.js +0 -12
  561. package/dist/chunk-WOIKCX6A.js +0 -2
  562. package/dist/chunk-WUN6KBHV.js +0 -2
  563. package/dist/chunk-WYCTJDVR.js +0 -2
  564. package/dist/chunk-WYPL7GF7.js +0 -2
  565. package/dist/chunk-XDAUYDFT.js +0 -2
  566. package/dist/chunk-XDQMU3BT.js +0 -2
  567. package/dist/chunk-XFA4SSO3.js +0 -3
  568. package/dist/chunk-XGZEP6GR.js +0 -8
  569. package/dist/chunk-XPDPNWTQ.js +0 -368
  570. package/dist/chunk-XRYABF57.js +0 -8
  571. package/dist/chunk-YBGKCQIS.js +0 -2
  572. package/dist/chunk-YEN6CYC7.js +0 -16
  573. package/dist/chunk-YF5IB2LF.js +0 -2
  574. package/dist/chunk-YI2AWIHC.js +0 -3
  575. package/dist/chunk-YPWBKGFU.js +0 -2
  576. package/dist/chunk-YPWHBBIS.js +0 -2
  577. package/dist/chunk-YSH6U3L4.js +0 -3
  578. package/dist/chunk-YU5DZUZI.js +0 -10
  579. package/dist/chunk-YWO5DDRC.js +0 -16
  580. package/dist/chunk-Z4CDXYNQ.js +0 -2
  581. package/dist/chunk-ZF5KHH7C.js +0 -2
  582. package/dist/chunk-ZOHS7AQV.js +0 -21
  583. package/dist/chunk-ZTI4SBFV.js +0 -3
  584. package/dist/code-MI6F2TTU.js +0 -2
  585. package/dist/code-result-json-FXALY4HE.js +0 -2
  586. package/dist/command-descriptors-P34VABY5.js +0 -343
  587. package/dist/dataflow-4KEMJPC6.js +0 -2
  588. package/dist/dependence-slice-R7FPWD5M.js +0 -2
  589. package/dist/deps-7EMQUYUT.js +0 -2
  590. package/dist/direct-navigation-6YO234F2.js +0 -3
  591. package/dist/entry-map-KOOLR26E.js +0 -2
  592. package/dist/files-OPIPJIGZ.js +0 -2
  593. package/dist/graph-evidence-Bjyky2V4.d.ts +0 -126
  594. package/dist/hierarchy-QPD2CAER.js +0 -2
  595. package/dist/imports-M6HUXRXC.js +0 -2
  596. package/dist/members-I5MEFOCT.js +0 -2
  597. package/dist/methods-5JYGGHXA.js +0 -2
  598. package/dist/next-anchor-candidates-BwMczMvX.d.ts +0 -90
  599. package/dist/output-continuation-command-UPQAAKBP.js +0 -3
  600. package/dist/output-pagination-3OFL2MJV.js +0 -19
  601. package/dist/project-reindex-UKKQ5PLS.js +0 -3
  602. package/dist/queries/anchors.d.ts +0 -123
  603. package/dist/queries/anchors.js +0 -2
  604. package/dist/queries/complexity-hotspots.d.ts +0 -40
  605. package/dist/queries/complexity-hotspots.js +0 -2
  606. package/dist/queries/convergence.d.ts +0 -33
  607. package/dist/queries/convergence.js +0 -2
  608. package/dist/queries/dataflow.d.ts +0 -77
  609. package/dist/queries/dataflow.js +0 -2
  610. package/dist/queries/deep-chains.d.ts +0 -5
  611. package/dist/queries/deep-chains.js +0 -2
  612. package/dist/queries/extract-candidates.d.ts +0 -52
  613. package/dist/queries/extract-candidates.js +0 -2
  614. package/dist/queries/isolated.d.ts +0 -24
  615. package/dist/queries/isolated.js +0 -2
  616. package/dist/queries/plan-context.d.ts +0 -33
  617. package/dist/queries/plan-context.js +0 -2
  618. package/dist/queries/reference-neighborhood.d.ts +0 -4
  619. package/dist/queries/reference-neighborhood.js +0 -2
  620. package/dist/queries/reference-reachability.d.ts +0 -48
  621. package/dist/queries/reference-reachability.js +0 -2
  622. package/dist/queries/self-audit.d.ts +0 -63
  623. package/dist/queries/self-audit.js +0 -2
  624. package/dist/queries/similar-chains.d.ts +0 -48
  625. package/dist/queries/similar-chains.js +0 -2
  626. package/dist/queries/slice.d.ts +0 -4
  627. package/dist/queries/slice.js +0 -2
  628. package/dist/queries/stale-abstractions.d.ts +0 -72
  629. package/dist/queries/stale-abstractions.js +0 -2
  630. package/dist/queries/system-map.d.ts +0 -449
  631. package/dist/queries/system-map.js +0 -2
  632. package/dist/queries/trace.js +0 -2
  633. package/dist/queries/twin-ab.d.ts +0 -66
  634. package/dist/queries/twin-ab.js +0 -2
  635. package/dist/queries/value-flow.d.ts +0 -43
  636. package/dist/queries/value-flow.js +0 -2
  637. package/dist/queries/wrapper-candidates.d.ts +0 -34
  638. package/dist/queries/wrapper-candidates.js +0 -2
  639. package/dist/refs-PSU4JZZW.js +0 -2
  640. package/dist/refs-pagination-JG6CJMRC.js +0 -2
  641. package/dist/slice-HYRATV64.js +0 -2
  642. package/dist/source-snippet-_wrcgmZc.d.ts +0 -15
  643. package/dist/stats-OOJ74B32.js +0 -2
  644. package/dist/surface-VTGDYWF5.js +0 -2
  645. package/dist/symbol-resolution-WD5EU5JE.js +0 -2
  646. package/dist/system-LRQNFOR2.js +0 -2
  647. package/dist/trace-F4B6OLL4.js +0 -2
  648. package/dist/value-flow-VRPZY72V.js +0 -2
  649. package/skills/concrete-plan/SKILL.md +0 -8
  650. package/skills/concrete-plan/agents/openai.yaml +0 -4
@@ -1,343 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a as dc,b as uc,c as pc,d as mc,e as Di,f as hc,g as tn,h as fc,i as gc,l as yc,m as Pt,n as Dn,o as qn,p as bc,r as vc,s as Sc,t as wc,u as $c,v as Rc,w as xc,x as Cc,z as Fn}from"./chunk-OLIWTZI3.js";import{a as qa}from"./chunk-4ILJCCXV.js";import"./chunk-RBLQNW26.js";import{a as U,b as S,c as ze,d as pe,e as Oe,f as u,g as ji,h as Fa,i as x,j as R,k as Je,l as Wa,m as X,n as _a,o as st,p as C,q as ge,r as At,s as Yt,t as Ni,u as Xt,v as Zt,w as de,x as me,y as Ae,z as Ja}from"./chunk-L6PJPETJ.js";import{A as b,B as O,C as k,D,E as Ka,F as P,G as za,H as le,a as fe,b as z,i as Z,j as te,k as Ba,l as Ga,m as Va,n as ft,o as Mi,p as Ua,q as Fe,r as Ha,s as Ie,t as Ln,u as Qa,v as N,x as H,y as w,z as K}from"./chunk-6PQNKL3G.js";import{$ as es,$a as ea,$b as Aa,A as In,Aa as Es,B as jr,Ba as Ts,C as ot,Ca as Is,Cb as qe,D as Ii,Da as As,Db as Pi,E as Nr,Ea as Ps,F as Mr,Fa as Ls,G as Ai,Ga as js,H as Or,Ha as Ns,Hb as Ra,I as Dr,Ia as Ms,Ib as Me,J as qr,Ja as Os,Jb as xa,K as Fr,Ka as Ds,L as Wr,La as qs,Lb as ce,M as _r,Ma as Fs,Mb as Ca,N as Br,Na as Ws,O as Gr,Oa as _s,P as Vr,Pa as Bs,Q as Ur,Qa as Gs,R as Hr,Ra as Vs,S as Qr,Sa as Us,Sb as Ta,T as Kr,Ta as Hs,U as zr,Ua as Qs,V as Jr,Va as Ks,W as Yr,Wa as zs,Wb as Ia,X as Tt,Xa as Js,Xb as Pn,Y as $t,Ya as Ys,Yb as j,Z as Xr,Za as Xs,Zb as ve,_ as Zr,_a as Zs,_b as V,a as gn,aa as ts,ab as ta,ac as A,b as Gt,ba as ns,bb as na,bc as Qt,c as sr,ca as is,cb as ia,cc as Kt,d as ar,da as os,db as sa,dc as zt,e as Vt,ea as rs,ec as rt,f as lr,fa as ss,fb as aa,g as dr,ga as as,gb as It,gc as Pa,h as ur,ha as cs,hb as Ee,hc as La,i as pr,ia as ls,ib as Rt,ic as ja,j as kn,ja as ds,jb as Ke,jc as Na,k as Rr,ka as us,kb as ca,kc as Ma,l as Tn,la as ps,lb as la,lc as Oa,m as xr,ma as ms,mb as da,n as Cr,na as hs,nb as ua,o as kr,oa as fs,p as Ut,pa as gs,pb as Te,pc as ht,qa as ys,qb as ha,qc as Jt,ra as bs,rb as fa,s as Er,sa as vs,sb as ga,sc as Da,t as Tr,ta as Ss,tb as ya,u as Ir,ua as ws,ub as ba,v as Ar,va as $s,vb as va,vc as Li,w as Pr,wa as Rs,wb as Sa,x as Lr,xa as xs,xb as wa,ya as Cs,yb as $a,z as Ht,za as ks,zb as ue}from"./chunk-NOYBFVJA.js";import{a as Ya,b as Xa,c as jn,d as en,e as Oi,f as Za,g as ec,h as tc,i as Nn,j as nc,k as ic,l as Mn,m as oc,n as On,o as rc,p as sc,q as ac,r as cc,s as lc,t as kc}from"./chunk-XPDPNWTQ.js";import{$ as Jo,$c as cr,$d as Ci,A as Vo,Ab as wt,Bb as nr,C as Uo,Fa as Bt,Ga as vi,Gc as Sn,Ge as oa,H as Ho,Ia as er,K as bi,L as Qo,Ld as $n,Mb as vn,Md as Rn,Me as Qe,Nb as ir,Nd as mr,Ob as Si,Od as xn,Oe as ra,P as Ko,Pd as He,Pe as An,Qd as ke,Rd as hr,S as zo,Td as Cn,Ud as wi,Vd as $i,Yd as Ri,Zd as xi,_ as Ve,_d as fr,a as yi,aa as Yo,ab as tr,ad as wn,be as gr,c as Bo,ce as yr,da as Ue,dc as or,de as br,eb as bn,ee as vr,ef as pa,fa as Xo,fe as ki,ff as ma,gb as ie,ge as Ei,hb as be,he as Ti,ie as Sr,ke as wr,l as bt,m as Go,me as En,n as yn,ne as $r,o as vt,oa as St,t as Ce,tc as oe,u as ae,uc as rr,vf as ka,wa as Zo,wf as Ea,zd as it}from"./chunk-66DVSJQG.js";import{existsSync as Wn,mkdirSync as Em,symlinkSync as Tm,readlinkSync as qi,unlinkSync as Fi,readdirSync as Ec}from"fs";import{join as Ye,dirname as nn,resolve as gt,relative as Im,isAbsolute as Am}from"path";import{homedir as Tc,platform as Pm}from"os";import{fileURLToPath as Ic}from"url";var Lm=Pm()==="win32",Ac=["scip-query","scip-explore","scip-plan","scip-setup","scip-integrity-audit"];var Pc=["scip-query","scip-plan","scip-setup","scip-integrity-audit","scip-explore","concrete-plan"];function _n(e={}){let t=e.quiet?()=>{}:console.log,n=Ic(import.meta.url),i=gt(nn(n),"..","skills"),o=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??Tc(),r=[Ye(o,".claude","skills"),Ye(o,".codex","skills"),Ye(o,".agents","skills")],s={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let a of r){let c=nn(a);if(!Wn(c))continue;Em(a,{recursive:!0});let l=Nc(a);jm(a,i,l,s,t);for(let d of Pc){let m=Ye(i,d),h=Ye(a,d);if(!Wn(m)){s.skipped.push(`${l}/${d}`);continue}if(Wn(h)){try{let p=qi(h);if(gt(p)===gt(m)){s.alreadyLinked.push(`${l}/${d}`),t(` ok: ${d} \u2192 ${l} (already linked)`);continue}}catch{s.skipped.push(`${l}/${d}`),t(` skip: ${d} \u2192 ${l} (exists, not a symlink)`);continue}Fi(h)}Tm(m,h,Lm?"junction":"dir"),s.installed.push(`${l}/${d}`),t(` done: ${d} \u2192 ${l}`)}}return s}function jm(e,t,n,i,o){let r=new Set(Pc);for(let s of Ec(e)){if(r.has(s))continue;let a=Ye(e,s),c;try{c=gt(nn(a),qi(a))}catch{continue}jc(c,t)&&(Fi(a),i.pruned.push(`${n}/${s}`),o(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function Lc(e={}){let t=Ic(import.meta.url),n=gt(nn(t),"..","skills"),i=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??Tc(),o=[Ye(i,".claude","skills"),Ye(i,".codex","skills"),Ye(i,".agents","skills")],r={removed:[],left:[],skipped:[]};for(let s of o){if(!Wn(s))continue;let a=Nc(s);for(let c of Ec(s)){let l=Ye(s,c),d;try{let m=qi(l);d=gt(nn(l),m)}catch{r.left.push(`${a}/${c} (not a symlink)`);continue}if(!jc(d,n)){r.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(r.removed.push(`${a}/${c}`),!e.dryRun)try{Fi(l)}catch(m){r.skipped.push(`${a}/${c} (${m instanceof Error?m.message:String(m)})`)}}}return r}function jc(e,t){let n=Im(gt(t),gt(e));return n===""||!n.startsWith("..")&&!Am(n)}function Nc(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as cn}from"fs";import{dirname as Ny,join as Id}from"path";import{execFileSync as wh}from"child_process";import{createRequire as Nm}from"module";var Mm=Nm(import.meta.url);function Mc(e,t=[]){let n=Om(),i=Rr(e,t),o=i[0];return n?i.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:o,tsconfigPaths:i}:{available:!1,dependencyAvailable:n,tsconfigPath:o,tsconfigPaths:i,reason:"ts-morph is not installed"}}function Om(){try{return Mm.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as on,spawnSync as Dm}from"child_process";import{existsSync as We,mkdtempSync as qm,readdirSync as Fm,rmSync as Oc,symlinkSync as Wm,writeFileSync as _m}from"fs";import{tmpdir as Bm}from"os";import{join as Se}from"path";var Gm=3e5,Vm=12,Wc=3e4,_i=1024*1024,Um={readWorkingTreeStatus(e){return on("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",timeout:Wc,maxBuffer:_i,killSignal:"SIGKILL"})}};function _c(e,t,n={}){let i=th(e,n.workingTreeRuntime),o=i.state==="known"?i.files:[],r=eh(t,i),s=Bi(e);if(s.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,batches:[]};let a=zm(t,s),c=n.timeoutMs??Gm,l=[],d=new Map,m;try{m=Gc(e,"scip-cleanup-verify-")}catch(h){return{checkers:s.map(p=>p.label),uncoveredFiles:a,baselineErrors:0,workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,unavailableReason:oh(h),batches:[]}}try{ih(e,m.root);for(let h of s)d.set(h.label,qc(h,m.root,c).rawErrors);for(let h of t.batches){Vc(m.root,h);let p=null;for(let f of s){let g=qc(f,m.root,c),y=Hm(g,d.get(f.label)??[],g.rawErrors);if(y.status==="failed"){let v=y.errors.length>0?y.errors:g.outputTail;p={depth:h.depth,status:"failed",reason:`${f.label}: ${y.reason}`,errors:v.slice(0,Vm)};break}}if(!p)l.push({depth:h.depth,status:"verified"});else{l.push(p);break}}}finally{m.dispose()}return{checkers:s.map(h=>h.label),uncoveredFiles:a,baselineErrors:[...d.values()].reduce((h,p)=>h+p.length,0),workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,batches:l}}function Hm(e,t,n){let i=Qm(t,n);return i.length>0?{status:"failed",reason:"checker reported new errors",errors:i}: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 Qm(e,t){let n=Km(e),i=new Map,o=[];for(let r of t){let s=Bc(r),a=(i.get(s)??0)+1;i.set(s,a),a>(n.get(s)??0)&&o.push(r)}return o}function Km(e){let t=new Map;for(let n of e){let i=Bc(n);t.set(i,(t.get(i)??0)+1)}return t}function zm(e,t){let n=new Set(t.flatMap(o=>o.coversExtensions));return[...new Set(e.batches.flatMap(o=>o.entries.map(r=>r.file)))].filter(o=>{let r=o.slice(o.lastIndexOf("."));return!n.has(r)}).sort()}function Bc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Dc=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],Jm=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Bi(e){let t=[];if(We(Se(e,"tsconfig.json"))){let n=Se(e,"node_modules",".bin","tsc");t.push(We(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Dc,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Dc,strength:"reference-aware"})}if(We(Se(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=>We(Se(e,n)))){let n=Ym();n&&t.push(n)}if(Jm.some(n=>We(Se(e,n)))){let n=Xm(e);n&&t.push(n)}for(let n of Zm(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:Se(e,n,"..","target")}});return t}function Ym(){return it("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"}:it("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function Xm(e){let t=Se(e,"node_modules",".bin","clj-kondo");return We(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...bn],strength:"reference-aware"}:it("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...bn],strength:"reference-aware"}:it("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...bn],strength:"reference-aware"}:null}function Zm(e){let t=[];if(We(Se(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Fm(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||We(Se(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function eh(e,t){if(t.state==="unavailable")return[];let n=new Set(t.files);return[...new Set(e.batches.flatMap(o=>o.entries.map(r=>r.file)))].filter(o=>n.has(o)).sort()}function th(e,t=Um){try{return{state:"known",files:t.readWorkingTreeStatus(e).split(`
3
- `).map(i=>i.slice(3).trim()).filter(i=>i!=="").sort()}}catch(n){return{state:"unavailable",reason:nh(n)}}}function nh(e){let t=e&&typeof e=="object"?e:{};if(t.code==="ETIMEDOUT"||t.killed===!0)return`git status timed out after ${Wc}ms`;if(t.code==="ENOBUFS"||typeof t.message=="string"&&/maxBuffer|stdout.*buffer/i.test(t.message))return`git status exceeded its ${_i}-byte output limit`;if(typeof t.signal=="string"&&t.signal!=="")return`git status was terminated by ${t.signal}`;if(typeof t.status=="number")return`git status exited with status ${t.status}`;let n=typeof t.message=="string"?t.message.replaceAll(/\s+/g," ").trim().slice(0,240):String(e).replaceAll(/\s+/g," ").trim().slice(0,240);return n===""?"git status failed for an unknown reason":`git status failed: ${n}`}function ih(e,t){for(let n of["node_modules"]){let i=Se(e,n),o=Se(t,n);if(We(i)&&!We(o))try{Wm(i,o,"junction")}catch{}}}function Gc(e,t){let n=qm(Se(Bm(),t)),i=Se(n,"checkout");try{let o=on("git",["-C",e,"rev-parse","--verify","HEAD"],{encoding:"utf-8",timeout:3e4,maxBuffer:_i,killSignal:"SIGKILL"}).trim();return on("git",["clone","--quiet","--no-checkout","--shared","--",e,i],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),on("git",["-C",i,"checkout","--quiet","--detach","--force",o],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),{root:i,dispose(){Oc(n,{recursive:!0,force:!0})}}}catch(o){throw Oc(n,{recursive:!0,force:!0}),o}}function oh(e){let t=e;return t?.code==="ETIMEDOUT"||t?.killed===!0?"isolated HEAD snapshot timed out after 30000ms":typeof t?.signal=="string"&&t.signal!==""?`isolated HEAD snapshot was terminated by ${t.signal}`:typeof t?.status=="number"?`isolated HEAD snapshot failed because Git exited with status ${t.status}`:"isolated HEAD snapshot failed; confirm that Git can read the repository and committed HEAD"}function Vc(e,t){let n=new Map;for(let i of t.entries){let o=n.get(i.file)??[];o.push({start:i.startLine,end:i.endLine}),n.set(i.file,o)}for(let[i,o]of n){let r=Se(e,i);if(!We(r))continue;let s=Ce(r,{maxBytes:vt,inputKind:"cleanup verification source file"});_m(r,ah(s,o,{rust:i.endsWith(".rs")}))}}function rh(e,t={}){let n=e.flatMap(i=>i.entries.map(o=>({batch:i.depth,file:o.file,startLine:o.startLine,endLine:o.endLine,loc:o.loc,symbol:o.shortName})));return{dryRun:t.dryRun===!0,batches:e.length,symbols:n.length,loc:e.reduce((i,o)=>i+o.loc,0),files:[...new Set(n.map(i=>i.file))],filesEmptied:[...new Set(e.flatMap(i=>i.filesEmptied))],targets:n}}function sh(e,t,n={}){let i=rh(t,n);if(!i.dryRun)for(let o of t)Vc(e,o);return i}function Uc(e,t){let n=Gc(e,"scip-cleanup-patch-");try{return sh(n.root,t),on("git",["-C",n.root,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024,timeout:3e4,killSignal:"SIGKILL"})}finally{n.dispose()}}function Hc(e,t={}){if(t.all)return[...e.batches];if(t.batch!==void 0){let n=e.batches.find(i=>i.depth===t.batch);return n?[n]:[]}return[...e.batches]}function Qc(e,t,n={}){if(e.unavailableReason)return[`Cleanup verification is unavailable: ${e.unavailableReason}.`];let i=[];e.checkers.length===0&&i.push("No project checker was detected, so no deletion patch is compiler-verified."),e.uncoveredFiles.length>0&&i.push(`No detected checker covers: ${e.uncoveredFiles.join(", ")}.`),!n.allowUnknownWorkingTree&&e.workingTree.state==="unavailable"&&i.push(`Working-tree inspection is unavailable: ${e.workingTree.reason}.`),!n.allowDirty&&e.dirtyOverlap.length>0&&i.push(`Plan files are dirty in the working tree: ${e.dirtyOverlap.join(", ")}.`);let o=new Set(e.batches.filter(r=>r.status==="verified").map(r=>r.depth));for(let r of t)o.has(r.depth)||i.push(`Batch ${r.depth} is not verified by the detected checker(s).`);return i}function ah(e,t,n={}){let i=e.split(`
4
- `),o=(n.rust===!0?ch(e):nr(e)).split(`
5
- `),r=new Set;for(let s of t){let a=lh(i,s.start),c=uh(o,a,Math.min(s.end,i.length-1));for(let l=a;l<=c&&l<i.length;l++)r.add(l)}return i.filter((s,a)=>!r.has(a)).join(`
6
- `)}function ch(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 lh(e,t){let n=t;for(;n>0;){let i=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(i))n-=1;else break}return n}var dh=200;function uh(e,t,n){let i=0;for(let o=t;o<e.length;o++){for(let r of e[o]??"")r==="("||r==="["||r==="{"?i+=1:(r===")"||r==="]"||r==="}")&&(i-=1);if(o>=n&&i<=0)return o;if(o-n>dh)break}return n}function qc(e,t,n){let i=Dm(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,killSignal:"SIGKILL",env:e.env??process.env,maxBuffer:33554432}),o=`${i.stdout??""}
7
- ${i.stderr??""}`;if(i.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:Fc(o)};let r=ph(e.label,o),s=r.diagnostics.length>0?r.diagnostics:i.error?[{file:"",message:String(i.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:i.status,rawErrors:s.map(Sh),diagnostics:s,parseBasis:r.parseBasis,outputTail:Fc(o)}}function ph(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:mh(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:hh(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=fh(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:gh(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:yh(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:bh(t),parseBasis:"clj-kondo-json"}:{diagnostics:vh(t),parseBasis:"heuristic"}}function mh(e){let t=[],n=/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/gm;for(let i of e.matchAll(n))t.push({file:i[1]??"",line:Number(i[2]),column:Number(i[3]),code:i[4],message:i[5]??"",parseBasis:"tsc"});return t}function hh(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+(.+)$/gm;for(let i of e.matchAll(n))t.push({file:i[1]??"",line:Number(i[2]),column:Number(i[3]),message:i[4]??"",parseBasis:"go"});return t}function fh(e){let t=Kc(e);if(!Array.isArray(t))return[];let n=[];for(let i of t){if(!i||typeof i!="object")continue;let o=i,r=o.location,s=r&&typeof r=="object"?r:{},a=typeof o.filename=="string"?o.filename:"",c=typeof o.message=="string"?o.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 o.code=="string"?o.code:void 0,message:c,parseBasis:"ruff-json"})}return n}function gh(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+([A-Z]\d{3})\s+(.+)$/gm;for(let i of e.matchAll(n))t.push({file:i[1]??"",line:Number(i[2]),column:Number(i[3]),code:i[4],message:i[5]??"",parseBasis:"ruff-text"});return t}function yh(e){let t=[];for(let n of e.split(`
8
- `)){if(!n.trim().startsWith("{"))continue;let i=Wi(n);if(!i||typeof i!="object")continue;let o=i;if(o.reason!=="compiler-message")continue;let r=o.message;if(!r||typeof r!="object")continue;let s=r;if(s.level!=="error")continue;let l=(Array.isArray(s.spans)?s.spans:[]).find(m=>!!m&&typeof m=="object"&&m.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 bh(e){let t=Kc(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let i=[];for(let o of n){if(!o||typeof o!="object")continue;let r=o;r.level==="error"&&i.push({file:typeof r.filename=="string"?r.filename:"",line:typeof r.row=="number"?r.row:void 0,column:typeof r.col=="number"?r.col:void 0,code:typeof r.type=="string"?r.type:void 0,message:typeof r.message=="string"?r.message:"",parseBasis:"clj-kondo-json"})}return i}function vh(e){return e.split(`
9
- `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function Sh(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 Kc(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return Wi(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(i=>i>=0));return Number.isFinite(n)?Wi(t.slice(n)):null}function Wi(e){try{return JSON.parse(e)}catch{return null}}function Fc(e,t=10){return e.split(`
10
- `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Yc={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"]},$h={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"},Rh={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 Xe(e,t){let n=t.languages??An(e),i=n.map(a=>{let c=$n(Nn(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),o=Mh(e,n,t),r=Vi({semantics:o},"typescript"),s=Bi(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:i,semantics:o,semantic:r,checkers:s,gitAvailable:qh(e)}}function Lt(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,i=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",o=i!=="unavailable",r=e.languages.map(c=>Lh(e,c,{hasIndexedGraph:jh(c,t),runtimeProbe:t.runtimeProbe})),s=r.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:r,relations:xh(r,o),capabilities:[{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="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.`},...Th(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"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"?r.map(c=>`${c.language}: ${c.cleanupVerification.status} (${c.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-impact",label:"Git change mapping",status:e.gitAvailable&&o?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-symbol and downstream-consumer mapping.":"Git is unavailable or the project root is not a git worktree."}]}}function xh(e,t){return dc.map(n=>{let i=jr.flatMap(r=>{let s=r.relations.filter(a=>a.family===n.family);return s.length===0?[]:[Ch(r,s,e,t)]}),o=Gi(i.map(r=>r.status));return{...n,status:o,providerCapabilities:i,reason:o==="unsupported"?t?"The current project has no available provider for this relationship family.":"An indexed graph is required before this relationship family can be queried.":o==="exact"?"Exact within indexed compiler/source identity coverage; dynamic or unindexed constructs remain outside scope.":"Supported by bounded static providers; unresolved and unsupported constructs remain explicitly reported."}})}function Ch(e,t,n,i){let o=n.map(a=>kh(e,t,a,i)),r=Gi(o.map(a=>a.status)),s=o.filter(a=>a.status!=="unsupported").map(a=>a.language);return{id:e.id,label:e.label,status:r,requirements:e.requirements,subtypes:t.map(a=>a.subtype),languages:o,reason:s.length===0?`Unavailable: requires ${e.requirements.join(", ")}.`:`${r} support for ${s.join(", ")}; analytical ceiling is declared per subtype.`}}function kh(e,t,n,i){let o=e.requirements.filter(s=>!Eh(s,n,i));if(o.length>0)return{language:n.language,status:"unsupported",reason:`Missing ${o.join(", ")}.`};let r=Gi(t.map(s=>s.supportCeiling));return{language:n.language,status:r,reason:`${e.label} is available; subtype coverage is ${r}.`}}function Eh(e,t,n){switch(e){case"indexed-graph":return n&&t.indexing.status!=="unavailable";case"source-facts":return t.sourceFacts.status!=="unavailable";case"typescript-semantic":return t.language==="typescript"&&t.semantic.status==="available"}}function Gi(e){let t=e.filter(n=>n!=="unsupported");return t.length===0?"unsupported":t.every(n=>n==="exact")?"exact":t.some(n=>n==="exact"||n==="partial")?"partial":"candidate"}function Th(e){return Ih(e).map(t=>{let n=Vi(e,t),i=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${Ah(t)} semantic provider`,status:i,evidence:"semantic",reason:Ph(t,n)}})}function Ih(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of Zc(e))t.add(n.language);return[...t].sort((n,i)=>zc(n)-zc(i))}function zc(e){return e==="typescript"?0:1}function Ah(e){return e==="typescript"?"TypeScript":"Rust"}function Ph(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 Lh(e,t,n){let i=e.indexers.find(d=>d.language===t),o=i?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",r=o!=="unavailable",s=Nh(t,n.runtimeProbe),a=Oh(e,t),c=Dh(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:o,evidence:"graph-fact",reason:o==="available"?`${i?.binaryLabel??t} is runnable${i?.resolvedBinary?` at ${i.resolvedBinary}`:""}.`:o==="partial"?`An indexed ${t} graph is present, but ${i?.binaryLabel??t} is not currently runnable for refresh.`:i?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:r?s.status:"unavailable",evidence:"heuristic",reason:r?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:r?"available":"unavailable",evidence:"heuristic",reason:r?"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 ${Yc[t].join(", ")} files.`}}}function jh(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function Nh(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)??Jc(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=Xc(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 i=t?.(e)??Jc(e);return i==="unavailable"?{status:"partial",reason:"tree-sitter native module not loadable \u2014 regex/import-only evidence remains available where registered."}:i==="regex"?{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`}:i==="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 Jc(e){let t=$h[e];return t?vn(t):Xc(e)==="regex-only"?"regex":"unavailable"}function Xc(e){let t=Rh[e],n=t?or(t):null;return n?.imports??n?.exports??n?.reExports??null}function Mh(e,t,n){let i=[];if(t.includes("typescript")&&i.push({language:"typescript",...Mc(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")){let o=pr(e);i.push({language:"rust",available:o.available,dependencyAvailable:o.dependencyAvailable,resolvedBinary:o.resolvedBinary,reason:o.available?o.note:o.reason})}return i}function Zc(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Vi(e,t){return Zc(e).find(n=>n.language===t)}function Oh(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=Vi(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 Dh(e,t){let n=new Set(Yc[t]);return e.checkers.filter(i=>i.coversExtensions.some(o=>n.has(o)))}function qh(e){try{return wh("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import we from"process";import{rmSync as Tl}from"fs";import{resolve as Wf}from"path";import{pathToFileURL as _f}from"url";import{statSync as Fh,watch as Wh}from"fs";function el(e){let t=!1,n=!1,i,o=[],r=[...new Set(e)],s=new Map,a=m=>{try{return Fh(m).mtimeMs}catch{return null}},c=()=>{for(let m of r)s.set(m,a(m))},l=()=>r.some(m=>a(m)!==s.get(m));c();let d=()=>{n=!0;let m=i;i=void 0,m?.()};for(let m of r)try{let h=Wh(m,{persistent:!1},d);h.on("error",()=>{}),o.push(h)}catch{}return{wait(m){return t||m<=0?(n=!1,Promise.resolve()):new Promise(h=>{let p=setTimeout(()=>{i===f&&(i=void 0),h()},m),f=()=>{clearTimeout(p),i===f&&(i=void 0),h()};i=f,(n||t||l())&&(n=!1,c(),f())})},close(){if(!t){t=!0;for(let m of o)try{m.close()}catch{}o.length=0}d()}}}import{lstatSync as _h}from"fs";function nl(e,t){let n=Bn(e);if(n.kind!=="directory")throw new Error(`Watcher root is not a directory: ${e}`);if(!t)return{projectRoot:e,projectDirectory:n};let i=Bn(t);if(i.kind!=="directory")throw new Error(`Git control path is not a directory: ${t}`);return{projectRoot:e,projectDirectory:n,gitControlDirectory:{path:t,identity:i}}}function il(e){try{if(!tl(e.projectDirectory,Bn(e.projectRoot)))return!1;let t=e.gitControlDirectory;return!t||tl(t.identity,Bn(t.path))}catch{return!1}}function Bn(e){let t=_h(e,{bigint:!0}),n=t.isDirectory()?"directory":t.isFile()?"file":void 0;if(!n||t.isSymbolicLink())throw new Error(`Unsupported watcher identity path: ${e}`);return{device:t.dev,inode:t.ino,birthtimeNs:t.birthtimeNs,kind:n}}function tl(e,t){return e.device===t.device&&e.inode===t.inode&&e.birthtimeNs===t.birthtimeNs&&e.kind===t.kind}import{existsSync as Ji,lstatSync as Gh,statSync as ml,watch as Vh}from"fs";import{EventEmitter as Uh}from"events";import{basename as Hh,dirname as hl,isAbsolute as Yi,join as _e,relative as fl,resolve as gl}from"path";import{watch as Qh}from"chokidar";import Kh from"ignore";function Ui(e){let t=JSON.stringify(e);return Buffer.byteLength(t)<=65536?t:void 0}var yl=5e3,Un=class{projectRoot;config;watchConfig;outputDb;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;budgetInspector;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;budgetTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;pendingChanges=new Map;pendingChangesComplete=!0;pendingChangesIncompleteReason;reindexInFlight=!1;lastReindexEnd=0;lastObservedGeneration=null;publishedGeneration;indexFreshness;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;reconcileTimer=null;lastGitState=null;preferFilesystemGitState=!0;watchGitLayout=null;localCacheWatchPath;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Ke(t.config),this.outputDb=t.outputDb??_e(Jo(this.projectRoot,t.config),"index.db"),this.preferFilesystemGitState=t.gitReader===void 0,this.localCacheWatchPath=Sf(this.projectRoot,hl(this.outputDb)),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onReindexError=t.onReindexError??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.clock=t.clock??Zh,bl.set(this,wf(t.stopTimeoutMs??yl,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??df(),this.subscriptionFactory=t.subscriptionFactory??ef,this.budgetInspector=t.budgetInspector??oc,this.publishedGeneration=t.publishedGeneration??Qe,this.indexFreshness=t.indexFreshness??vf,this.lastObservedGeneration=this.readPublishedGeneration(),vl.set(this,{projectRoot:t.projectRoot,config:t.config,gitReader:t.gitReader??Vo,languages:wl(t.languages??t.config.languages),typeScriptInputPaths:null,stagedIndexEntries:null}),this.gitignoreFilter=ra(t.projectRoot),this.extraIgnore=Kh(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore),Qi(this)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,Vn(this).errors=[],this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let t=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.clearGitPollTimer(),this.clearReconcileTimer();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...Vn(this).closures],o=Jh(this),r=this.clock.now()+o;return this.stopPromise=this.finishStop(t,i,n,r,o).catch(s=>{throw this.stopInProgress=!1,s}),this.stopPromise}requestRefresh(t,n={}){if(!this.stopped){if(this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`),!n.immediate||this.reindexInFlight||this.status.state==="cooldown"||this.status.state==="budget-paused"){this.scheduleReindex(t);return}this.pendingTrigger=Hi(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(i,o)=>this.isIgnoredWatchPath(i,o?.isDirectory()??!1),usePolling:t,ignorePermissionErrors:!0,...t?{interval:5e3,binaryInterval:1e4}:{}});n.on("all",(i,o)=>{!this.stopped&&i!=="addDir"&&i!=="unlinkDir"&&this.handleFileChange(i,o)}),n.on("error",i=>this.handleSourceWatcherError(n,i,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,i){if(this.markPendingChangesIncomplete("source-watcher-error"),i||this.sourcePollingFallbackStarted||!hf(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(o=>o!==t),Yh(Vn(this),t,o=>this.onError(o));try{this.startSourceWatcher(!0)}catch(o){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(o)}`))}}isIgnoredWatchPath(t,n){let i=this.relativeWatchPath(t);if(!i)return!1;if(al(i,this.localCacheWatchPath))return!0;let o=n?`${i}/`:i;return this.gitignoreFilter.isIgnored(o)||this.extraIgnore.ignores(o)}handleFileChange(t,n){let i=this.relativeWatchPath(n);if(!i||i===".."||i.startsWith("../")||al(i,this.localCacheWatchPath)||this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)||i.endsWith("index.db")||i.endsWith("index.scip")||i.endsWith("index.db.tmp")||Hh(i).startsWith(nc))return;i===".scipquery.json"&&dl(this,this.projectRoot);let o=ul(this,t,i);o!==null&&(o||this.markPendingChangesIncomplete(`unsupported-source-event:${t}`),this.scheduleReindex({kind:"watch-source",detail:i},o?[{path:i,kind:o}]:void 0,o!==void 0))}relativeWatchPath(t){let n=Yi(t)?t:_e(this.projectRoot,t);return fl(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t,n,i=!1){this.pendingTrigger=Hi(this.pendingTrigger,t),i||this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`);for(let r of n??[])this.recordPendingChange(r);if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});let r=this.activeOperation;r&&jt.get(this)!==r&&(jt.set(this,r),r.cancel().then(s=>{s.state==="degraded"&&!this.stopped&&this.onError(new Error(s.reason))},s=>{this.stopped||this.onError(s instanceof Error?s:new Error(String(s)))}));return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}if(this.status.state==="budget-paused"){this.dirty=!0,this.setStatus({...this.status,dirty:!0});return}this.clearDebounceTimer();let o=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:o}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped||this.reconcileExternalPublication())return;let t=this.inspectBudget(),n=this.watchConfig.allowExpensiveRebuild&&t.state!=="paused";if(t.state==="paused"&&t.reason!=="rebuild-count"){this.dirty=!0;let c=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:c,dirty:!0,reason:t.detail,rebuilt:t.rebuilt,estimatedWriteBytes:t.estimatedWriteBytes}),this.clearBudgetTimer(),this.budgetTimer=this.clock.setTimeout(()=>{this.budgetTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},Math.min(2147483647,Math.max(1,c-this.wallNow())));return}let i=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&i<this.watchConfig.cooldownMs){let c=this.watchConfig.cooldownMs-i;this.dirty=!0;let l=this.wallNow()+c;this.setStatus({state:"cooldown",until:l,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},c);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let o=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=this.consumePendingChangeJournal(),s=this.wallNow();this.setStatus({state:"indexing",startedAt:s});let a=this.reindexRunner.start(this.reindexRequest(o,n,r));this.activeOperation=a,a.completion.then(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),Gn.set(this,0),this.stopped)return;if(jt.get(this)===a){if(this.restorePendingChangeJournal(r),this.dirty){let d=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:d,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"});return}Qi(this),this.lastObservedGeneration=this.readPublishedGeneration();let l=!1;try{l=this.onReindexComplete(c,o,{pendingChanges:this.dirty})===!0}catch(d){this.onError(d instanceof Error?d:new Error(String(d)))}if(this.dirty&&!this.stopped){if(l){let m=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),this.onRefreshSuppressed(m),this.setStatus({state:"idle"});return}let d=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:d,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let l=c instanceof Error?c:new Error(String(c));this.restorePendingChangeJournal(r);let d=Sl(l),m=0;if(d?(m=(Gn.get(this)??0)+1,Gn.set(this,m),this.dirty=!0,this.pendingTrigger=Hi(this.pendingTrigger,o)):Gn.set(this,0),!d&&jt.get(this)!==a&&(this.onReindexError(l,o),this.onError(l)),this.dirty){let h=d?lf(this.watchConfig.cooldownMs,m):this.watchConfig.cooldownMs,p=this.wallNow()+h;this.setStatus({state:"cooldown",until:p,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},h);return}this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===a&&(this.activeOperation=null),jt.get(this)===a&&jt.delete(this)})}async finishStop(t,n,i,o,r){let s=[],a=t.map(async h=>{try{await h.close()}catch(p){s.push(`watch subscription close failed: ${String(p)}`)}});a.push(...n),i&&a.push((async()=>{try{let h=await i.cancel();h.state==="degraded"&&s.push(h.reason)}catch(h){s.push(`reindex cancellation failed: ${h instanceof Error?h.message:String(h)}`)}})());let c=a.length,l=a.map(h=>h.finally(()=>{c-=1})),d=await zh(l,o,this.clock),m=Vn(this);return s.push(...m.errors),m.errors=[],d?this.stopInProgress=!1:(s.push(`watch shutdown exceeded the ${r}ms deadline with ${c} operation(s) still pending`),Promise.all(l).then(()=>{this.stopInProgress=!1})),s.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:s.join("; ")}),{state:"degraded",reasons:s}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}inspectBudget(){try{return this.budgetInspector(this.outputDb,this.watchConfig.resourceBudget,new Date(this.wallNow()))}catch(t){return{state:"paused",reason:"activity-evidence",until:this.wallNow()+this.watchConfig.resourceBudget.windowMs,rebuilt:0,estimatedWriteBytes:0,detail:`reindex activity evidence could not be read: ${t instanceof Error?t.message:String(t)}`}}}reindexRequest(t,n=!0,i){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:t,changeJournal:i,allowExpensiveRebuild:n}}setStatus(t){this.status=t,t.state==="cooldown"||t.state==="budget-paused"?this.armReconcileTimer(t.until):this.clearReconcileTimer(),this.onStatus(t)}recordPendingChange(t){if(this.pendingChanges.size>=1024&&!this.pendingChanges.has(t.path)){this.pendingChanges.clear(),this.markPendingChangesIncomplete("change-entry-limit");return}let n=this.pendingChanges.get(t.path),i=pf(n,t.kind);i===null?this.pendingChanges.delete(t.path):this.pendingChanges.set(t.path,i)}markPendingChangesIncomplete(t){this.pendingChangesComplete=!1,this.pendingChangesIncompleteReason??=t}consumePendingChangeJournal(){let t=Qe(this.outputDb),n=[...this.pendingChanges.entries()].map(([s,a])=>({path:s,kind:a})).sort((s,a)=>s.path.localeCompare(a.path)),i=this.pendingChangesComplete,o=this.pendingChangesIncompleteReason;t||(i=!1,o??="accepted-generation-unavailable");let r={version:1,baseGeneration:t,complete:i,...o?{incompleteReason:o}:{},entries:n};return Ui(r)||(r={version:1,baseGeneration:t,complete:!1,incompleteReason:"change-journal-byte-limit",entries:[]}),this.resetPendingChanges(),r}restorePendingChangeJournal(t){let n=[...this.pendingChanges.entries()].map(([r,s])=>({path:r,kind:s})),i=this.pendingChangesComplete,o=this.pendingChangesIncompleteReason;this.resetPendingChanges(),t.complete||this.markPendingChangesIncomplete(t.incompleteReason??"failed-reindex");for(let r of t.entries)this.recordPendingChange(r);i||this.markPendingChangesIncomplete(o??"failed-reindex");for(let r of n)this.recordPendingChange(r)}resetPendingChanges(){this.pendingChanges.clear(),this.pendingChangesComplete=!0,this.pendingChangesIncompleteReason=void 0}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}clearBudgetTimer(){this.budgetTimer&&(this.clock.clearTimeout(this.budgetTimer),this.budgetTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(at(this).stagedIndexEntries=pl(this.projectRoot,at(this).gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}armReconcileTimer(t){this.clearReconcileTimer();let n=t-this.wallNow();if(n<=0||!(this.watchConfig.gitPollMs>0))return;let i=Math.min(this.watchConfig.gitPollMs,n);this.reconcileTimer=this.clock.setTimeout(()=>{this.reconcileTimer=null,!(this.stopped||this.reconcileExternalPublication())&&(this.status.state==="cooldown"||this.status.state==="budget-paused")&&this.armReconcileTimer(this.status.until)},i),this.reconcileTimer.unref?.()}clearReconcileTimer(){this.reconcileTimer&&(this.clock.clearTimeout(this.reconcileTimer),this.reconcileTimer=null)}readPublishedGeneration(){try{return this.publishedGeneration(this.outputDb)}catch{return null}}reconcileExternalPublication(){if(this.stopped||this.reindexInFlight||!(this.dirty||this.status.state==="budget-paused"||this.status.state==="cooldown"||this.status.state==="waiting"))return!1;let n=this.readPublishedGeneration();if(n===null||n===this.lastObservedGeneration)return!1;this.lastObservedGeneration=n;let i;try{i=this.indexFreshness(this.projectRoot,this.config,this.outputDb)}catch{return!1}if(i!=="fresh")return!1;let o=this.pendingTrigger??{kind:"unknown"};return this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),Qi(this),this.onRefreshSuppressed({...o,detail:`a generation published outside the watcher is fresh${o.detail?` (${o.detail})`:""}`}),this.setStatus({state:"idle"}),!0}pollGitState(){if(this.reindexInFlight||this.stopped)return;let t=this.lastGitState,n=this.readGitState();if(!t||!n||this.stopped){this.lastGitState=n;return}this.lastGitState=n;let i=t.head!==n.head,o=t.indexPath!==n.indexPath||t.indexMtimeMs!==n.indexMtimeMs||t.indexSize!==n.indexSize;if(!i&&!o)return;let r=at(this),s=r.stagedIndexEntries,a=pl(this.projectRoot,r.gitReader);r.stagedIndexEntries=a;let c=Cf(this.projectRoot,r.gitReader,t,n,s,a,i,o),l=null;if(c!==null&&(c.includes(".scipquery.json")&&dl(this,this.projectRoot),l=c.filter(m=>ul(this,"add",m)!==null),l.length===0))return;let d=l?.map(m=>({path:m,kind:Ji(_e(this.projectRoot,m))?"change":"delete"}));i&&o?this.scheduleReindex({kind:"watch-git-state",detail:Ki("HEAD and index changed",l)},d,d!==void 0):i?this.scheduleReindex({kind:"watch-git-head",detail:Ki("HEAD changed",l)},d,d!==void 0):o&&this.scheduleReindex({kind:"watch-git-index",detail:Ki(n.indexPath??"index changed",l)},d,d!==void 0)}readGitState(){if(this.preferFilesystemGitState){let t=this.readFilesystemGitState();if(t)return t}return this.readGitStateFromGit()}readFilesystemGitState(){let t=this.watchGitLayout??ff(this.projectRoot);if(!t)return null;this.watchGitLayout=t;let n=gf(t.gitDir);return n?ll(n,t.indexPath):null}readGitStateFromGit(){let t=at(this).gitReader,n=bi(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let i=Qo(this.projectRoot,n);return ll(bi(this.projectRoot,["rev-parse","--verify","HEAD"],t),i)}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function zh(e,t,n){if(e.length===0)return!0;let i=Promise.all(e).then(()=>!0),o=Math.max(0,t-n.now()),r=null,s=new Promise(c=>{r=n.setTimeout(()=>c(!1),o)}),a=await Promise.race([i,s]);return a&&r&&n.clearTimeout(r),a}var rl=new WeakMap,bl=new WeakMap,vl=new WeakMap,jt=new WeakMap,Gn=new WeakMap;function Vn(e){let t=rl.get(e);if(t)return t;let n={closures:new Set,errors:[]};return rl.set(e,n),n}function Jh(e){return bl.get(e)??yl}function at(e){let t=vl.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function Yh(e,t,n){let i=Promise.resolve().then(()=>t.close()).catch(o=>{let r=`watch subscription close failed during polling fallback: ${String(o)}`;e.errors.push(r),n(new Error(r))});e.closures.add(i),i.then(()=>e.closures.delete(i))}function Xh(e,t=He){let{projectRoot:n,config:i,languages:o,pnpmWorkspaces:r,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:c,indexerConcurrency:l,trigger:d}=e,m=Ee(n),h=Object.keys(m).length>0?m:i,p=Ue(n,h),f=h.indexer?.typescript,g=h.indexer?.clojure,y=t(process.pid);if(!y)throw new Error(`Could not establish watcher process identity for reindex worker ownership (pid ${process.pid}).`);return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:n,SCIP_REINDEX_OUTPUT_SCIP:p.indexPath,SCIP_REINDEX_OUTPUT_DB:p.dbPath,SCIP_REINDEX_LANGUAGES:(h.languages??o)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(h.indexerConcurrency??l??""),SCIP_REINDEX_PNPM_WORKSPACES:f?.pnpmWorkspaces??r?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:f?.projectMode??s,projects:f?.projects??a??[],maxHeapMb:f?.maxHeapMb}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:g?.configPath??c??"",SCIP_REINDEX_TRIGGER_KIND:d.kind,SCIP_REINDEX_TRIGGER_DETAIL:d.detail??"",SCIP_REINDEX_CHANGE_JOURNAL:e.changeJournal?Ui(e.changeJournal)??"":"",SCIP_REINDEX_ALLOW_EXPENSIVE:e.allowExpensiveRebuild===!1?"0":"1",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(y)}}}var Zh={now:ke,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ef=(e,t)=>tf(process.platform,t.usePolling)?new zi(e):Qh(e,t);function tf(e,t){return e==="darwin"&&t!==!0}var rn=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="RecursiveSourceWatchError"}},zi=class{events=new Uh;watcher;constructor(t){this.watcher=Vh(t,{recursive:!0},(n,i)=>{if(i===null){this.events.emit("error",new rn("Recursive source watcher omitted the changed path."));return}let o=_e(t,i.toString());this.events.emit("all",nf(n,o),o)}),this.watcher.on("error",n=>{this.events.emit("error",new rn(`Recursive source watcher failed: ${n.message}`,n))})}on=(t,n)=>(this.events.on(t,n),this);close(){this.watcher.close()}};function nf(e,t){return e==="change"?"change":Ji(t)?ml(t).isDirectory()?"addDir":"add":"unlink"}var of=15*6e4,rf=1e3,sf=64*1024;function af(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function sl(e,t){let n=e instanceof Error?e.message:String(e),i=t.stderrTail.trim()||t.stdoutTail.trim();return i?`${n}
11
- ${i}`:n}function cf(e,t){return Object.assign(new Error(e,t===void 0?void 0:{cause:t}),{retryable:!0})}function Sl(e){return e instanceof Error&&"retryable"in e&&e.retryable===!0}function lf(e,t){let n=e*2**Math.min(5,Math.max(0,t-1));return Math.max(e,Math.min(3e4,n))}function df(e={}){let t=e.timeoutMs??of,n=e.terminationGraceMs??rf,i=e.maxOutputBytes??sf,o=e.resolveLaunch??Xh;return{start(r){let s=o(r),a=new AbortController,c=af(),l=!1,d=Ea({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:i,maxStderrBytes:i,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(m=>{if(c={stdoutTail:m.stdout,stderrTail:m.stderr,stdoutTruncated:m.stdoutTruncated,stderrTruncated:m.stderrTruncated},m.status!==0){let h=sl(new Error(`Reindex worker exited with ${m.signal?`signal ${m.signal}`:`code ${m.status}`}`),c);throw m.status===75?cf(h):new Error(h)}return m.durationMs}).catch(m=>{throw Sl(m)?m:(m instanceof ka&&(c={stdoutTail:m.stdout,stderrTail:m.stderr,stdoutTruncated:m.stdoutTruncated,stderrTruncated:m.stderrTruncated}),new Error(sl(m,c),{cause:m}))}).finally(()=>{l=!0});return{completion:d,async cancel(){l||a.abort();try{await d}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Hi(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 uf(e){if(e==="add")return"add";if(e==="change")return"change";if(e==="unlink")return"delete"}function pf(e,t){return e?e==="add"?t==="delete"?null:"add":e==="delete"&&t==="add"?"change":t:t}function mf(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function hf(e){return e instanceof rn||mf(e)}var Xi=/^[0-9a-f]{40,64}$/i;function al(e,t){return e===".git"||e.startsWith(".git/")||e==="node_modules"||e.startsWith("node_modules/")||e.endsWith("/node_modules")||e.includes("/node_modules/")?!0:t!==void 0&&(e===t||e.startsWith(`${t}/`))}function ff(e){let t=_e(e,".git");try{let n=Gh(t),i;if(n.isDirectory())i=t;else if(n.isFile()){let o=/^gitdir:\s*(.+)\s*$/m.exec(ae(t,"Git directory marker"));if(!o?.[1])return null;let r=o[1].trim();i=Yi(r)?r:gl(e,r)}else return null;return Ji(i)?{gitDir:i,indexPath:_e(i,"index")}:null}catch{return null}}function gf(e){let t;try{t=ae(_e(e,"HEAD"),"Git HEAD").trim()}catch{return}if(Xi.test(t))return t.toLowerCase();let n=/^ref:\s*(.+)$/.exec(t)?.[1]?.trim();if(!n)return;let i=yf(e);return cl(e,n)??cl(i,n)??bf(i,n)}function yf(e){try{let t=ae(_e(e,"commondir"),"Git common-directory marker").trim();return t?Yi(t)?t:gl(e,t):e}catch{return e}}function cl(e,t){try{let n=ae(_e(e,t),"Git reference").trim();return Xi.test(n)?n.toLowerCase():void 0}catch{return}}function bf(e,t){try{for(let n of ae(_e(e,"packed-refs"),"Git packed references").split(`
12
- `)){if(n.startsWith("#")||n.startsWith("^"))continue;let i=n.indexOf(" ");if(i===-1)continue;let o=n.slice(0,i);if(n.slice(i+1).trim()===t&&Xi.test(o))return o.toLowerCase()}}catch{return}}function vf(e,t,n){let i=hl(n);return Te(e,t,{dbPath:n,metaPath:_e(i,"meta.json"),cacheDir:i}).state}function ll(e,t){let n={head:e,indexPath:t};try{let i=ml(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}function Sf(e,t){let n=fl(e,t).replaceAll("\\","/");if(!(!n||n===".."||n.startsWith("../")))return n}function wf(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function wl(e){return e&&e.length>0?[...e]:Bt}function dl(e,t){try{let n=at(e);n.config=Ee(t),n.languages=wl(n.config.languages)}catch{at(e).languages=Bt}}function ul(e,t,n){let i=at(e);if(yi(n,i.languages)==="other")return null;let r=uf(t);if(n===".scipquery.json"||Ko(n))return i.typeScriptInputPaths=null,r;if(!$f(n,i.languages))return r;let s=i.typeScriptInputPaths;if(!s)return r;let a=s.has(n);if(r!=="add")return a?r:null;if(a)return"change";let c=$l(e);return c?c.has(n)?"add":null:r}function Qi(e){let t=at(e);if(!t.languages.includes("typescript")){t.typeScriptInputPaths=null;return}let n=Rf(t.projectRoot,t.config,t.languages);t.typeScriptInputPaths=n??$l(e)}function $l(e){let t=at(e);if(!t.languages.includes("typescript"))return t.typeScriptInputPaths=null,null;try{let n=t.config.indexer?.typescript,i=zo(t.projectRoot,n?.projectMode,n?.projects);return t.typeScriptInputPaths=i,i}catch{return t.typeScriptInputPaths=null,null}}function $f(e,t){if(!t.includes("typescript"))return!1;let n=yi(e,["typescript","javascript"]);return n==="source"||n==="ambient"}function Rf(e,t,n){try{let i=er(ae(Ue(e,t).metaPath,"reindex metadata"));if(i.kind!=="supported"&&i.kind!=="legacy")return null;let o=Bo(i.metadata.fingerprint);return!o||!xf(o,n,t)?null:new Set(o.files.map(r=>r.path))}catch{return null}}function xf(e,t,n){let i=Zo(t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath});return e.version===i.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(i.languages)&&e.pnpmWorkspaces===i.pnpmWorkspaces&&e.typescriptProjectMode===i.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(i.typescriptProjects)&&e.clojureConfigPath===i.clojureConfigPath}function Cf(e,t,n,i,o,r,s,a){let c=new Set;if(s){if(!n.head||!i.head)return null;let l=t.runResult(e,["diff","--name-only","-z","--no-renames","--relative",n.head,i.head,"--"]);if(l.kind!=="success")return null;for(let d of kf(l.output))c.add(d)}if(a){if(o===null||r===null)return null;for(let l of Tf(o,r))c.add(l)}return[...c].sort()}function pl(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?Ef(n.output):null}function kf(e){return e.split("\0").filter(t=>t.length>0)}function Ef(e){let t=e.split("\0");if(t.at(-1)===""&&t.pop(),t.length%2!==0)return null;let n=new Map;for(let i=0;i<t.length;i+=2){let o=t[i],r=t[i+1];if(!o.startsWith(":")||!r)return null;n.set(r,o)}return n}function Tf(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(i=>e.get(i)!==t.get(i))}function Ki(e,t){return t===null?`${e}; changed paths unavailable`:t.length===0?e:t.length===1?t[0]:`${t.length} compiler inputs changed`}var Hn=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(t,n={}){this.root=t,this.now=n.now??Date.now,this.randomId=n.randomId,this.retryDelayMs=Math.max(1,Math.floor(n.retryDelayMs??1e3)),this.currentStatus=tn(t)}initializeAfterOwnershipAcquired(){let t=hc(this.root),n=fc(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:t,prunedHistory:n}}observeLegacyRequest(t,n){uc(this.root,n??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${t}`,now:()=>new Date(t)}),this.refreshStatus()}poll(t,n){if(this.active||t.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let i=pc(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),i.requests.length===0)return!1;this.active=i;try{return n(If(i)),!0}catch(o){throw Di(this.root,i),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),o}}completeActive(){return this.active?(mc(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(Di(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=tn(this.root)}};function If(e){if(e.requests.length===1)return e.requests[0].detail;let n=[...new Set(e.requests.map(i=>i.detail))].slice(0,3).join("; ");return`${e.requests.length} coalesced refresh requests${n?`: ${n}`:""}`.slice(0,2048)}import{randomUUID as Pf}from"crypto";import{rmSync as Lf}from"fs";import{Worker as jf}from"worker_threads";var Qn=class{constructor(t){this.options=t;if(this.now=t.now??Date.now,this.setTimer=t.setTimer??setTimeout,this.clearTimer=t.clearTimer??clearTimeout,t.maxWorkerFailureRetries!==void 0&&(!Number.isInteger(t.maxWorkerFailureRetries)||t.maxWorkerFailureRetries<0))throw new Error("Worker maxWorkerFailureRetries must be a non-negative integer.")}options;now;setTimer;clearTimer;worker=null;active=null;activeFailure=null;terminating=null;closed=!1;workerGeneration=0;idleTimer=null;canAccept(){return!this.closed&&this.active===null&&this.terminating===null}hasWorker(){return this.worker!==null}start(t){if(!this.canAccept())return!1;if(this.clearIdleTimer(),t.deadlineAtMs<this.now()){try{this.options.onReject(t,`${this.options.name} request expired before processing.`)}catch(o){this.closed=!0,this.options.onFatal(Zi(o))}return!0}let n=this.ensureWorker(),i=this.deadlineTimer(t);this.active={request:t,timer:i,workerFailureRetries:0,workerFailureReasons:[]};try{n.postMessage({kind:"request",...t})}catch(o){this.failActiveAfterTermination(eo(o),!0)}return!0}async close(t=`${this.options.name} service is shutting down.`){if(this.closed=!0,this.clearIdleTimer(),this.active){await this.failActiveAfterTermination(t);return}await this.terminateWorker()}ensureWorker(){if(this.worker)return this.worker;let t=this.options.createWorker(),n=++this.workerGeneration;return t.on("message",i=>this.handleMessage(n,i)),t.on("error",i=>{n===this.workerGeneration&&this.failActiveAfterTermination(`${this.options.name} worker failed: ${i.message}`,!0)}),t.on("exit",i=>{n!==this.workerGeneration||this.terminating||(this.worker=null,this.active&&this.failActiveAfterTermination(`${this.options.name} worker exited unexpectedly with code ${i}.`,!0))}),this.worker=t,t}handleMessage(t,n){if(t!==this.workerGeneration||this.closed||!this.active)return;let i=Af(n);if(!i){this.failActiveAfterTermination(`${this.options.name} worker returned an invalid response.`);return}if(i.requestId!==this.active.request.requestId){this.failActiveAfterTermination(`${this.options.name} worker returned a mismatched request identity.`);return}if(this.now()>this.active.request.deadlineAtMs){this.failActiveAfterTermination(`${this.options.name} request expired while it was processing.`);return}let o=this.active,r;try{this.options.onStatus(i.status),i.ok?this.options.onComplete(o.request,i.result,i.status):this.options.onReject(o.request,i.error,i.status),r=this.options.retireAfterResponse?.(i.status)??!1}catch(s){this.closed=!0,this.clearTimer(o.timer),this.options.onFatal(Zi(s));return}this.releaseActive(o),r?this.terminateWorker():this.scheduleIdleTermination()}async failActiveAfterTermination(t,n=!1){if(this.activeFailure){await this.activeFailure;return}let i=this.active;if(!i){await this.terminateWorker();return}this.clearTimer(i.timer),n&&i.workerFailureReasons.push(t);let o=(async()=>{if(!await this.terminateWorker())return;let s=this.options.maxWorkerFailureRetries??0;if(n&&!this.closed&&i.workerFailureRetries<s&&this.now()<=i.request.deadlineAtMs){i.workerFailureRetries+=1;try{let c=this.ensureWorker();i.timer=this.deadlineTimer(i.request),c.postMessage({kind:"request",...i.request});return}catch(c){let l=`Cold Worker retry failed: ${eo(c)}`;if(i.workerFailureReasons.push(l),t=`${t} ${l}`,!await this.terminateWorker())return}}let a=i.workerFailureReasons.length===0?t:[...new Set([...i.workerFailureReasons,t])].join(" Cold Worker retry: ");try{this.options.onReject(i.request,a)}catch(c){this.closed=!0,this.options.onFatal(Zi(c));return}this.releaseActive(i)})();this.activeFailure=o;try{await o}finally{this.activeFailure===o&&(this.activeFailure=null)}}deadlineTimer(t){let n=Math.max(1,Math.min(2147483647,t.deadlineAtMs-this.now()));return this.setTimer(()=>{this.failActiveAfterTermination(`${this.options.name} request exceeded its deadline.`)},n)}releaseActive(t){this.active===t&&(this.active=null,this.clearTimer(t.timer))}scheduleIdleTermination(){let t=this.options.idleTtlMs;!t||t<=0||this.closed||this.active||!this.worker||(this.clearIdleTimer(),this.idleTimer=this.setTimer(()=>{this.idleTimer=null,!(this.closed||this.active||!this.worker)&&this.terminateWorker()},t))}clearIdleTimer(){this.idleTimer&&(this.clearTimer(this.idleTimer),this.idleTimer=null)}async terminateWorker(){if(this.clearIdleTimer(),this.terminating)return this.terminating;let t=this.worker;if(!t)return!0;this.worker=null;let n=++this.workerGeneration;return this.terminating=(async()=>{try{return await t.terminate(),!0}catch(i){return this.closed=!0,this.options.onFatal(new Error(`${this.options.name} worker termination failed: ${eo(i)}`,{cause:i})),!1}finally{n===this.workerGeneration&&(this.terminating=null)}})(),this.terminating}};function Af(e){if(!e||typeof e!="object")return null;let t=e;if(t.kind!=="response"||typeof t.requestId!="string"||!("status"in t))return null;if(t.ok===!0){if(!("result"in t)||"error"in t)return null}else if(t.ok===!1){if("result"in t||typeof t.error!="string")return null}else return null;return t}function Zi(e){return e instanceof Error?e:new Error(String(e))}function eo(e){return e instanceof Error?e.message:String(e)}var Nf=6e4,Mf=10*6e4;function Rl(e){let t=e.maxActiveSessions??8,n=e.workerSoftMemoryMb??Df(e.workerHeapMb),i=()=>({protocolVersion:On,state:"idle",requests:0,sessionsCreated:0,sessionsReplaced:0,sessionsEvicted:0,activeSessions:0,maxActiveSessions:t,softMemoryLimitBytes:n*1024*1024,retireRequested:!1,initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0});return Cl({name:"TypeScript index",paths:e.paths,now:e.now,limits:e.limits,initialStatus:i,parseEnvelope:sc,createWorker:()=>El(e,{kind:"index",projectRoot:e.projectRoot,dbPath:e.dbPath,maxActiveSessions:t,softMemoryLimitMb:n}),complete(o,r,s,a){ki(e.paths,o,{ok:!0,protocolVersion:On,id:r.id,baseGeneration:r.baseGeneration,response:s},{nowMs:a,limits:e.limits})},reject(o,r,s,a){Ei(e.paths,o,{ok:!1,protocolVersion:On,id:r,error:s},s,{nowMs:a,limits:e.limits})},idleTtlMs:e.workerIdleMs??Mf,maxWorkerFailureRetries:1,retireAfterResponse:o=>o.retireRequested===!0,statusWhenWorkerAbsent:o=>({...o,state:"idle",activeSessions:0,heapUsedBytes:0,retireRequested:!1}),onBusy:e.onBusy,onFatal:e.onFatal})}function xl(e){let t=()=>({protocolVersion:Tn,state:"idle",requests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0});return Cl({name:"TypeScript semantic",paths:e.paths,now:e.now,limits:e.limits,initialStatus:t,parseEnvelope:Cr,createWorker:()=>El(e,{kind:"semantic",projectRoot:e.projectRoot}),complete(n,i,o,r){ki(e.paths,n,{ok:!0,protocolVersion:Tn,id:i.id,generation:i.generation,response:o},{nowMs:r,limits:e.limits})},reject(n,i,o,r){Ei(e.paths,n,{ok:!1,protocolVersion:Tn,id:i,error:o},o,{nowMs:r,limits:e.limits})},idleTtlMs:Nf,onBusy:e.onBusy,onFatal:e.onFatal})}function Cl(e){let t=e.now??Date.now,n=He(process.pid),i={pid:process.pid,...n?{processIdentity:n}:{}},o=`${e.name.toLowerCase().replaceAll(" ","-")}-${process.pid}-${Pf()}`,r={...e.limits,maxBatch:1},s=null,a=e.initialStatus(),c=!1,l=p=>{c=!0,e.onFatal(p)},d=new Qn({name:e.name,createWorker:e.createWorker,now:t,idleTtlMs:e.idleTtlMs,maxWorkerFailureRetries:e.maxWorkerFailureRetries,retireAfterResponse:e.retireAfterResponse,onComplete(p,f,g){let y=m(p.requestId);a=g;let v=t();try{e.complete(y.claim,y.envelope,f,v)}catch($){if(!($ instanceof xi))throw $;try{e.reject(y.claim,y.envelope.id,$.message,v)}catch(L){if(!(L instanceof xi))throw L;Lf(y.claim.path,{force:!0})}}h(y)},onReject(p,f,g){let y=m(p.requestId);g!==void 0&&(a=g),e.reject(y.claim,y.envelope.id,f,t()),h(y)},onStatus(p){a=p},onFatal:l});return{poll(){if(c||!d.canAccept())return 0;let p=br(e.paths,{ownerId:o,nowMs:t(),limits:r,owner:i,liveness:{isProcessAlive:Rn,readProcessIdentity:He}})[0];if(!p)return 0;let f=p.requestId;try{let g=e.parseEnvelope(vr(p,r));if(f=g.id,g.id!==p.requestId)throw new Error(`${e.name} request identity does not match its mailbox path.`);if(g.deadlineAtMs<t())throw new Error(`${e.name} request expired before processing.`);if(s={claim:p,envelope:g},e.onBusy?.(g.deadlineAtMs),!d.start({requestId:g.id,deadlineAtMs:g.deadlineAtMs,payload:g}))throw new Error(`${e.name} worker lane closed admission after claiming a request.`)}catch(g){let y=Ff(g);try{e.reject(p,f,y,t()),s?.claim===p&&h(s)}catch(v){l(qf(v))}}return 1},status(){return{...d.hasWorker()||!e.statusWhenWorkerAbsent?a:e.statusWhenWorkerAbsent(a),mailbox:Sr(e.paths)}},async close(p){await d.close(p)}};function m(p){let f=s;if(!f||f.envelope.id!==p)throw new Error(`${e.name} parent lost the active mailbox claim.`);return f}function h(p){s===p&&(s=null,e.onBusy?.(void 0))}}var Of=6144;function kl(){let e=Number.parseInt(process.env.SCIP_TS_WORKER_HEAP_MB??"",10);return Number.isFinite(e)&&e>0?e:Of}function Df(e){return Math.max(1,Math.floor((e??kl())*.9))}function El(e,t){if(e.createWorker)return e.createWorker(t);let n=e.workerUrl??new URL("./typescript-mailbox-worker.js",import.meta.url);return new jf(n,{workerData:t,resourceLimits:{maxOldGenerationSizeMb:e.workerHeapMb??kl()}})}function qf(e){return e instanceof Error?e:new Error(String(e))}function Ff(e){return e instanceof Error?e.message:String(e)}var Il=2e3,Bf=5e3,Gf=5e3,Vf=6e4,Uf=10,Hf=50,Qf=1e4;function Kf(e,t=1){return hr(e,t,Uf,Hf,Qf,8)}function zf(e,t){let n;return{begin(){return n||(t.requestStop(),t.closeWake(),n=e.stop(),n.catch(()=>{})),n}}}async function Jf(e,t){let n=t.processIndexRequests(),i=t.processSemanticRequests(),o=n+i,r=o>0?0:e+1;if(t.afterMailboxPoll({indexRequests:n,semanticRequests:i,processedRequests:o}),t.shouldStop())return{indexRequests:n,semanticRequests:i,processedRequests:o,consecutiveIdlePolls:r,stopped:!0};let s=Kf(o,r);return await t.wait(s),{indexRequests:n,semanticRequests:i,processedRequests:o,consecutiveIdlePolls:r,stopped:!1,delayMs:s}}function Yf(e){return e==="fresh"?null:{kind:"watch-startup",detail:`index ${e} when watch service started`}}function Xf(e){bc(e.statePath,{version:1,protocolVersion:wr,pid:we.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{},projectRoot:e.projectRoot,...e.worktreeId?{worktreeId:e.worktreeId}:{},cliVersion:e.cliVersion,startedAt:new Date(e.startedAtMs).toISOString(),heartbeatAt:new Date(e.nowMs).toISOString(),lastActivityAt:new Date(e.lastActivityAtMs).toISOString(),...e.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(e.lastActivityAtMs+e.idleTimeoutMs).toISOString()},watcher:e.watcherStatus,...e.watcherStatus.state==="idle"&&e.indexGeneration?{indexGeneration:e.indexGeneration}:{},...e.lastRefresh?{lastRefresh:e.lastRefresh}:{},...e.lastError?{lastError:e.lastError}:{},reindexActivity:e.reindexActivity,refreshRequests:e.refreshCoordinator.status(),typescriptSemantic:{...e.semanticLane.status(),...e.semanticBusyUntilMs===void 0?{}:{busyUntil:new Date(e.semanticBusyUntilMs).toISOString()}},typescriptIndex:{...e.indexLane.status(),...e.indexBusyUntilMs===void 0?{}:{busyUntil:new Date(e.indexBusyUntilMs).toISOString()}}},{durability:e.durability})}function Zf(e){let t=0,n=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;return({processedRequests:s})=>{let a=ke();if(a-i>=Gf&&(i=a,!il(e.worktreeLiveness))){e.requestStop();return}if(a-r>=Vf&&(r=a,Ti(e.indexMailboxPaths),Ti(e.semanticMailboxPaths)),a-o>=Rc&&(o=a,xc(e.projectRoot,e.cliVersion)),a-n>=Bf){n=a;let c=vc(e.activityPath);c&&e.updateObservedActivity(c.atMs,a),c?.refreshRequestedAtMs!==void 0&&c.refreshRequestedAtMs>t&&(t=c.refreshRequestedAtMs,e.refreshCoordinator.observeLegacyRequest(c.refreshRequestedAtMs,c.refreshDetail??"stale index observed by a legacy command"))}e.refreshCoordinator.poll(e.watcherStatus(),c=>{e.recordActivity(),e.requestRefresh(c)}),s>0&&(e.recordActivity(),e.persistState(!0,"visibility")),e.persistState()}}async function eg(e){let t,n=0,i=!1,o,r;we.once("SIGINT",e.stopSignal),we.once("SIGTERM",e.stopSignal);try{e.watcher.start();let a=e.initializeFreshness();for(e.recordActivity(),e.markReady(),e.persistState(!0),t=setInterval(()=>e.persistState(),Il),t.unref?.(),a&&e.requestRefresh(a);!e.stopRequested();){let c=await Jf(n,{processIndexRequests:e.processIndexRequests,processSemanticRequests:e.processSemanticRequests,afterMailboxPoll:e.afterMailboxPoll,shouldStop:e.shouldStop,wait:e.wait});if(n=c.consecutiveIdlePolls,c.stopped)break}}catch(a){i=!0,o=a}finally{we.off("SIGINT",e.stopSignal),we.off("SIGTERM",e.stopSignal),t!==void 0&&clearInterval(t);let a=e.shutdown.begin();await e.closeLanes();let c=await a;c.state==="stopped"?e.finalizeStopped():r=e.finalizeDegraded(c.reasons)}let s=e.mailboxFatalError();if(!i&&s&&(i=!0,o=s),i&&r)throw new AggregateError([o,r],"Watch service execution and shutdown both failed.");if(i)throw o;if(r)throw r}function tg(e){let t=xl({paths:e.semanticPaths,projectRoot:e.projectRoot,onBusy:e.onSemanticBusy,onFatal:e.onFatal}),n=e.config.indexer?.typescript,i=Rl({paths:e.indexPaths,projectRoot:e.projectRoot,dbPath:e.dbPath,...n?.maxWarmSessions===void 0?{}:{maxActiveSessions:n.maxWarmSessions},...n?.workerIdleMs===void 0?{}:{workerIdleMs:n.workerIdleMs},...n?.workerSoftMemoryMb===void 0?{}:{workerSoftMemoryMb:n.workerSoftMemoryMb},...n?.workerHeapMb===void 0?{}:{workerHeapMb:n.workerHeapMb},onBusy:e.onIndexBusy,onFatal:e.onFatal});return{semanticLane:t,indexLane:i}}async function to(e,t,n={}){let i=yc(e,t),o=i.projectRoot,r=i.worktreeKind==="git"?ng(o,i.worktreeId):void 0,s=nl(o,r),a=Ee(o);a.watch={...a.watch,...n};let c=Ke(a);if(!c.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let l=Ue(o,a),d=En(l.cacheDir),m=He(we.pid),h=Sc(d.lockPath,o,{readProcessIdentity:q=>q===we.pid?m:He(q)});if(!h.acquired)return;let p=new Hn(d.refreshRequestsPath,{retryDelayMs:Math.max(1e3,c.cooldownMs)});p.initializeAfterOwnershipAcquired();let f=Date.now(),g=ke(),y=f,v=g,$={state:"idle"},L,_,I,T,W=Mn(l.dbPath),E=!1,B=!1,J=Number.NEGATIVE_INFINITY,F,Y,pt=xr(l.cacheDir),et=rc(l.cacheDir);Ci(pt),Ci(et);let fn=el([et.pendingDir,et.legacyRequestDir,pt.pendingDir,pt.legacyRequestDir,d.refreshRequestsPath]),Re=(q=!1,nt=q?"durable":"visibility")=>{if(!B)return;let he=Date.now(),ne=ke();!q&&ne-J<Il||(J=ne,Xf({statePath:d.statePath,durability:nt,processIdentity:m,projectRoot:o,worktreeId:i.worktreeId,cliVersion:t,startedAtMs:f,nowMs:he,lastActivityAtMs:y,idleTimeoutMs:c.idleTimeoutMs,watcherStatus:$,indexGeneration:L,lastRefresh:_,lastError:I,reindexActivity:W,refreshCoordinator:p,semanticLane:mt,indexLane:Et,semanticBusyUntilMs:F,indexBusyUntilMs:Y}))},tt=()=>{y=Date.now(),v=ke()},Ge=q=>{tt(),T??=q,I={at:new Date().toISOString(),message:q.message},Re(!0,"visibility")},{semanticLane:mt,indexLane:Et}=tg({semanticPaths:pt,indexPaths:et,projectRoot:o,dbPath:l.dbPath,config:a,onSemanticBusy(q){F=q===void 0?void 0:q+5e3,Re(!0,"visibility")},onIndexBusy(q){Y=q===void 0?void 0:q+5e3,Re(!0,"visibility")},onFatal:Ge}),ye=new Un({projectRoot:o,config:{...a,watch:c},outputDb:l.dbPath,languages:a.languages,onStatus(q){$=q,q.state!=="idle"&&(L=void 0),q.state!=="idle"&&tt(),Re(!0)},onReindexComplete(q,nt,he){tt();let ne=he?.pendingChanges!==!1?Te(o,a,l):ha(l);return _=ne.lastRefresh,L=ne.state==="fresh"?Qe(l.dbPath)??void 0:void 0,W=Mn(l.dbPath),p.completeActive(),I=void 0,Re(!0),ne.state==="fresh"},onReindexError(){p.failActive()},onRefreshSuppressed(q){let nt=ic(l.dbPath,q);nt.state==="failed"&&(I={at:new Date().toISOString(),message:`Suppressed-refresh telemetry was not recorded: ${nt.reason}`},Re(!0,"visibility")),W=Mn(l.dbPath)},onError(q){tt(),L=void 0,I={at:new Date().toISOString(),message:q.message},Re(!0)}}),Wt=zf(ye,{requestStop(){E=!0},closeWake(){fn.close()}}),xe=()=>{Wt.begin()},Ne=Zf({worktreeLiveness:s,indexMailboxPaths:et,semanticMailboxPaths:pt,projectRoot:o,cliVersion:t,activityPath:d.activityPath,refreshCoordinator:p,watcherStatus:()=>$,requestRefresh:q=>ye.requestRefresh({kind:"watch-demand",detail:q},{immediate:!0}),requestStop:()=>{E=!0},recordActivity:tt,updateObservedActivity(q,nt){q<=y||(y=q,v=nt)},persistState:Re});await eg({watcher:ye,shutdown:Wt,stopSignal:xe,initializeFreshness(){let q=Te(o,a,l);return _=q.lastRefresh,L=q.state==="fresh"?Qe(l.dbPath)??void 0:void 0,Yf(q.state)},markReady:()=>{B=!0},recordActivity:tt,persistState:Re,requestRefresh:q=>ye.requestRefresh(q,{immediate:!0}),stopRequested:()=>E,processIndexRequests:()=>Et.poll(),processSemanticRequests:()=>mt.poll(),afterMailboxPoll:Ne,shouldStop:()=>E||T!==void 0||$c({watcher:$,lastActivityAtMs:v,nowMs:ke(),idleTimeoutMs:c.idleTimeoutMs}),wait:q=>fn.wait(q),closeLanes:()=>Promise.all([mt.close("TypeScript semantic service stopped before completing the request."),Et.close("TypeScript index service stopped before completing the request.")]).then(()=>{}),mailboxFatalError:()=>T,finalizeStopped(){Tl(d.statePath,{force:!0}),Tl(d.activityPath,{force:!0}),h.release()},finalizeDegraded(q){return I={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${q.join("; ")}`},Re(!0),new Error(I.message)}})}function ng(e,t){let n=Ho(e);if(n.kind!=="worktree"||n.identity.worktreeId!==t)throw new Error(`Git worktree identity changed while starting the watch service for ${e}.`);return n.identity.gitDir}function ig(e,t={report:n=>console.error(n),exit:n=>we.exit(n)}){return t.report(`watch-service: ${Ta(e instanceof Error?e.message:String(e))}`),t.exit(1)}var og=we.argv[1]?_f(Wf(we.argv[1])).href:null;if(og===import.meta.url){let e=we.argv[2],t=we.argv[3],n=rg(we.argv[4]);if(!e||!t)console.error("watch-service: expected <project-root> <cli-version>"),we.exitCode=1;else try{await to(e,t,n)}catch(i){ig(i)}}function rg(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}import{execFileSync as sg}from"child_process";import{existsSync as zn,lstatSync as ag,realpathSync as Pl}from"fs";import{dirname as cg,join as yt}from"path";var Al=["- `scip-query search <exact-text>` \u2014 Where does this exact text occur in current project text, and which aligned compiler symbol owns each line? Requires: One exact text literal or deliberately bounded regular expression; insert `--` before a literal that starts with a dash.","- `scip-query outline <file>` \u2014 What symbols and nesting exist in this file? Requires: One exact current project file path.","- `scip-query entrypoints [text]` \u2014 Which detected external roots or entry-surface candidates match this text? Requires: Optional exact text to filter candidates; otherwise the current indexed repository.","- `scip-query evidence` \u2014 Which exact execution, runtime, data, state, temporal, contract, identity, ownership, or dependency relationships surround these referents? Which related source must be read only when graph evidence leaves a named implementation gap? Requires: One or more exact symbol, file:line, or literal roots plus explicit family, direction, depth, and output bound.","- `scip-query inspect` \u2014 Which related source units across several known text, symbol, or location anchors should be read together? Requires: One or more exact text, symbol, or file:line selectors naming the unresolved behavior.","- `scip-query code <selectors...>` \u2014 What exact source defines these symbols, ranges, or file surfaces? Requires: One or more exact symbols, file:line ranges, or file paths.","- Choose graph controls explicitly: `execution incoming` \u2014 Who can call or reach this?; `execution outgoing` \u2014 What can this call or reach?; `dataflow incoming` \u2014 Where can this value come from?; `dataflow outgoing` \u2014 Where can this value go?; `runtime both` \u2014 Which producer and consumer rendezvous?; `state both` \u2014 What resource is observed or changed?; `temporal both` \u2014 What occurs before or after this?; `contract both` \u2014 What interface constrains this?; `identity both` \u2014 Are these observations the same entity?; `ownership both` \u2014 What contains or owns this?; `dependencies outgoing` \u2014 What does this statically rely on?. The CLI does not infer them from English intent.","- Calibration: exact is directly observed; derived is deterministically computed; candidate needs confirmation; mixed discloses its constituents; unknown cannot support a stronger claim. Read coverage and recovery before making absence claims.","- The controls above are complete for ordinary exploration. Run `scip-query capabilities --matrix` only when a named claim depends on uncertain provider support; do not run it for routine orientation."],Kn=[{stage:"locate",id:"search",command:"search <exact-text>",question:"Where does this exact text occur in current project text, and which aligned compiler symbol owns each line?",requiredInput:"One exact text literal or deliberately bounded regular expression; insert `--` before a literal that starts with a dash.",returnedFact:"exact cardinality, bounded identities and source, and scope commands that recover withheld matches",evidenceCeiling:"Exact current-text cardinality and locations within reported text coverage; compiler ownership only where aligned.",nonClaim:"Structural source ranking orders exact matches but does not establish task relevance. A literal co-occurrence does not establish a graph relationship.",outputCost:"small",contrasts:["outline: search locates exact text across files; outline enumerates compiler-owned constructs in one known file."],gapClosingCommands:["evidence","inspect","code"]},{stage:"locate",id:"outline",command:"outline <file>",question:"What symbols and nesting exist in this file?",requiredInput:"One exact current project file path.",returnedFact:"symbol names, nesting, and line ranges",evidenceCeiling:"Exact compiler-owned constructs and ranges when the file is indexed; no invented semantic overlay.",nonClaim:"File ownership and nesting do not establish execution or task relevance.",outputCost:"small",contrasts:["search: outline enumerates constructs in one known file; search locates exact text across current project text.","code: outline returns identities and ranges; code materializes exact source for selected identities."],gapClosingCommands:["evidence","inspect","code"]},{stage:"locate",id:"entrypoints",command:"entrypoints [text]",question:"Which detected external roots or entry-surface candidates match this text?",requiredInput:"Optional exact text to filter candidates; otherwise the current indexed repository.",returnedFact:"entry symbols with files, confidence, evidence, and indexed caller counts",evidenceCeiling:"Source/compiler-grounded entry evidence and indexed caller counts; exported-only candidates remain candidates.",nonClaim:"A package-public export or zero indexed callers is an entry candidate, not proof of runtime ingress. Entry classification does not establish that the callable executes.",outputCost:"bounded",contrasts:["entry-map: entrypoints locates possible external roots; entry-map traverses static calls from one selected root.","search: entrypoints classifies callable roots; search only locates exact text and ownership."],gapClosingCommands:["evidence","inspect","code"]},{stage:"project",id:"evidence",command:"evidence",question:"Which exact execution, runtime, data, state, temporal, contract, identity, ownership, or dependency relationships surround these referents? Which related source must be read only when graph evidence leaves a named implementation gap?",requiredInput:"One or more exact symbol, file:line, or literal roots plus explicit family, direction, depth, and output bound.",returnedFact:"batched exact selectors and typed graph relationships; compact endpoints with exact locations and follow-up commands; coverage and recoverable omissions; exact source-recovery command when source was requested with a graph projection; explicit ambiguity failure with exact rerun commands",evidenceCeiling:"Typed edges only to each registered provider ceiling within the explicitly selected projection and reported coverage.",nonClaim:"The projection does not infer which relationships are relevant to the user task. Reference, dependency, data, state, temporal, contract, and identity edges do not become execution claims.",outputCost:"bounded",contrasts:["refs: refs enumerates direct reference sites; evidence traverses explicitly selected typed relationships.","call-graph: call-graph specializes in static calls; evidence can combine execution with other selected families.","value-flow: value-flow specializes in proved transfers; evidence projects bounded dataflow alongside other families.","dependence-slice: dependence-slice computes a program-dependence slice; evidence performs bounded graph projection."],gapClosingCommands:["inspect","code"]},{stage:"read",id:"inspect",command:"inspect",question:"Which related source units across several known text, symbol, or location anchors should be read together?",requiredInput:"One or more exact text, symbol, or file:line selectors naming the unresolved behavior.",returnedFact:"one ranked, deduplicated semantic packet plus exact selector cardinality and explicit expansion coverage",evidenceCeiling:"Complete current source for every materialized syntax unit; bounded selector and packet coverage remain explicit.",nonClaim:"A source packet does not choose which implementation details are relevant to the user task. A reference mention does not establish executable reachability.",outputCost:"potentially-large",contrasts:["code: inspect batches bounded behavior or source gaps; code materializes complete exact source.","evidence: inspect reads implementation units; evidence projects typed relationships without source."],gapClosingCommands:[]},{stage:"read",id:"code",command:"code <selectors...>",question:"What exact source defines these symbols, ranges, or file surfaces?",requiredInput:"One or more exact symbols, file:line ranges, or file paths.",returnedFact:"per-selector resolution, complete definition source, exact ranges with statically attributed same-file call closure, file export surfaces, omitted-local ledgers, and line ranges",evidenceCeiling:"Exact current source bytes for every resolved selector, with omitted file-local constructs disclosed.",nonClaim:"Source materialization does not establish callers, runtime reachability, or task relevance by itself.",outputCost:"potentially-large",contrasts:["inspect: code materializes complete exact source; inspect batches bounded behavior or source gaps.","outline: code reads selected implementations; outline enumerates file structure without reading every body."],gapClosingCommands:[]}];var ct="<!-- scip-query:agent-setup:begin -->",Nt="<!-- scip-query:agent-setup:end -->",lg="# scip-query:agent-setup",no=[".codex/hooks.json",".claude/settings.local.json"],Ll="# scip-query:local-agent-hooks:begin",jl="# scip-query:local-agent-hooks:end",ql="hook-architecture-stop";function Fl(e){let t=e.written.length+e.unchanged.length,n=e.skipped.length;return{verdict:n===0?"ready":t===0?"blocked":"partial",ready:t,skipped:n}}function Jn(e,t={}){let n={written:[],unchanged:[],skipped:[]};return dg(e,n),t.architectureHook!==!1&&mg(e,n,t.architectureHook),n}function Wl(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Ml(e,"AGENTS.md",t,n),_l(e,"CLAUDE.md")?n.unchanged.push("CLAUDE.md"):Ml(e,"CLAUDE.md",t,n),hg(e,t,n),pg(e,t,n),n}function dg(e,t){let n=[ct,"## scip-query","","This repository uses scip-query as its primary code exploration surface.","","Native text and file tools show matching lines or file slices. scip-query is an indexed code-exploration surface that additionally resolves exact compiler-owned identities and typed execution, data, runtime, state, temporal, contract, identity, ownership, and dependency relationships. The agent chooses the repository question and relevant controls; the CLI returns observations without guessing task relevance.","","- Use scip-query for tracked repository text, including literal search and exact source reads. Native tools are for applying edits, running checks, binary content, or a specific unsupported gap reported by scip-query\u2014not a parallel exploration workflow.",...Al,"- Treat commands as controls, not a checklist. Use every capability needed by the task, but make each query answer a distinct repository question. There is no mandatory command sequence or query-count limit. Thoroughness means understanding the relevant system end to end, not exhausting the repository.","- Use a discriminating exact `search`, `outline`, or `entrypoints` locator, then reuse every returned symbol or `file:line` as a graph root. Do not repeat generic synonym searches after usable candidates exist. There is no required anchor-discovery phase, and locator ordering does not establish relevance.","- When several implementations match the same vocabulary, do not select one by path, naming, apparent recency, or result order. Compare their entry surfaces, incoming execution, ownership, callers, or runtime connections; if the repository does not establish one as authoritative, explain the alternatives and their scopes.","- `evidence` requires one or more repeated `--symbol`, `--at`, or `--search` roots, one or more repeated `--edge <family>` flags, `--direction incoming|outgoing|both`, `--depth <n>`, and `--max-edges <n>`. Use `--subtype <subtype>` to narrow a family, `--connecting` when the roots themselves must be connected, and `--inventory-only` when counts are enough to choose the next projection.","- Treat execution and exact runtime handoffs as executable reachability. Other families describe what data moves, state changes, ordering occurs, contracts constrain, identities coincide, owners contain, or static dependencies require; they do not become call claims.","- Read request, observed facts, evidence calibration, coverage, and recovery together. Exact observations are facts within their reported coverage; derived observations are deterministic computations; candidate observations require confirmation. Missing or bounded output is not evidence of absence.","- An emitted `Continue exactly:` command is a cursor: a next-page read from one immutable rendered result. It is required transport, not optional evidence expansion. Run the emitted command unchanged and repeat until no continuation remains before interpreting that command's complete result. Do not rerun the original query or alter cursor flags. Continuation reads saved output without repository preparation, reindexing, or watcher startup. Printed recovery and expansion commands are different: run those only when their omitted evidence matters.","- Batch independent roots and source gaps when practical. `inspect --view behavior` returns connected behavior for named units; `code` returns exact source. Do not reread source already rendered by either command.","- After edits, use `scip-query diff-impact` when downstream consumers matter, `scip-query architecture` for declared boundaries, and `scip-query health --full` for configured quality or cleanup detectors.","- Prefer human output for agent reading. If a model-facing consumer genuinely needs JSON, add `--json --agent-output`; add `--result-only` only when the common envelope is unnecessary, and drain every emitted cursor before interpreting the result. Never send raw `--json` output through a model-facing terminal or tool. When a program needs the exhaustive machine payload, use `--json --json-output <path>` and inspect that file programmatically instead of injecting its complete contents into model context.","- Commit relevant `.scipquery/suppressions/*.json` records with the change. Do not commit local agent-tool settings.",Nt].join(`
13
- `);if(Nl(e,"AGENTS.md",n,t),_l(e,"CLAUDE.md")){t.unchanged.push("CLAUDE.md");return}let i=[ct,"@AGENTS.md",Nt].join(`
14
- `);Nl(e,"CLAUDE.md",i,t,o=>o.includes("@AGENTS.md")&&!o.includes(ct))}function _l(e,t){let n=yt(e,t);try{return ag(n).isSymbolicLink()?Pl(n)===Pl(yt(e,"AGENTS.md")):!1}catch{return!1}}function Nl(e,t,n,i,o){let r=yt(e,t),s=!1,a=io(r,t,i,c=>{if(o?.(c.text))return s=!0,{kind:"unchanged"};let l=ug(c.text,n);return l===c.text?{kind:"unchanged"}:{kind:"write",text:l,...c.revision.exists?{}:{mode:420}}});a&&(!a.changed||s?i.unchanged.push(t):i.written.push(t))}function Ml(e,t,n,i){let o=yt(e,t);if(n.dryRun){if(!zn(o)){i.unchanged.push(t);return}try{let s=ae(o,"agent instruction file");s.includes(ct)?(Ol(s),i.removed.push(t)):i.unchanged.push(t)}catch(s){i.skipped.push({target:t,reason:s instanceof Error?s.message:String(s)})}return}let r=io(o,t,i,s=>{if(!s.revision.exists||!s.text.includes(ct))return{kind:"unchanged"};let a=Ol(s.text);return a.length===0?{kind:"delete"}:{kind:"write",text:a}});r&&(r.changed?i.removed.push(t):i.unchanged.push(t))}function ug(e,t){if(Bl(e)==="present"){let i=new RegExp(`${ct}[\\s\\S]*?${Nt}`);return e.replace(i,t)}return e.length>0?`${e.replace(/\n*$/,`
15
-
16
- `)}${t}
17
- `:`${t}
18
- `}function Ol(e){Bl(e);let t=new RegExp(`${ct}[\\s\\S]*?${Nt}`),n=e.replace(t,"").replace(/\n{3,}/g,`
19
-
20
- `).trim();return n.length===0?"":`${n}
21
- `}function Bl(e){let t=e.split(ct).length-1,n=e.split(Nt).length-1;if(t===0&&n===0)return"absent";if(t===1&&n===1&&e.indexOf(ct)<e.indexOf(Nt))return"present";throw new Error("managed scip-query markers are incomplete, duplicated, or out of order")}function io(e,t,n,i){try{return It(e,i,{maxRetries:0})}catch(o){n.skipped.push({target:t,reason:o instanceof Error?o.message:String(o)});return}}function pg(e,t,n){let i=".git/hooks/pre-commit",o=yt(e,i);if(!zn(o)){n.unchanged.push(i);return}if(!ae(o,"pre-commit hook").includes(lg)){n.skipped.push({target:i,reason:"pre-commit hook is not managed by scip-query"});return}if(t.dryRun){n.removed.push(i);return}io(o,i,n,()=>({kind:"delete"}))?.changed&&n.removed.push(i)}function mg(e,t,n={}){let i=(n.inspectReadiness??fg)(e);if(i.state==="not-configured")return;if(i.state==="blocked"){t.skipped.push({target:"architecture Stop hook",reason:i.reason});return}let o=n.commandPrefix??"scip-query";for(let r of no){if(Ql(e,r)){t.skipped.push({target:r,reason:"tracked repository config; the checkout-local hook installer will not modify it"});continue}Ul(yt(e,r),r,t,s=>gg(s,o))}vg(e,t)}function hg(e,t={},n){for(let i of no){let o=yt(e,i);if(zn(o)){if(Ql(e,i)){n.skipped.push({target:i,reason:"tracked repository config; the checkout-local hook remover will not modify it"});continue}if(t.dryRun){try{let r=bg(o);JSON.stringify(Dl(r))!==JSON.stringify(r)&&n.removed.push(i)}catch(r){n.skipped.push({target:i,reason:Yn(r)})}continue}Ul(o,i,n,Dl,!0)}}}function fg(e){let t=Ee(e);if(!t.architecture||t.architecture.boundaries.length===0)return{state:"not-configured"};let n=Ue(e,t),i=Te(e,t,n);if(i.state!=="fresh")return{state:"blocked",reason:`the index is ${i.state}; refresh it before installing a persistent architecture grader`};let o;try{o=Ra(e);let r=$t(Tt(o));return r.length>0?{state:"blocked",reason:`the current architecture baseline has ${r.length} enforced violation(s); make the declared policy clean before installing the Stop hook`}:{state:"ready"}}catch(r){return{state:"blocked",reason:Yn(r)}}finally{o?.close()}}function gg(e,t="scip-query"){let n=Gl(e.hooks),i=Array.isArray(n.Stop)?n.Stop:[];return{...e,hooks:{...n,Stop:[...Vl(i),{hooks:[{type:"command",command:`${t} ${ql}`,timeout:120,statusMessage:"Checking architecture boundaries"}]}]}}}function Dl(e){let t=Gl(e.hooks),n=Array.isArray(t.Stop)?t.Stop:[],i=Vl(n),o={...t};i.length>0?o.Stop=i:delete o.Stop;let r={...e};return Object.keys(o).length>0?r.hooks=o:delete r.hooks,r}function Gl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Vl(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!yg(n)):[]})).filter(t=>t.hooks.length>0)}function yg(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&new RegExp(`(?:^|\\s)${ql}$`,"u").test(t)}function Ul(e,t,n,i,o=!1){try{It(e,s=>{let a=s.revision.exists?Hl(s.text,e):{},c=i(a);return JSON.stringify(c)===JSON.stringify(a)?{kind:"unchanged"}:o&&Object.keys(c).length===0?{kind:"delete"}:{kind:"write",text:`${JSON.stringify(c,null,2)}
22
- `,mode:384}}).changed?"written"in n?n.written.push(t):n.removed.push(t):o||n.unchanged.push(t)}catch(r){n.skipped.push({target:t,reason:Yn(r)})}}function bg(e){return Hl(ae(e,"agent hook settings"),e)}function Hl(e,t){let n=JSON.parse(e);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Cannot update ${t}: the hook config is not a JSON object.`);return n}function Ql(e,t){try{return sg("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore",timeout:5e3,killSignal:"SIGKILL"}),!0}catch{return!1}}function vg(e,t){let n=yt(e,".git","info","exclude");if(!zn(cg(n))){t.skipped.push({target:".git/info/exclude",reason:"Git metadata was not found; local hook files may appear as untracked"});return}try{It(n,i=>{let o=new RegExp(`${Ll}[\\s\\S]*?${jl}\\n?`,"gu"),r=i.text.replace(o,"").replace(/\n*$/u,""),s=[Ll,...no.map(c=>`/${c}`),jl].join(`
23
- `),a=`${r}${r?`
24
-
25
- `:""}${s}
26
- `;return a===i.text?{kind:"unchanged"}:{kind:"write",text:a,mode:420}})}catch(i){t.skipped.push({target:".git/info/exclude",reason:Yn(i)})}}function Yn(e){return e instanceof Error?e.message:String(e)}import{existsSync as Bg}from"fs";import{randomUUID as Gg}from"crypto";import{existsSync as ro,mkdirSync as zl,rmSync as Sg}from"fs";import{homedir as wg}from"os";import{dirname as Jl,isAbsolute as $g,join as Xn,relative as Kl,resolve as Rg}from"path";function Yl(e,t){return t?Rg(e,t):Xn(e,"docs","scip-query")}function Xl(e,t,n={}){let i=Xn(Yl(e,n.dossierDir),"health-dossier.attempt.json"),o=xg(i);zl(Jl(i),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
27
- `;return ro(i)?wi(i,r,{durability:"durable"}):$i(i,r,{durability:"durable"}),{attemptPath:i,attempt:t,interrupted:o}}function Zl(e){Sg(e.attemptPath,{force:!0})}function xg(e){if(!ro(e))return null;try{let t=JSON.parse(ae(e,"health dossier attempt"));return typeof t.runId!="string"||typeof t.startedAt!="string"?null:{runId:t.runId,startedAt:t.startedAt,indexGeneration:typeof t.indexGeneration=="string"?t.indexGeneration:null,...typeof t.completedAt=="string"?{completedAt:t.completedAt}:{}}}catch{return null}}function ed(e,t={}){let n=Yl(e.projectRoot,t.dossierDir),i={markdownPath:Xn(n,"health-dossier.md"),jsonPath:Xn(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},o=jg({...e,generatedAt:new Date().toISOString(),healthDossier:i},e.projectRoot);try{return Ag(i.markdownPath,Cg(o),i),Pg(i.jsonPath,o,i),i}catch(r){return{...i,status:"failed",error:r instanceof Error?r.message:String(r)}}}function Cg(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${so(e.health)}`,`Index generation: ${e.indexGeneration??"unavailable"}`,...e.attempt?[`Audit attempt: ${e.attempt.runId} started ${e.attempt.startedAt}, completed ${e.attempt.completedAt??"not recorded"}`]:[],"","## Items That Need Attention","",...kg(e),"","## Blocked Or Unavailable Checks","",...Eg(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","",...Tg(e),"","## JSON","",`Machine-readable report: \`${Ig(e)}\``,""].join(`
28
- `)}`}function kg(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 Eg(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 Tg(e){return e.indexerRemediation.length===0?["All detected indexers were already runnable."]:e.indexerRemediation.map(t=>{let n=t.after.runnable?"READY":"BLOCKED",i=t.attempted?"install attempted":"no automatic install attempted";return`- ${n} ${t.language}: ${t.binaryLabel} (${i})`})}function so(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function Ig(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Ag(e,t,n){td(e,t,n,"health dossier Markdown",i=>i===t)}function Pg(e,t,n){let i=`${JSON.stringify(t,null,2)}
29
- `;td(e,i,n,"health dossier JSON",o=>Lg(o,i))}function td(e,t,n,i,o){zl(Jl(e),{recursive:!0});let r=ro(e)?ae(e,i):null;if(r!==null&&o(r)){n.unchanged.push(e);return}r===null?$i(e,t,{durability:"durable"}):wi(e,t,{durability:"durable"}),n.written.push(e)}function Lg(e,t){try{let n=JSON.parse(e),i=JSON.parse(t);return delete n.generatedAt,delete i.generatedAt,delete n.attempt,delete i.attempt,JSON.stringify(n)===JSON.stringify(i)}catch{return e===t}}function jg(e,t){return oo(e,t)}function oo(e,t){return typeof e=="string"?Ng(e,t):Array.isArray(e)?e.map(n=>oo(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,i])=>[n,oo(i,t)])):e}function Ng(e,t){if(e===t)return".";if(!$g(e))return e;let n=Kl(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let i=Kl(wg(),e).replace(/\\/g,"/");return i&&!i.startsWith("..")?`~/${i}`:e}return n}import{spawnSync as Mg}from"child_process";import{dirname as nd,join as Og,resolve as Dg}from"path";import{fileURLToPath as qg}from"url";var sn={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 Fg(e,t){let n=new Set(["tree-sitter"]);for(let i of e)for(let o of sn[i]?.packages??[])n.add(o);return[...n].filter(i=>t[i]).sort().map(i=>`${i}@${t[i]}`)}function Zn(e){return[...new Set(e.filter(t=>sn[t]!==void 0))].sort()}function id(e,t=rd){let n=Zn(e),i=n.filter(o=>t.probe(sn[o].ast));return{supportedLanguages:n,available:i,missing:n.filter(o=>!i.includes(o))}}function od(e,t={}){let n=t.runtime??rd,i=t.packageRoot??Wg(),o=Zn(e),r=o.filter(m=>n.probe(sn[m].ast)),s=o.filter(m=>!r.includes(m));if(s.length===0)return{supportedLanguages:o,availableBefore:r,installed:[],availableAfter:r,unavailable:[],attempted:!1};let a=_g(i),c=Fg(s,a),l=n.install(i,c);l.ok&&n.resetProbe();let d=o.filter(m=>n.probe(sn[m].ast));return{supportedLanguages:o,availableBefore:r,installed:l.ok?c:[],availableAfter:d,unavailable:o.filter(m=>!d.includes(m)),attempted:!0,...l.error?{error:l.error}:{}}}function Wg(){let e=nd(qg(import.meta.url));for(;;){let t=Og(e,"package.json");try{if(JSON.parse(ae(t,"AST parser package manifest")).name==="scip-query")return e}catch{}let n=nd(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function _g(e){return JSON.parse(ae(Dg(e,"package.json"),"AST parser package manifest")).optionalDependencies??{}}var rd={probe:e=>vn(e)==="ast",resetProbe:ir,install:(e,t)=>{let n=Mg(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 sd(e){if(e.guided){if(e.yes)throw new Error("--guided cannot be combined with --yes; choose interactive or automatic setup.");if(e.json)throw new Error("--guided cannot be combined with --json; the interactive checklist emits human output.");if(!e.stdinIsTty||!e.stdoutIsTty)throw new Error("--guided requires an interactive terminal; use --yes for non-interactive setup.")}}function ad(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"});let n=e.readiness.indexers.filter(i=>!i.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 cd(e={}){let t=[],n=qe(),{projectRoot:i,paths:o,dbPath:r}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,c=Rt(n.config,{projectRoot:i}).filter(M=>M.level==="error"),l=null,d=null;if(c.length===0&&!n.config.collaborationDomainId)try{l=la(i,n.config)}catch(M){d=Mt(M)}let m=l?.config??n.config,h=e.languages?da(i,m,e.languages):null,p=h?.config??m,f=Rt(p,{projectRoot:i}),g=f.filter(M=>M.level==="error"),y=null,v=null;if(g.length===0&&p.watch?.enabled!==s)try{y=ua(i,p,s)}catch(M){v=Mt(M)}let $=y?.config??p,L=en();G(t,{id:"collaboration-domain-config",label:"Collaboration domain",status:d!==null?"failed":c.length>0?"skipped":"ok",message:d??(c.length>0?"Skipped because the existing project config has validation errors.":l?.changed?"Generated the committed identity shared by merge-intended branches, clones, and forks.":"The committed collaboration-domain identity is already present."),...l?{details:[l.configPath]}:{}}),G(t,{id:"automatic-indexing-config",label:"Automatic indexing config",status:v!==null?"failed":g.length>0||!s?"skipped":"ok",message:v??(g.length>0?"Skipped because the existing project config has validation errors.":s?y?.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."),...y?{details:[y.configPath]}:{}});let _=jn();G(t,{id:"scip-cli",label:"scip CLI",status:L||!_?"ok":"warn",message:L?"scip CLI is available.":_?e.installIndexers===!0?"scip CLI is not installed; the reviewed release will be installed during the index refresh.":"scip CLI is required by SCIP_QUERY_SQLITE_CONVERTER=scip-cli but not installed; pass --install-missing to install the reviewed release.":"scip CLI is not installed and not required: SCIP is converted to SQLite in-process (SCIP_QUERY_SQLITE_CONVERTER=scip-cli selects the external converter)."});let I=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:_n({quiet:!0});G(t,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":I.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${I.installed.length} installed, ${I.alreadyLinked.length} already linked, ${I.pruned.length} pruned, ${I.skipped.length} skipped.`,details:[...I.pruned.map(M=>`Pruned ${M}`),...I.skipped.map(M=>`Skipped ${M}`)]});let T=y?Rt($,{projectRoot:i}):f,W=T.filter(M=>M.level==="error");G(t,{id:"config",label:"Project config",status:W.length>0?"failed":T.length>0?"warn":"ok",message:T.length===0?"Config OK.":`${T.length} diagnostic(s), ${W.length} error(s).`,details:T.map(M=>`${M.level.toUpperCase()} ${M.path}: ${M.message}`)});let E=Xe(i,$);G(t,{id:"readiness",label:"Indexer readiness",status:E.languages.length===0?"failed":E.indexers.some(M=>!M.runnable)?"warn":"ok",message:E.languages.length===0?"No supported project languages detected.":`Detected languages: ${E.languages.join(", ")}`,details:E.indexers.map(M=>`${M.runnable?"OK":M.installed?"WARN":"MISSING"} ${M.language}: ${M.binaryLabel}${M.note?` - ${M.note}`:""}`)});let B;if(e.installAstParsers===!0)B=od(E.languages),G(t,{id:"ast-parsers",label:"AST parser packages",status:B.unavailable.length>0?"warn":"ok",message:B.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${B.availableAfter.length}/${B.supportedLanguages.length} selected language parser(s) available${B.installed.length>0?`; installed ${B.installed.join(", ")}`:""}.`,details:[...B.unavailable.length>0?[`Unavailable: ${B.unavailable.join(", ")}`]:[],...B.error?[B.error]:[]]});else{let M=id(E.languages);B={supportedLanguages:M.supportedLanguages,availableBefore:M.available,installed:[],availableAfter:M.available,unavailable:M.missing,attempted:!1},G(t,{id:"ast-parsers",label:"AST parser packages",status:M.missing.length===0?"ok":"skipped",message:M.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":M.missing.length===0?`${M.available.length}/${M.supportedLanguages.length} selected language parser(s) available; nothing to install.`:"Skipped because installing missing parser packages requires explicit consent.",details:M.missing.length>0?[`Missing: ${M.missing.join(", ")}`]:[]})}let J=e.installIndexers===!0,F=J?ny(i,E,t):[];if(!J){let M=E.indexers.filter(_t=>!_t.runnable);G(t,M.length===0?{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"Nothing to install: every detected language has a runnable indexer."}:{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because installing missing indexers requires explicit consent.",details:M.map(_t=>`Missing ${_t.language}: ${_t.binaryLabel}`)})}let Y=Xe(i,$),pt=await Vg({projectRoot:i,paths:o,config:$,readiness:Y,configHasErrors:W.length>0,steps:t,onStatus:e.onStatus,installMissing:e.installIndexers===!0}),et=pt.reindexResult,fn=pt.freshness,Re=Ke($),tt=Ug({projectRoot:i,cacheDir:o.cacheDir,watchConfig:Re,readiness:Y,configHasErrors:W.length>0,reindexResult:et,postReindexFreshness:fn,steps:t}),Ge=Xe(i,$),mt=Lt(Ge),Et=Te(i,$,o);G(t,{id:"capabilities",label:"Capability matrix",status:cy(mt),message:ly(mt)}),e.onStatus?.(e.runHealth===!0?"Running optional full health audit\u2026":"Skipping optional full health audit.");let ye=e.runHealth===!0?Xl(i,{runId:Gg(),startedAt:new Date().toISOString(),indexGeneration:Qe(o.dbPath)},{dossierDir:e.dossierDir}):null;ye?.interrupted&&G(t,{id:"health-dossier-attempt",label:"Previous health audit",status:"warn",message:`A health audit started at ${ye.interrupted.startedAt} (index generation ${ye.interrupted.indexGeneration??"unavailable"}) did not complete; the dossier it would have written was never published.`,details:[ye.attemptPath]});let Wt=e.runHealth===!0?await oy(o.dbPath,t):ry(t),xe=Ge.languages.includes("rust")?kn(i,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;G(t,{id:"rust-semantic-session",label:"Rust semantic session",status:xe===null?"skipped":xe.valid?"ok":"failed",optional:xe===null,message:xe===null?"Skipped because Rust was not detected.":`${xe.transport}/${xe.state} selected from ${xe.source}; ${xe.fallback} fallback; opt out with ${xe.optOut}.`});let Ne=null;try{e.noAgentGuidance?G(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(Ne=Jn(i),G(t,{id:"agent-guidance",label:"Project agent guidance",status:Ne.skipped.length>0?"warn":"ok",message:`${Ne.written.length} written, ${Ne.unchanged.length} already wired, ${Ne.skipped.length} skipped.`,details:Ne.skipped.map(M=>`Skipped ${M.target}: ${M.reason}`)}))}catch(M){G(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Mt(M)})}let q=Hg({reindexResult:et,readiness:Ge,capabilities:mt,freshness:Et,health:Wt,healthSelected:e.runHealth===!0,agentResult:Ne,watchConfig:Re,watchService:tt,rustSemanticSession:xe,steps:t});G(t,{id:"smoke-tests",label:"Setup smoke tests",status:Qg(q),message:Kg(q),details:q.map(M=>`${M.command}: ${M.status} - ${M.evidence}`)});let nt={repository:[...h?.changed?[h.configPath]:[],...y?.changed?[y.configPath]:[],...Ne?.written??[]],checkout:[],user:[...I.installed,...B.installed,...F.filter(M=>M.attempted).map(M=>`${M.binaryLabel} installer`)]},he={projectRoot:i,dbPath:r,configuredDbPath:o.dbPath,scipCliInstalled:L,languages:Ge.languages,steps:t,skills:I,astParsers:B,initialReadiness:E,indexerRemediation:F,readiness:Ge,capabilities:mt,freshness:Et,reindex:et,automaticRefreshConfig:y,watchService:tt,rustSemanticSession:xe,health:Wt,smokeTests:q,healthDossier:null,setupAgent:Ne,changeScopes:nt,filesWritten:Ne?.written??[],verdict:co(t,Ge)};if(e.runHealth!==!0)return G(t,{id:"health-dossier",label:"Health dossier",status:"skipped",optional:!0,message:"Skipped because the optional health audit was not selected."}),he.verdict=co(t,Ge),he;ye&&(he.indexGeneration=ye.attempt.indexGeneration,he.attempt={...ye.attempt,completedAt:new Date().toISOString()});let ne=ed(he,{dossierDir:e.dossierDir});return ye&&ne.status!=="failed"&&Zl(ye),he.healthDossier=ne,he.changeScopes.repository.push(...ne.written),he.filesWritten=[...he.filesWritten,...ne.written],G(t,{id:"health-dossier",label:"Health dossier",status:ne.status==="failed"?"failed":"ok",message:ne.status==="failed"?ne.error:`${ne.written.length} written, ${ne.unchanged.length} unchanged.`,details:[ne.markdownPath,ne.jsonPath]}),he.verdict=co(t,Ge),he}async function Vg(e){if(e.readiness.languages.length===0||e.configHasErrors)return G(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,i=null;try{let o=0,r=!1;for(let s=0;s<2;s+=1){if(n=await lc({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,maxHeapMb:e.config.indexer?.typescript?.maxHeapMb,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)}}),o+=n.durationMs,r||=!n.reused,i=Te(e.projectRoot,e.config,e.paths),s===0&&n.skipped.length===0&&i.state==="stale"){t.push(`Index inputs changed during the first build (${i.reason}); running one settling refresh.`);continue}break}if(!n)throw new Error("Setup index refresh produced no result.");G(e.steps,{id:"reindex",label:"Index refresh",status:n.skipped.length>0?"warn":"ok",message:`${r?"Indexed":"Reused"} ${n.languages.join(", ")} in ${(o/1e3).toFixed(1)}s.`,details:[...t,...n.skipped.map(s=>`Skipped ${s.language}: ${s.reason}`)]})}catch(o){G(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:Mt(o),details:t})}return{reindexResult:n,freshness:i}}function Ug(e){let t=e.readiness.languages.length===0?{reason:"Skipped because no supported languages were detected.",optional:!1}:e.configHasErrors?{reason:"Skipped because config validation has errors.",optional:!1}:e.watchConfig.enabled?e.reindexResult===null||e.reindexResult.skipped.length>0||e.postReindexFreshness?.state!=="fresh"?{reason:"Skipped because the initial refresh did not produce a complete fresh generation.",optional:!1}:null:{reason:"Disabled by watch.enabled=false; setup left the explicit opt-out unchanged.",optional:!0};if(t===null&&!e.watchConfig.autoStart)return G(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"ok",optional:!0,message:"Demand-started: the service starts with the first query that needs it (watch.autoStart=false); run scip-query watch --daemon to start it now."}),null;if(t!==null)return G(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",optional:t.optional,message:t.reason}),null;try{let n=Dn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:Ve,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 i=e.watchConfig.idleTimeoutMs===0?"configured to remain running":`clean-idle exit scheduled for ${n.state.idleDeadlineAt}`;return G(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"ok",message:`${n.disposition} pid ${n.state.pid}; ${i}.`,details:[`watcher=${n.state.watcher.state}`,`autoRefresh=${e.watchConfig.autoRefresh}`,`gitPollMs=${e.watchConfig.gitPollMs}`]}),n}catch(n){return G(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:Mt(n)}),null}}function ld(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${so(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:"),ao("Repository records (commit)",e.changeScopes.repository),ao("Checkout preferences (do not commit)",e.changeScopes.checkout),ao("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",i=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${i})`),t.recovery&&console.log(` ${t.recovery}`)}}}function ao(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function Hg(e){let t=e.steps.find(o=>o.id==="reindex"),n=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:zg(e.steps),evidence:Jg(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?Yg(e.capabilities):"No detected languages produced capability rows."},{id:"health",command:"scip-query health",status:e.health.score===null?"unavailable":"pass",optional:!e.healthSelected,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:Xg(e.readiness,e.freshness),evidence:Zg(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:ey(e.capabilities),evidence:ty(e.capabilities)},{id:"watch-refresh",command:"scip-query status --json",status:i?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",...i?.optional===!0?{optional:!0}:{},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",...e.rustSemanticSession===null?{optional:!0}:{},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":n?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:n?.message??"Project agent guidance was not written."}]}function Qg(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable"&&t.optional!==!0)?"warn":"ok"}function Kg(e){let t=e.filter(o=>o.status==="pass").length,n=e.filter(o=>o.status==="unavailable").length,i=e.filter(o=>o.status==="fail").length;return`${t} passed, ${n} unavailable, ${i} failed.`}function zg(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Jg(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function Yg(e){let t=e.matrix.filter(n=>[n.indexing,n.sourceFacts,n.semantic,n.cleanupVerification].some(i=>i.status==="unavailable")).length;return`${e.matrix.length} language row(s), ${t} with unavailable capability cells.`}function Xg(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function Zg(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 ey(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function ty(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(o=>o.cleanupVerification.status==="available").length,n=e.matrix.filter(o=>o.cleanupVerification.status==="partial").length,i=e.matrix.filter(o=>o.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${i} unavailable cleanup-verification row(s).`}function ny(e,t,n){let i=[];if(t.languages.length===0)return G(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),i;for(let s of t.indexers){if(s.runnable)continue;let a=Nn(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=ac(a,h=>c.push(h)):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 m=iy($n(a,e));i.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:d,before:s,after:m,messages:c,recovery:m.runnable?void 0:m.note??m.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(i.length===0)return G(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),i;let o=i.filter(s=>!s.after.runnable),r=i.filter(s=>s.attempted);return G(n,{id:"indexer-remediation",label:"Indexer remediation",status:o.length>0?"warn":"ok",message:o.length===0?`${r.length} install attempt(s); all detected indexers are runnable.`:`${r.length} install attempt(s); ${o.length} indexer(s) still blocked.`,details:i.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),i}function iy(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function oy(e,t){if(!Bg(e)){let n="Skipped because no SQLite index database exists yet.";return G(t,{id:"health",label:"Health audit",status:"skipped",message:n}),lo(n)}try{let n=await La({full:!0,json:!0});return G(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),sy(n)}catch(n){let i=Mt(n);return G(t,{id:"health",label:"Health audit",status:"failed",message:i}),lo(i)}}function ry(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return G(e,{id:"health",label:"Health audit",status:"skipped",optional:!0,message:t}),lo(t)}function sy(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(ay),warnings:e.warnings??[]}}function ay(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:"Confirm this signal against its named source evidence before editing; fix it only when it matches the requested goal."}}function lo(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function co(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"&&n.optional!==!0)?"partial":"ready"}function cy(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 ly(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 G(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Mt(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as dy}from"readline";function uy(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function py(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 i=n[e.cursor]?.id;if(!i)return e;let o=new Set(e.selected);return o.has(i)?o.delete(i):o.add(i),{...e,selected:o}}async function dd(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let i=uy(e);dy(t);let o=t.isRaw;t.setRawMode(!0),t.resume();let r=(s=!1)=>{s||n.write(`\x1B[${e.length+3}A`),n.write(`scip-query setup
30
- `),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
31
-
32
- `),e.forEach((a,c)=>{let l=c===i.cursor?"\u203A":" ",d=i.selected.has(a.id)?"\u25CF":"\u25CB";n.write(`${l} ${d} ${a.label} [${a.scope}]\x1B[K
33
- `)}),n.write("\x1B[K")};r(!0);try{return await new Promise((s,a)=>{let c=(d,m)=>{if(m.ctrl&&m.name==="c"){l(),a(new Error("Setup cancelled."));return}if(m.name==="return"||m.name==="enter"){l(),n.write(`
34
- `),s(i.selected);return}let h=m.name==="up"?"up":m.name==="down"?"down":m.name==="space"?"toggle":null;h&&(i=py(i,h,e),r())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!o),t.pause()}}import{existsSync as my}from"fs";import{join as uo}from"path";function ud(e,t={}){let n=[],i=e.dryRun?"would ":"";if(e.global){for(let r of e.global.removed)n.push(` ${i}remove: ${r}`);if(t.verbose)for(let r of e.global.left)n.push(` left: ${r}`);else if(e.global.left.length>0){let r=e.global.left.length===1?"entry":"entries";n.push(` left: ${e.global.left.length} unrelated global skill ${r} (use --verbose to list)`)}for(let r of e.global.skipped)n.push(` skip: ${r}`)}if(e.project){for(let r of e.project.agentSetup.removed)n.push(` ${i}remove: ${r}`);for(let r of e.project.agentSetup.unchanged)n.push(` ok: ${r} (no managed block)`);for(let r of e.project.agentSetup.skipped)n.push(` skip: ${r.target} \u2014 ${r.reason}`);for(let r of e.project.left)n.push(` left: ${r}`)}return(e.global?.removed.length??0)+(e.project?.agentSetup.removed.length??0)===0&&n.push(e.dryRun?"No scip-query-owned files would be removed.":"No scip-query-owned files removed."),n}function po(e){let t=e.global===!0,n=e.project===!0;return t&&n?{ok:!1,message:"choose either --global or --project, not both."}:!t&&!n?e.dryRun===!0?{ok:!0,global:!0,project:!0}:{ok:!1,message:"uninstall requires an explicit scope: use --global or --project. To preview both scopes without removing anything, run uninstall --dry-run."}:{ok:!0,global:t,project:n}}function pd(e){let t=po(e);if(!t.ok)throw new Error(t.message);let n={dryRun:e.dryRun===!0};return t.global&&(n.global=Lc({dryRun:e.dryRun,homeDir:e.homeDir})),t.project&&(n.project=hy(e.projectRoot,{dryRun:e.dryRun})),n}function hy(e,t={}){return{agentSetup:Wl(e,{dryRun:t.dryRun}),left:fy(e)}}function fy(e){return[[".scipquery.json",uo(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",uo(e,".scipquery","suppressions")],["docs/scip-query/",uo(e,"docs","scip-query")]].filter(([,t])=>my(t)).map(([t])=>t)}import{existsSync as md,lstatSync as gy,readdirSync as yy}from"fs";import{join as hd}from"path";function yd(e={}){let t=hd(e.cacheRoot??Yo(),"projects"),n={projectsDirectory:t,scannedCacheDirs:0,ownedCacheDirs:0,retainedRoots:0,orphanedRoots:0,stoppedServices:0,alreadyStoppedServices:0,skipped:[],failures:[]};if(!fd(t))return n;let i=e.rootIsCurrent??fd,o=e.stopService??qn;for(let r of yy(t,{withFileTypes:!0}).sort((s,a)=>s.name.localeCompare(a.name))){let s=hd(t,r.name);if(n.scannedCacheDirs+=1,!r.isDirectory()||r.isSymbolicLink()){n.skipped.push({cacheDir:s,message:"not a regular cache directory"});continue}let a;try{a=Xo(s).record.canonicalProjectRoot,n.ownedCacheDirs+=1}catch(c){n.skipped.push({cacheDir:s,message:gd(c)});continue}if(i(a)){n.retainedRoots+=1;continue}try{if(by(s,a),i(a)){n.retainedRoots+=1;continue}n.orphanedRoots+=1,o({projectRoot:a,cacheDir:s,cliVersion:"orphan-prune"}).disposition==="stopped"?n.stoppedServices+=1:n.alreadyStoppedServices+=1}catch(c){n.failures.push({cacheDir:s,projectRoot:a,message:gd(c)})}}return n}function by(e,t){let n=En(e),i=$r(n.statePath),o=wc(n.lockPath);if(md(n.statePath)&&!i)throw new Error("watch state exists but is not a valid ownership record");if(md(n.lockPath)&&!o)throw new Error("watch lock exists but is not a valid ownership record");if(i&&i.projectRoot!==t)throw new Error("watch state belongs to a different project root");if(o&&o.projectRoot!==t)throw new Error("watch lock belongs to a different project root");if(i&&o&&i.pid!==o.pid)throw new Error("watch state and lock name different process owners");if(i?.processIdentity&&o?.processIdentity&&!xn(i.processIdentity,o.processIdentity))throw new Error("watch state and lock name different process identities")}function fd(e){try{let t=gy(e);return t.isDirectory()&&!t.isSymbolicLink()}catch(t){let n=t.code;if(n==="ENOENT"||n==="ENOTDIR")return!1;throw t}}function gd(e){return e instanceof Error?e.message:String(e)}var bd={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 vd(e,t){let n=vy(t);return{...e,warnings:[...e.warnings??[],bd.note,...n],capabilities:t,scoreInterpretation:bd}}function vy(e){return e.matrix.flatMap(t=>{let n=[t.indexing,t.sourceFacts,t.semantic,t.cleanupVerification].map(i=>/syntax only/i.test(i.reason)?`${i.label}=partial (syntax only)`:i.status==="available"?null:`${i.label}=${i.status}`).filter(i=>i!==null);return n.length===0?[]:[`${t.language} capability limits: ${n.join(", ")}. Unsupported analyses are not clean zeros.`]})}import{createHash as Sy}from"crypto";import{basename as wy,join as $y}from"path";function Rd(e,t){let n=[t.id?`finding ${t.id}`:void 0,t.check?`check ${t.check}`:void 0,t.file?`file ${t.file}`:void 0].filter(o=>o!==void 0),i=t.decision;return[`Suppression ${e.disposition} at ${e.path}.`,` scope: ${n.join("; ")}`,` reason code: ${i?.reasonCode??"legacy/manual"}`,` counterevidence: ${i?.evidence.length??0} item(s)`,` expires: ${t.expiresAt??"none \u2014 no time limit; evidence invalidation still applies"}`,` revision: ${e.revision}`]}var an=class extends Error{constructor(n,i,o){super(`${n} ${o?`Current revision: ${o}. Retry with --replace ${o} after reviewing it.`:"The suppression file was left untouched."}`);this.path=i;this.currentRevision=o;this.name="SuppressionWriteConflictError"}path;currentRevision};function xd(e,t,n,i,o){if(!vi.includes(t))throw new Error(`unsupported suppression reason code ${JSON.stringify(t)}; expected one of ${vi.join(", ")}`);if(n.length===0)throw new Error("automatic suppression requires at least one --evidence <kind:referent>");let r=n.map(s=>Ty(e,s,i));return{kind:"automated-adjudication",reasonCode:t,decidedBy:"agent",policyVersion:1,...o?{observation:o}:{},evidence:r,invalidateOn:{targetContentChange:r.some(s=>s.contentHash!==void 0),detectorMajorChange:!0}}}function Cd(e,t,n={}){let i=n instanceof Date?{now:n}:n,o=xy(t),r=Cy(i.expectedRevision),s=$y(ba(e),va(o)),a=i.now??new Date,c="unchanged",l=It(s,d=>{if(!d.revision.exists){if(r)throw new an(`Cannot replace ${s}: the observed suppression no longer exists.`,s);return c="created",{kind:"write",text:$d(Sd(o,void 0,a,i.toolVersion))}}let m=Ry(d);if(ky(m.suppression,o))return c="unchanged",{kind:"unchanged"};if(!r)throw new an(`A different suppression decision already exists at ${s}.`,s,d.revision.hash);if(r!==d.revision.hash)throw new an(`Suppression ${s} changed after the revision you reviewed.`,s,d.revision.hash);return c="replaced",{kind:"write",text:$d(Sd(o,m.suppression,a,i.toolVersion))}},{maxRetries:0,onBeforeCommit:i.onBeforeCommit});return{path:s,disposition:c,revision:l.current.revision.hash}}function Ry(e){let t;try{t=JSON.parse(e.text)}catch(i){throw new Error(`Cannot update ${e.path}: the existing suppression is malformed JSON.`,{cause:i})}let n=wa(t,Ey(e.path));if("error"in n)throw new Error(`Cannot update ${e.path}: ${n.error}.`);return n}function Sd(e,t,n,i=Ve){let o=n.toISOString(),{decision:r,createdAt:s,...a}=e,c={kind:fa,suppressionIdentity:Sa(e),writer:{tool:"scip-query",version:i},...a,createdAt:t?.createdAt??s??o,...t?{updatedAt:o}:{}};return r?{...c,schemaVersion:ya,decision:r}:{...c,schemaVersion:ga}}function xy(e){let t=e.reason?.trim();if(!t)throw new Error("suppression requires a non-empty reason");let n=e.id?.trim(),i=e.check?.trim();if(!n&&!i)throw new Error("suppression requires an id or a check");if(e.decision!==void 0&&!aa(e.decision))throw new Error("suppression decision is malformed");return{...n?{id:n}:{},...i?{check:i}:{},...e.file?{file:e.file}:{},reason:t,...e.expiresAt?{expiresAt:e.expiresAt}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.decision?{decision:e.decision}:{}}}function Cy(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 ky(e,t){return JSON.stringify(wd(e))===JSON.stringify(wd(t))}function wd(e){let{createdAt:t,...n}=e;return n}function Ey(e){let t=wy(e);return t.endsWith(".json")?t.slice(0,-5):t}function $d(e){return`${JSON.stringify(e,null,2)}
35
- `}function Ty(e,t,n){let i=t.indexOf(":");if(i<=0||i===t.length-1)throw new Error("--evidence must use <source|config|test|graph>:<referent>");let o=t.slice(0,i),r=t.slice(i+1).trim();if(o==="graph"){if(!r.startsWith("scip-query "))throw new Error("graph suppression evidence must name the exact scip-query command that produced it");return{kind:o,referent:r,claim:n}}if(o!=="source"&&o!=="config"&&o!=="test")throw new Error(`unsupported suppression evidence kind ${JSON.stringify(o)}`);let s=Go(r),a=St(e,s);return{kind:o,referent:s,claim:n,contentHash:Sy("sha256").update(a).digest("hex")}}import{execFileSync as Iy}from"child_process";var Ay={changedPaths:Ly,indexedPaths:e=>tr(e,{includeIgnored:!1}),architectureFindings:e=>$t(Tt(e))},Py=/\.(?:[cm]?[jt]sx?|vue|java|scala|kt|kts|rs|py|rb|go|c|cc|cpp|cxx|h|hh|hpp|hxx|cs|vb|dart|php|clj|cljs|cljc)$/iu;function Ed(e,t,n=Ay){let i=n.changedPaths(e);if(i.includes(".scipquery.json"))return{kind:"block",checkedSourceFiles:[],findings:[],reason:"Architecture policy changed in the same worktree as the implementation. Keep .scipquery.json policy changes in a separate reviewed change, then stop again."};let o=new Set(n.indexedPaths(t)),r=i.filter(a=>o.has(a)||Py.test(a));if(r.length===0)return{kind:"allow",checkedSourceFiles:[],findings:[]};let s=n.architectureFindings(t);return s.length===0?{kind:"allow",checkedSourceFiles:r,findings:[]}:{kind:"block",checkedSourceFiles:r,findings:s,reason:`scip-query found ${s.length} enforced architecture violation(s):
36
- ${s.map(a=>`- ${a}`).join(`
37
- `)}
38
-
39
- Inspect the boundary graph with: scip-query architecture`}}function Td(e){return e.kind==="block"?{decision:"block",reason:e.reason}:{}}function Ly(e){let t=kd(e,["diff","--name-only","--diff-filter=ACMRTUXB","HEAD","--"]),n=kd(e,["ls-files","--others","--exclude-standard","--"]);return[...new Set([...t,...n])].sort()}function kd(e,t){try{return Iy("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:10*1024*1024,killSignal:"SIGKILL"}).split(/\r?\n/u).map(n=>n.trim()).filter(Boolean)}catch(n){throw new Error(`Could not inspect changed files for the architecture Stop hook: ${jy(n)}`,{cause:n})}}function jy(e){return e instanceof Error?e.message:String(e)}var My=new Set(Bt),Ld=Z(({db:e})=>{try{let t=Ed(ue(),e);process.stdout.write(`${JSON.stringify(Td(t))}
40
- `)}catch(t){let n=`scip-query could not verify architecture at Stop: ${t instanceof Error?t.message:String(t)}. The Stop was blocked because the architecture result is unknown.`;process.stdout.write(`${JSON.stringify({decision:"block",reason:n})}
41
- `)}});function Oy(e){return e.filter(t=>My.has(t))}async function jd(e){let t=le(e),n=ue(),i=Ee(n),o=Ue(n,i),r=b(t,"json");try{let s=Oy(O(t,"language")),a=await kc(n,i,o,{languages:s.length>0?s:i.languages,force:b(t,"force"),allowPartial:b(t,"allowPartial"),allowExpensiveRebuild:b(t,"allowExpensiveRebuild"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",installMissing:b(t,"installMissing"),trustProjectTools:b(t,"trustProjectTools"),indexerConcurrency:K(t,"indexerConcurrency")??i.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...r?{onStatus:()=>{}}:{onStatus:console.log}});if(r){P("reindex",[],t,a);return}if(a.skipped.length>0){let c=a.languages.length>0?a.languages.join(", "):"none";console.log(`Reindex partial: available language output ${c}; ${a.skipped.length} skipped in ${(a.durationMs/1e3).toFixed(1)}s.`);for(let l of a.skipped)console.log(` skip: ${l.language} \u2014 ${l.reason}`)}else 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 Nd(){let e=ue(),t=Pi(e);try{let n=Za({projectRoot:e,dbPath:t,onStatus:i=>console.log(i)});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 Md(e){let t=le(e),n=ue(),i=Pi(n);try{let o=await cc({projectRoot:n,dbPath:i,tsconfig:w(t,"project")??"frontend/tsconfig.scip.json",onStatus:r=>console.log(r)});console.log(`Vue files: ${o.vueFiles}; resolved references: ${o.resolvedReferences}; inserted mentions: ${o.insertedMentions}; not-inserted identifier tokens: ${o.skippedReferences}; synthetic symbols: ${o.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${o.skippedReferenceReasons["no-definition"]}; same-file definition ${o.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${o.skippedReferenceReasons["unindexed-definition"]}; missing source ${o.skippedReferenceReasons["missing-source-file"]}; missing service script ${o.skippedReferenceReasons["missing-service-script"]}. Samples: ${o.skippedReferenceSamples.length} omitted, ${o.resolvedReferenceSamples.length} resolved.`)}catch(o){console.error(`error: ${o instanceof Error?o.message:o}`),process.exit(1)}}function Od(e){let t=le(e);Me(n=>{let i=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),o=$s(n,{base:w(t,"base")}),r=Rs(n,i,o.changedFiles,o.changedRanges);Pn(zt,r)})}async function Dd(e){let t=le(e);try{let n=await Ma({base:w(t,"base")});if(b(t,"json")){P("diff-impact",[],t,n.result,{observationReceipt:n.observationReceipt});return}Oa(n.result)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function qd(e,t){let n=le(t),i=String(e).split(",").filter(o=>o.length>0);Me(o=>{let r=[];for(let c of i)zs.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),r.push(c);let s={scope:w(n,"scope"),full:b(n,"full")},a=r.length===1?Js(o,r[0],s):Ys(o,r,s);Pn(Qt,a)})}async function Fd(e){let t=le(e);await xa(async n=>{let i=Number.parseInt(w(t,"shardIndex")??"",10),o=Number.parseInt(w(t,"shardCount")??"",10),r=Number.isSafeInteger(i)&&Number.isSafeInteger(o)&&o>1&&i>=0&&i<o?{index:i,count:o}:void 0,s=await Pa(n,{scope:w(t,"scope"),full:b(t,"full"),...r?{shard:r}:{}});Pn(Kt,s)})}async function Wd(e){let t=le(e);if(b(t,"writeBaseline")||b(t,"baseline")){Dy(t);return}try{let n=await ja({scope:w(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:i,config:o,dbPath:r}=qe(),s=Lt(Xe(i,o),{hasIndexedGraph:cn(r)}),a=vd(n.result,s);if(b(t,"json")){P("health",[],t,a,{observationReceipt:n.observationReceipt});return}Na(a)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Dy(e){let t=w(e,"scope");Me(n=>{if(b(e,"writeBaseline")){let o=Us(n,{scope:t});console.log(`Baseline written to ${o.path} (${o.findingCount} finding(s)).`);return}let i=Hs(n,{scope:t});if(i.fixedFindings.length>0&&console.log(`${i.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),i.newFindings.length===0){console.log(`OK: no new findings vs baseline (${i.baselineCount} baselined, ${i.current.length} current).`);return}console.log(`FAIL: ${i.newFindings.length} new finding(s) vs ${i.baselinePath}:`);for(let o of i.newFindings)console.log(` + ${o}`);process.exitCode=1})}function _d(){let e=_n(),t=e.installed.length+e.alreadyLinked.length;console.log(`
42
- ${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 Bd(){let e=!1;en()?console.log("scip CLI: installed"):jn()?(Oi(),e=!0):console.log("scip CLI: not installed (not required; SCIP is converted to SQLite in-process unless SCIP_QUERY_SQLITE_CONVERTER=scip-cli).");let t=ue(),n=Ee(t),i=Xe(t,n);if(i.languages.length===0){console.log(`
43
- No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
44
- Detected languages: ${i.languages.join(", ")}`),console.log(`
45
- Indexer readiness:`);for(let r of i.indexers){let s=r.runnable?" OK":r.installed?" WARN":" MISSING",a=r.resolvedBinary?` (${r.resolvedBinary})`:"";console.log(`${s} ${r.language}: ${r.binaryLabel}${a}`),r.note&&console.log(` ${r.note}`),!r.installed&&r.installUrl&&console.log(` install: ${r.installUrl}`),r.runnable||(e=!0)}let o=iu(i);o.length>0&&console.log(`
46
- Semantic provider readiness:`);for(let r of o){let s=r.available?" OK":r.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${r.language}: ${Jy(r)}${ou(r)}`),r.reason&&console.log(` ${r.reason}`)}process.exitCode=e?1:0}function Gd(e){qy(e)}function qy(e){let t=le(e),{projectRoot:n,config:i,paths:o,dbPath:r}=qe(),s=Xe(n,i),a=Te(n,i,o),c=Lt(s,{hasIndexedGraph:cn(r)&&a.state!=="missing"});if(b(t,"json")){P("capabilities",[],t,{...c,explorationControls:Kn,relationshipQuestions:Fn(),unavailableRelationshipFrontiers:In});return}tb(c,{matrix:b(t,"matrix")})}function Vd(){let e=ue(),t=An(e),n=ca(e,t);console.log(n.changed?`Config written to ${n.configPath}`:`Config already exists at ${n.configPath}; existing contents left unchanged.`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Ud(e){let t=le(e),n=ue(),i=Ee(n),o=$a(n),r=[...Rt(i,{projectRoot:n}),...o.compatibility.issues.map(s=>({level:"error",path:s.path,message:s.reason}))];if(b(t,"json"))P("config-validate",[],t,{diagnostics:r});else if(r.length===0)console.log("Config OK.");else for(let s of r)console.log(`${s.level.toUpperCase()} ${s.path}: ${s.message}`);r.some(s=>s.level==="error")&&(process.exitCode=1)}function Hd(e,t){let n=le(t),i=w(n,"reason");if(!i||i.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}let o=w(n,"reasonCode"),r=O(n,"evidence");if(!o||r.length===0){console.error("error: suppress requires --reason-code <code> and at least one --evidence <source|config|test|graph>:<referent> so automatic adjudication has inspectable counterevidence."),process.exitCode=1;return}try{let s=ue(),a=(()=>{try{return Me(()=>Ia())}catch{return}})(),c={id:String(e),check:w(n,"check"),file:w(n,"file"),reason:i,expiresAt:w(n,"expiresAt"),decision:xd(s,o,r,i,a)},l=Cd(s,c,{expectedRevision:w(n,"replace")});if(b(n,"json")){P("suppress",[String(e)],n,l);return}for(let d of Rd(l,c))console.log(d)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exitCode=1}}function Qd(e){let t=le(e),{report:n,hasIndexerProblems:i,hasErrors:o}=Kd("doctor");b(t,"json")?P("doctor",[],t,n):Uy(n,i),process.exitCode=o?1:0}function Kd(e){let{projectRoot:t,config:n,paths:i,dbPath:o}=qe(),r=Rt(n,{projectRoot:t}),s=Xe(t,n),a=Te(t,n,i),c=cn(o),l=Lt(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=Cc(t,n,i),m=s.indexers.some(f=>!f.runnable),h=r.some(f=>f.level==="error")||m||a.state==="missing"||a.state==="stale",p=r.some(f=>f.level==="error")||m||a.state==="missing";return{report:{command:e,projectRoot:t,dbPath:o,configuredDbPath:i.dbPath,exists:c,configDiagnostics:r,readiness:s,freshness:a,capabilities:l,sharedCache:d,ok:!h},hasIndexerProblems:m,hasErrors:p}}function zd(e){le(e);let t=ue(),n=Jn(t);for(let o of n.written)console.log(` done: ${o}`);for(let o of n.unchanged)console.log(` ok: ${o} (already wired)`);for(let o of n.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);let i=Fl(n);i.verdict==="ready"?console.log(`
47
- Project agent guidance is configured for every selected target.`):i.verdict==="partial"?console.log(`
48
- Project agent guidance is only partially configured: ${i.ready} target(s) ready, ${i.skipped} skipped. Resolve the skips before relying on every agent integration.`):console.log(`
49
- Project agent guidance was not configured: all ${i.skipped} selected target(s) were skipped.`),i.ready>0&&console.log("Configured agents can use compiler-backed exploration, impact, architecture, and health evidence. When declared architecture rules are ready, setup also installs the local architecture-only Stop hook."),process.exitCode=i.verdict==="ready"?0:1}async function Jd(e){let t=le(e);try{let n=b(t,"guided"),i=b(t,"yes"),o=b(t,"json");sd({guided:n,yes:i,json:o,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0});let r=b(t,"installMissing"),s={dossierDir:w(t,"dossierDir"),runHealth:t.health===!0,installSkills:t.skills!==!1,installIndexers:r,installAstParsers:r&&t.parsers!==!1,...i?{automaticRefresh:!0}:{}},a=!o&&!i&&process.stdin.isTTY&&process.stdout.isTTY;(n||a)&&(s=await Fy(s,{json:o})),o||(s.onStatus=l=>console.log(` ${l}`));let c=await cd(s);o?P("setup",[],t,c):ld(c),process.exitCode=c.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Fy(e,t){let{projectRoot:n,config:i}=qe(),o=Xe(n,i),r=ad({files:Wy(n),watchEnabled:Ke(i).enabled,readiness:o}),s=o.languages.map(f=>({id:`language:${f}`,scope:"project",label:`Index ${f}`,reason:"Detected in this project.",selected:!0})),a=r.actions.map(f=>({id:f.id,scope:f.scope==="repository"?"project":f.scope,label:f.label,reason:f.reason,selected:f.recommended})),c=Zn(o.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:e.runHealth===!0});let l=!t.json&&process.stdin.isTTY&&process.stdout.isTTY,d=l?await dd([...s,...a]):new Set([..._y(r.actions),...s.map(f=>f.id),...e.runHealth===!0?["run-health-analysis"]:[]]);l&&By(r.actions,d);let m=d.has("create-agent-guidance")||d.has("update-agent-guidance"),h=r.actions.some(f=>f.id==="enable-automatic-refresh"),p=r.actions.some(f=>f.id==="install-indexers");return{...e,...h?{automaticRefresh:d.has("enable-automatic-refresh")}:{},noAgentGuidance:!m,...p?{installIndexers:l?d.has("install-indexers"):e.installIndexers===!0}:{},languages:o.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 Wy(e){return{agentsMd:cn(Id(e,"AGENTS.md")),claudeMd:cn(Id(e,"CLAUDE.md"))}}function _y(e){return new Set([...e.filter(t=>t.recommended&&t.id!=="install-indexers").map(t=>t.id),"install-agent-skills"])}function By(e,t){console.log(""),console.log("Selected setup changes:");for(let n of["repository","checkout","user"]){let i=e.filter(r=>r.scope===n&&t.has(r.id)).map(r=>r.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"}): ${i.length>0?i.join(", "):"none"}`)}}function Yd(e){let t=le(e),n=po({global:b(t,"global"),project:b(t,"project"),dryRun:b(t,"dryRun")});if(!n.ok){console.error(`error: ${n.message}`),process.exitCode=1;return}let i=pd({projectRoot:ue(),global:n.global,project:n.project,dryRun:b(t,"dryRun")});if(b(t,"json")){P("uninstall",[],t,i);return}for(let o of ud(i,{verbose:b(t,"verbose")}))console.log(o)}async function Xd(e){let t=le(e),n=K(t,"debounce"),i=K(t,"cooldown"),o=K(t,"gitPoll"),r=K(t,"idleTimeout"),s=b(t,"daemon"),a=b(t,"status"),c=b(t,"stop"),l=b(t,"prune"),d=b(t,"json"),m=[s,a,c,l].filter(Boolean).length;if(m>1){console.error("error: choose only one of --daemon, --status, --stop, or --prune."),process.exitCode=1;return}if(d&&m===0){console.error("error: --json requires --daemon, --status, --stop, or --prune."),process.exitCode=1;return}let p=[["--debounce",n],["--cooldown",i],["--git-poll",o],["--idle-timeout",r]].filter(([,I])=>I!==void 0);if((a||c||l)&&p.length>0){console.error(`error: timing options (${p.map(([I])=>I).join(", ")}) only apply when starting a foreground or daemon watcher; ${l?"--prune does":"--status and --stop do"} not accept them.`),process.exitCode=1;return}let f=[["--debounce",n,!1],["--cooldown",i,!0],["--git-poll",o,!1],["--idle-timeout",r,!0]].find(([,I,T])=>I!==void 0&&(!Number.isInteger(I)||(T?Number(I)<0:Number(I)<=0)));if(f){console.error(`error: ${f[0]} requires ${f[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}if(l){Gy(t,d);return}let g=ue(),y=Ee(g),v={...n===void 0?{}:{debounceMs:n},...i===void 0?{}:{cooldownMs:i},...o===void 0?{}:{gitPollMs:o},...r===void 0?{}:{idleTimeoutMs:r}};n&&((y.watch??={}).debounceMs=n),i!==void 0&&((y.watch??={}).cooldownMs=i),o&&((y.watch??={}).gitPollMs=o),r!==void 0&&((y.watch??={}).idleTimeoutMs=r);let $=Ke(y);y.watch=$;let L=Ue(g,y),_={projectRoot:g,cacheDir:L.cacheDir,cliVersion:Ve,watchOverrides:v};if(a){let I=Zd(Pt(_),$.enabled);d?P("watch",[],t,I):eu(I);return}if(c){try{let I=qn(_);d?P("watch",[],t,I):console.log(I.disposition==="stopped"?`Stopped watch service${I.pid?` (pid ${I.pid})`:""}.`:"Watch service is already stopped.")}catch(I){console.error(`error: ${I instanceof Error?I.message:String(I)}`),process.exitCode=1}return}if(!$.enabled){console.error('error: watch mode is disabled. Set "watch.enabled": true in .scipquery.json to start it.'),process.exitCode=1;return}if(s){try{if(p.length>0){let T=Pt(_);if(T.classification.kind==="live")throw new Error(`watch service pid ${T.classification.state.pid} is already running. Timing options only apply when the process starts; run "scip-query watch --stop", then repeat this daemon command.`)}let I=Dn(_);d?P("watch",[],t,I):(console.log(`${I.disposition==="started"?"Started":"Reused"} watch service for ${g} (pid ${I.state.pid}).`),p.length>0&&console.log(`Process-local timing overrides: ${p.map(([T,W])=>`${T}=${W}`).join(", ")}. These were not written to .scipquery.json.`))}catch(I){console.error(`error: ${I instanceof Error?I.message:String(I)}`),process.exitCode=1}return}console.log(`Watching ${g}`),console.log(`Debounce: ${$.debounceMs}ms | Cooldown: ${$.cooldownMs}ms | Git poll: ${$.gitPollMs}ms`),console.log(`Press Ctrl+C to stop.
50
- `);try{await to(g,Ve,v),console.log(`
51
- Stopped.`)}catch(I){console.error(`
52
- Watch error: ${I instanceof Error?I.message:String(I)}`),process.exitCode=1}}function Gy(e,t){try{let n=yd();if(t)P("watch",[],e,n);else{console.log(`Watcher cleanup scanned ${n.scannedCacheDirs} cache ${n.scannedCacheDirs===1?"directory":"directories"}: stopped ${n.stoppedServices} orphaned service(s), found ${n.alreadyStoppedServices} already stopped, retained ${n.retainedRoots} live root(s), and skipped ${n.skipped.length} unowned or invalid entry/entries.`);for(let i of n.skipped)console.log(`Skipped ${i.cacheDir}: ${i.message}`);for(let i of n.failures)console.error(`error: could not clean ${i.cacheDir}: ${i.message}`)}n.failures.length>0&&(process.exitCode=1)}catch(n){console.error(`error: ${n instanceof Error?n.message:String(n)}`),process.exitCode=1}}function Zd(e,t=!0){let{classification:n}=e,i=tn(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:i}:{enabled:t,state:"stopped",mode:"none",refreshRequests:i};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:i,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:i,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};default:return Vy(n)}}function eu(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`),Ad(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: ${Ca(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, ${ce(n.estimatedWriteBytes??n.estimatedLogicalOutputBytes)} estimated writes (${ce(n.estimatedLogicalOutputBytes)} logical output)${n.confidence&&n.confidence!=="complete"?` [${n.confidence} evidence]`:""}`),(n.reflinkedBytes!==void 0||n.fallbackCopiedBytes!==void 0)&&console.log(`Reindex staging: ${ce(n.reflinkedBytes??0)} reflinked, ${ce(n.fallbackCopiedBytes??0)} byte-copied`);for(let[i,o]of Object.entries(n.byLanguage??{}).sort(([r],[s])=>r.localeCompare(s)))o&&console.log(`Reindex language ${i}: ${o.runs} run(s) (${o.rebuilt} rebuilt, ${o.reused} reused), ${ce(o.producedOutputBytes)} produced, ${Xy(o.durationMs)} cumulative indexer time`);n.languageAttribution&&n.languageAttribution!=="complete"&&console.log(`Reindex language attribution: ${n.languageAttribution}; ${n.unattributedRuns??0} completed run(s) unattributed, ${n.invalidLanguageDetails??0} invalid detail(s) ignored`),n.confidence&&n.confidence!=="complete"&&console.log(`Reindex evidence: ${n.recordsRead??0} record(s) read, ${n.invalidRecords??0} invalid, ${n.readErrors??0} read error(s), ${n.ignoredPartialTailBytes??0} incomplete byte(s) ignored`)}if("refreshRequests"in e&&e.refreshRequests&&Ad(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,i=n.activeSessions===void 0||n.maxActiveSessions===void 0?"":`, ${n.activeSessions}/${n.maxActiveSessions} warm sessions`;console.log(`TypeScript index: ${n.state} (${n.initializations} warmups, ${n.programUpdates} updates, ${n.requests} requests${i}${n.sessionsEvicted?`, ${n.sessionsEvicted} evicted`:""})`),n.heapUsedBytes!==void 0&&console.log(`TypeScript index memory: ${ce(n.heapUsedBytes)}${n.heapLimitBytes===void 0?"":` / ${ce(n.heapLimitBytes)} heap`}${n.softMemoryLimitBytes===void 0?"":`; ${ce(n.softMemoryLimitBytes)} retirement mark`}${n.retireRequested?"; retirement requested":""}`)}}function Ad(e){console.log(`Refresh requests: ${e.pending} pending, ${e.claimed} claimed, ${e.completed} completed, ${e.expired} expired${e.invalid>0?`, ${e.invalid} invalid`:""}`)}function Vy(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function tu(e){let t=le(e),{report:n}=Kd("status"),i=Ke(Ee(n.projectRoot)).enabled,o=Zd(Pt({projectRoot:n.projectRoot,cacheDir:Ny(n.configuredDbPath),cliVersion:Ve}),i),r=ec(n.dbPath),s=ma(n.dbPath,n.freshness.metaPath),a=pa(n.dbPath),c=kn(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(b(t,"json")){P("status",[],t,{...n,affectedSetShadow:r,sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:o,stats:Zy(n.exists)});return}Hy(n,{affectedSetShadow:r,capabilities:b(t,"capabilities"),sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:o})}function Uy(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(i=>!i.runnable))console.log(` MISSING ${n.language}: ${n.note??n.binaryLabel}`);console.log(` Freshness: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),nu(e.capabilities)}function Hy(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 iu(e.readiness)){let i=n.available?"available":n.dependencyAvailable?"fallback":"unavailable",o=n.language==="typescript"?"TS sem:":`${n.language} sem:`;console.log(`${o.padEnd(9)}${i}${ou(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: ${Yy(e.freshness.lastRefresh)}`),eu(t.watchService),Qy(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"),Ky(t.sqliteGeneration),zy(t.localGenerations),console.log(`Shadow: ${tc(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),eb(e.exists),t.capabilities&&(console.log(""),nu(e.capabilities),console.log("Run `scip-query capabilities` for the semantic control manual."))}function nu(e){let t=Pd(e.capabilities),n=Pd(e.relations);console.log(` Languages: ${e.languages.join(", ")||"(none detected)"}`),console.log(` Analysis readiness: ${t.available} available, ${t.partial} partial, ${t.unavailable} unavailable`),console.log(` Relationship providers: ${n.available} available, ${n.partial} partial, ${n.unavailable} unavailable`)}function Pd(e){return{available:e.filter(t=>t.status==="available").length,partial:e.filter(t=>t.status==="partial").length,unavailable:e.filter(t=>t.status!=="available"&&t.status!=="partial").length}}function Qy(e){if(e.state!=="managed"){console.log(`Shared: ${e.state}${e.reason?` (${e.reason})`:""}`);return}let t=e.baseGenerationId?.slice(0,12)??"none",n=e.activeGenerationId?.slice(0,12)??"none",i=e.lastAction??"none";console.log(`Shared: ${i}, base ${t}, active ${n}, ${e.generations} generation(s), ${ce(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${ce(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), ${ce(e.cleanup.deletedBytes??0)} removed`)}function Ky(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",i=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(o=>o!==null).join(", "):"no publication metrics";console.log(`DB gen: ${e.state} ${e.generation.currentGeneration.slice(0,12)} (${n}; ${i})`),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 zy(e){e.state!=="absent"&&(console.log(`Local GC: ${e.state}, ${e.generationCount} generation(s), ${ce(e.logicalBytes)}, ${e.protectedGenerations} protected (${e.activeReaderLeases} live reader lease(s)); limits ${e.limits.maxGenerations} / ${ce(e.limits.maxLogicalBytes)}`),e.oldestGenerationAt&&console.log(`Local age: oldest generation ${e.oldestGenerationAt}`),e.lastCollection&&console.log(`Local last: ${e.lastCollection.state} at ${e.lastCollection.at}, ${e.lastCollection.removedGenerations} removed`),e.reason&&console.log(`Local why: ${e.reason}`))}function iu(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Jy(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function ou(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function Yy(e){let t=(e.durationMs/1e3).toFixed(1),n=e.trigger.detail?` (${e.trigger.detail})`:"",i=e.error?`: ${e.error}`:"";return`${e.result} by ${e.trigger.kind}${n} in ${t}s at ${e.completedAt}${i}`}function Xy(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(1)} s`}function Zy(e){if(e)return Me(t=>{let n=Gt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function eb(e){e&&Me(t=>{let n=Gt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${ce(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function tb(e,t={}){console.log(`Exploration capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`),console.log(`
53
- Primary controls:`);for(let n of Kn)console.log(` ${n.stage.toUpperCase().padEnd(8)} scip-query ${n.command} [${n.outputCost}] \u2014 ${n.question}`);console.log(`
54
- Relationship controls:`);for(let n of Fn()){let o=e.relations.find(r=>r.family===n.family)?.status??"unsupported";console.log(` ${o.toUpperCase().padEnd(11)} ${n.family} ${n.direction} \u2014 ${n.question}`)}if(console.log(`
55
- Strengths: ${Object.keys(Ht).join(", ")}. Unavailable analyses: ${In.map(n=>n.id).join(", ")}.`),console.log(`
56
- The agent chooses a question, family, and direction; this command reports support and does not infer intent.`),!t.matrix){console.log("Run `scip-query capabilities --matrix` only when a named claim needs contract or provider details.");return}nb(e),ib(e)}function nb(e){console.log(`
57
- Control contracts:`);for(let t of Kn)console.log(` scip-query ${t.command}`),console.log(` Input: ${t.requiredInput}`),console.log(` Returns: ${t.returnedFact}`),console.log(` Ceiling: ${t.evidenceCeiling}`),console.log(` Does not establish: ${t.nonClaim}`),t.contrasts.length>0&&console.log(` Contrast: ${t.contrasts.join(" ")}`),t.gapClosingCommands.length>0&&console.log(` Close disclosed gaps with: ${t.gapClosingCommands.join(", ")}`);console.log(`
58
- Relationship contracts:`);for(let t of Fn()){let i=e.relations.find(o=>o.family===t.family)?.status??"unsupported";console.log(` ${i.toUpperCase().padEnd(11)} ${t.family} ${t.direction}`),console.log(` Establishes: ${t.establishes}`),console.log(` Strengths: ${t.evidenceStrengths.join(", ")||"none registered"}`),console.log(` Provider ceilings: ${t.supportCeilings.join(", ")||"none registered"}`),console.log(` Does not establish: ${t.nonClaim}`)}console.log(`
59
- Evidence strength legend:`);for(let[t,n]of Object.entries(Ht))console.log(` ${t.toUpperCase().padEnd(11)} ${n}`);console.log(`
60
- Explicitly unavailable relationship analyses:`);for(let t of In)console.log(` ${t.id} [${t.families.join(", ")}]`),console.log(` ${t.capability}`),console.log(` Consequence: ${t.consequence}`),console.log(` Recover selected paths with: ${t.recoverWith.join(", ")}`)}function ib(e){console.log(`
61
- Project capability matrix:`);for(let t of e.capabilities)console.log(` ${t.status.toUpperCase().padEnd(11)} ${t.label} [${t.evidence}]`),console.log(` ${t.reason}`);console.log(`
62
- Relationship support:`);for(let t of e.relations){console.log(` ${t.status.toUpperCase().padEnd(11)} ${t.family}`),console.log(` ${t.establishes}`),console.log(` Does not establish: ${t.nonClaims.join(" ")}`);for(let n of t.providerCapabilities)console.log(` ${n.status.toUpperCase().padEnd(11)} ${n.id}: ${n.subtypes.join(", ")}`),console.log(` ${n.reason}`)}if(e.matrix.length!==0){console.log(`
63
- 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 Ot(e){return{...e,options:x(e.options)}}function lt({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let d=Ot(l);return{...d,renderShape:"list",handler:Ba({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c})}}function ei({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d,...m}){let h=Ot(m);return{...h,renderShape:"table",handler:Ga({commandName:h.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d})}}function ru({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,key:l,...d}){let m=Ot(d);return{...m,renderShape:"grouped-by-file",handler:Va({commandName:m.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,key:l})}}function mo({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let d=Ot(l);return{...d,renderShape:"sectioned-report",handler:Mi({commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:o,sections:i,toJson:r,coverage:s,agentResult:a,after:c})}}function su({query:e,precomputed:t,emptyMessage:n,heuristicLabel:i,sections:o,before:r,toJson:s,coverage:a,agentResult:c,after:l,...d}){let m=Ot(d),h={commandName:m.id,emptyMessage:n,heuristicLabel:i,sections:o,before:r,toJson:s,coverage:a,agentResult:c,after:l},p=Mi({...h,query:e});return{...m,renderShape:"sectioned-report",handler:Ua(h,t,p)}}function xt({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let d=Ot(l);return{...d,budget:d.budget??"semantic",renderShape:"sectioned-report",handler:Ha(d.id,{commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:o,sections:i,toJson:r,coverage:s,agentResult:a,after:c})}}import{existsSync as Mb,mkdirSync as Ob,writeFileSync as Db}from"fs";import{dirname as qb,relative as Fb}from"path";import{existsSync as dt,readdirSync as lb}from"fs";import{basename as db,dirname as mu,isAbsolute as hu,join as ub,relative as pb,resolve as ln,sep as mb}from"path";import{spawnSync as rb}from"child_process";import{dirname as sb}from"path";function cu(e){let n=(e.spawnSync??rb)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:sb(e.specPath),maxBuffer:1024*1024*32,timeout:3e4,killSignal:"SIGKILL"});if(n.status!==0)return null;let i=n.stdout??"";return i.includes("<?xml")?i:null}function lu(e){let t=cb(e),n=new Map,i=new Map,o=[],r=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?i.set(a.uid,a.uniquename):a.type==="UserDefinedOpKind"&&a.uniquename&&(o.push(a),r.set(a.uid,a));let s=[];for(let a of o){let c=du(a.block,n,i,r,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:o.map(a=>a.uniquename).sort(),actions:s}}var ab=8;function cb(e){let t=[],n=/<entry>\s*<UID>(\d+)<\/UID>\s*<(\w+)>/g;for(let i of e.matchAll(n)){let o=i.index,r=e.indexOf("</entry>",o),s=e.slice(o,r<0?e.length:r),a=ho(s,"uniquename"),c=ho(s,"kind"),l=ho(s,"filename");t.push({uid:i[1],type:i[2],uniquename:a===null?null:au(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:au(l),block:s})}return t}function du(e,t,n,i,o,r,s){let a=new Set,c=new Set,l=[...e.matchAll(/<(\w+Ref)>\s*<UID>(\d+)<\/UID>/g)],d="read";for(let[,m,h]of l){if(m==="BuiltInKindRef"){let p=n.get(h)??"";p==="'"?d="write-next":p==="UNCHANGED"?d="unchanged-run":d==="unchanged-run"&&p==="$Tuple"||d!=="write-next"&&(d="read");continue}if(m==="OpDeclNodeRef"){let p=t.get(h);if(!p)continue;d==="write-next"?(c.add(p),d="read"):d==="unchanged-run"||a.add(p);continue}if(m==="UserDefinedOpKindRef"){d==="unchanged-run"&&(d="read");let p=i.get(h);if(p&&s<ab&&!r.has(p.uid)&&p.filename===o){let f=du(p.block,t,n,i,o,new Set([...r,p.uid]),s+1);for(let g of f.reads)a.add(g);for(let g of f.writes)c.add(g)}continue}d==="unchanged-run"&&(d="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function ho(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function au(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var fu=["update","insert","delete"],gu=["select","query","findFirst","findMany"],fo=new Set([...fu,...gu]);function go(e){let t=e.methods&&e.methods.length>0?e.methods:[...fo],n=new Set(fu),i=new Set(gu);return{write:t.filter(o=>n.has(o)),read:t.filter(o=>i.has(o))}}var hb=/^(.*)@L(\d+)-L(\d+)$/;function yo(e){let t=e.match(hb);if(!t)return{ref:e};let n=t[1],i=Number.parseInt(t[2],10),o=Number.parseInt(t[3],10);return n?i<1?{error:`codeRef "${e}" line window must start at line 1 or later`}:o<i?{error:`codeRef "${e}" line window end (L${o}) is before its start (L${i})`}:{ref:n,window:{startLine:i,endLine:o}}:{error:`codeRef "${e}" has a line window but no referent before @L${t[2]}-L${t[3]}`}}var fb=new Set(["auto","sany","tlc","apalache","none"]),ni=/^[A-Za-z_][A-Za-z0-9_]*$/;function yu(e){return fb.has(e)}function ii(e,t){let n=[],i=Pe(e,t);if(!i)return{errors:[`map path escapes project root: ${t}`]};if(!dt(i))return{errors:[`map file not found: ${t}`]};let o;try{o=JSON.parse(Ce(i,{inputKind:"TLA mapping",maxBytes:yn}))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let r=gb(o,n);return r?{loaded:{contract:r,mapPath:i,mapDir:mu(i)},errors:n}:{errors:n}}function Pe(e,t){if(!t)return null;let n=hu(t)?ln(t):ln(e,t);return bt(e,n)?n:null}function bu(e,t,n){if(!n)return null;if(hu(n)){let s=ln(n);return bt(e,s)?s:null}let i=ln(e,n);if(bt(e,i)&&dt(i))return i;let o=ln(t,n);if(bt(e,o)&&dt(o))return o;let r=bt(e,i)?i:o;return bt(e,r)?r:null}function vu(e,t){let n=Pe(e,t);if(!n||!dt(n))return null;let i=Ce(n,{inputKind:"TLA module",maxBytes:vt});return{path:n,modelParse:"regex-fallback",text:i,variables:Ab(i),operators:Pb(i),actions:[]}}function Su(e,t,n){let i=Pe(e,t);if(!i||!dt(i))return null;let o=Ce(i,{inputKind:"TLA module",maxBytes:vt}),r=lu(n);return{path:i,modelParse:"sany",text:o,variables:r.variables,operators:r.operators,actions:r.actions}}function bo(e,t){let n=Pe(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!dt(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let i=JSON.parse(Ce(n,{inputKind:"TLA trace",maxBytes:vt})),o=Array.isArray(i)?i:ie(i)&&Array.isArray(i.steps)?i.steps:null;if(!o)return{steps:[],errors:["trace file must be an array or an object with a steps array"]};let r=[],s=[];for(let[a,c]of o.entries()){if(!ie(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}r.push({action:c.action,before:ie(c.before)?c.before:void 0,after:ie(c.after)?c.after:void 0,code:typeof c.code=="string"?c.code:void 0})}return{steps:r,errors:s}}catch(i){let o=i instanceof Error?i.message:String(i);return{steps:[],errors:[`trace file is not valid JSON: ${o}`]}}}function vo(e,t){let n=new Set,i=[];for(let o of t){let r=Pe(e,o)??o;n.has(r)||(n.add(r),i.push(o))}return i}function gb(e,t){if(!ie(e))return t.push("map file must contain a JSON object"),null;let n=$b(e.variables,t);wb(n,t);let i=Tb(e.actions,n,t),o=yb(e.init,t);vb(o,i,t);let r={module:pu(e.module,"module",t),config:pu(e.config,"config",t),scope:be(e.scope)??[],variables:n,actions:i,...o?{init:o}:{},invariants:be(e.invariants)??[],traces:be(e.traces)??[],unmappedWriteScope:Sb(e.unmappedWriteScope,t)};return jb(e.scope,t),t.length===0?r:null}function yb(e,t){if(e===void 0)return;if(!ie(e)){t.push("init must be an object when present");return}let n=be(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let i=bb(e.waive,t);return{codeRefs:n,...i?{waive:i}:{}}}function bb(e,t){if(e===void 0)return;if(!ie(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 vb(e,t,n){if(!e)return;let i=new Set(e.codeRefs),o=new Set;for(let r of Object.values(t))for(let s of r.code)i.has(s)&&o.add(s);o.size>0&&n.push(`init.codeRefs overlaps action code referents: ${[...o].sort().join(", ")} \u2014 a referent cannot be both Init and an action`)}function Sb(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 wb(e,t){ti(e,t,"alias",n=>n.aliases),ti(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),ti(e,t,"statement pattern",n=>n.statements?n.statements.map(i=>i.pattern):[]),ti(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(i=>{let{write:o,read:r}=go(i);return[...o,...r].map(s=>`${i.table}:${s}`)}))}function ti(e,t,n,i){let o=new Map;for(let[r,s]of Object.entries(e))for(let a of i(s)){let c=o.get(a);c?c.push(r):o.set(a,[r])}for(let[r,s]of o)s.length<2||t.push(`variables ${[...new Set(s)].sort().join(", ")} share ${n} "${r}" \u2014 conformance scanning cannot attribute a matching write/read to one variable unambiguously`)}function $b(e,t){if(!ie(e))return t.push("variables must be an object keyed by TLA+ variable name"),{};let n={};for(let[i,o]of Object.entries(e)){if(!ni.test(i)){t.push(`invalid TLA+ variable name: ${i}`);continue}if(!ie(o)){t.push(`variables.${i} must be an object`);continue}let r=$u(o.code);if(!r||r.length===0){t.push(`variables.${i}.code must name at least one TypeScript referent`);continue}let s=be(o.aliases)??[],a=xb(o.resource,i,t),c=Cb(o.statements,i,t),l=kb(o.ormCalls,i,t),d=Eb(o.waive,i,t),m=Rb(o.selfAlias,i,t),h=m?[...new Set([i,...s])]:[...new Set(s)];m===!1&&h.length===0&&!a&&!c&&!l&&!d&&t.push(`variables.${i}.selfAlias is false but no aliases, resource, statements, ormCalls, or waive are set \u2014 ${i} would be unattributable; add an explicit alias, bind resource/statements/ormCalls, or add variables.${i}.waive with a reason`),n[i]={code:r,aliases:h,projection:typeof o.projection=="string"?o.projection:void 0,...a?{resource:a}:{},...c?{statements:c}:{},...l?{ormCalls:l}:{},...d?{waive:d}:{},...m===!1?{selfAlias:!1}:{}}}return n}function Rb(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 xb(e,t,n){if(e===void 0)return;if(!ie(e)){n.push(`variables.${t}.resource must be an object when present`);return}let i=typeof e.path=="string"?e.path.trim():"";if(!i){n.push(`variables.${t}.resource.path must be a non-empty string`);return}return{path:i}}function Cb(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 i=[];return e.forEach((o,r)=>{if(!ie(o)){n.push(`variables.${t}.statements[${r}] must be an object`);return}let s=typeof o.pattern=="string"?o.pattern.trim():"";if(!s){n.push(`variables.${t}.statements[${r}].pattern must be a non-empty string`);return}try{gn(s,`variables.${t}.statements[${r}].pattern`)}catch(a){let c=a instanceof Error?a.message:String(a);n.push(`variables.${t}.statements[${r}].pattern is not a valid regular expression: ${c}`);return}i.push({pattern:s})}),i.length>0?i:void 0}function kb(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 i=[];return e.forEach((o,r)=>{if(!ie(o)){n.push(`variables.${t}.ormCalls[${r}] must be an object`);return}let s=typeof o.table=="string"?o.table.trim():"";if(!s){n.push(`variables.${t}.ormCalls[${r}].table must be a non-empty string`);return}if(o.methods===void 0){i.push({table:s});return}let a=be(o.methods);if(!a){n.push(`variables.${t}.ormCalls[${r}].methods must be an array of strings when present`);return}let c=a.filter(l=>!fo.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${r}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...fo].join(", ")}`);return}i.push(a.length>0?{table:s,methods:a}:{table:s})}),i.length>0?i:void 0}function Eb(e,t,n){if(e===void 0)return;if(!ie(e)){n.push(`variables.${t}.waive must be an object when present`);return}let i=typeof e.reason=="string"?e.reason.trim():"";if(!i){n.push(`variables.${t}.waive.reason must be a non-empty string`);return}return{reason:i}}function Tb(e,t,n){if(!ie(e))return n.push("actions must be an object keyed by TLA+ action name"),{};let i=new Set(Object.keys(t)),o={};for(let[r,s]of Object.entries(e)){if(!ni.test(r)){n.push(`invalid TLA+ action name: ${r}`);continue}if(!ie(s)){n.push(`actions.${r} must be an object`);continue}let a=$u(s.code);if(!a||a.length===0){n.push(`actions.${r}.code must name at least one TypeScript referent`);continue}for(let h of a){let p=yo(h);"error"in p&&n.push(`actions.${r}.code: ${p.error}`)}let c=be(s.reads)??[],l=be(s.writes)??[],d=be(s.calls)??[];for(let h of[...c,...l])i.has(h)||n.push(`actions.${r} references unknown variable: ${h}`);let m=Ib(s.waive,s.allowUnknown===!0,c,l,i,r,n);o[r]={code:a,reads:c,writes:l,calls:d,...m?{waive:m}:{}}}return o}function Ib(e,t,n,i,o,r,s){if(ie(e)){let a=typeof e.reason=="string"?e.reason.trim():"";a||s.push(`actions.${r}.waive.reason must be a non-empty string`);let c=be(e.reads)??[],l=be(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${r}.waive must list reads or writes`),uu(r,"reads",c,o,s),uu(r,"writes",l,o,s),{reads:[...new Set(c)],writes:[...new Set(l)],reason:a}}if(e!==void 0&&s.push(`actions.${r}.waive must be an object when present`),t)return{reads:[...new Set(n)],writes:[...new Set(i)],reason:"legacy allowUnknown",legacy:!0}}function uu(e,t,n,i,o){for(let r of n)i.has(r)||o.push(`actions.${e}.waive.${t} references unknown variable: ${r}`)}function Ab(e){let t=new Set;for(let n of e.matchAll(/^\s*VARIABLES?\s+([^\n]+)/gm)){let i=n[1]??"";for(let o of i.split(",")){let r=o.trim();ni.test(r)&&t.add(r)}}return[...t].sort()}function Pb(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 Lb=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function wu(e){if(!e||!dt(e))return[];let t=Ce(e,{inputKind:"TLA checker configuration",maxBytes:yn}).replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,i=!1;for(let o of t.split(/[\s,]+/))if(o){if(Lb.has(o)){i=o==="INVARIANT"||o==="INVARIANTS";continue}i&&ni.test(o)&&n.add(o)}return[...n].sort()}function pu(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function $u(e){return typeof e=="string"?[e]:be(e)}function jb(e,t){e!==void 0&&(be(e)||t.push("scope must be an array of strings when present"))}function oi(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var Nb=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function Ru(e,t){if(!dt(t))return{status:"none"};let i=Ce(t,{inputKind:"TLA module",maxBytes:vt}).match(Nb)?.[1],o=pb(e,t).split(mb).join("/"),r=db(t),s=new Set([i,o,r,r.replace(/\.tla$/i,"")].filter(d=>!!d)),a=mu(t);if(!dt(a))return{status:"none"};let c=[];for(let d of lb(a)){if(!d.endsWith(".scip-tla.json"))continue;let m=ub(a,d),h;try{h=JSON.parse(Ce(m,{inputKind:"TLA mapping candidate",maxBytes:yn}))}catch{continue}ie(h)&&typeof h.module=="string"&&s.has(h.module)&&c.push(m)}c.sort();let l=i??o;return c.length===0?{status:"none"}:c.length>1?{status:"ambiguous",candidates:c,moduleName:l}:{status:"found",mapPath:c[0],moduleName:l}}function ri(e,t,n,i,o={count:e.length,loc:i}){let r=o.count===e.length&&o.loc===i?`${e.length}, ${i} LOC`:`${e.length} of ${o.count}, ${i} of ${o.loc} LOC`;console.log(`\u2550\u2550\u2550 ${t} (${r}) \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((m,h)=>m+h.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((m,h)=>m.startLine-h.startLine);for(let m of d){let h=m.implicitUsageReason?` [implicit usage: ${m.implicitUsageReason}]`:"";console.log(` ${ve(m.startLine,m.endLine)} (${m.loc} LOC) ${m.shortName}${h}`)}}}var So=20,xu=te("dead",({db:e,args:t,opts:n,budget:i})=>{let o={scope:H(t,0)||void 0,minLoc:k(n,"minLoc",1),includeTests:b(n,"includeTests"),skipBarrels:b(n,"skipBarrels"),includeMembers:b(n,"includeMembers"),scanLimit:i.scanLimit,semantic:i.semantic},r=Fr(e,o),s=r.symbols.filter(F=>F.kind==="dead-code"),a=r.symbols.filter(F=>F.kind==="file-internal"),c=r.symbols.filter(F=>F.kind==="implicit-usage"),l=!b(n,"onlyInternal"),d=!b(n,"onlyDead"),m=!b(n,"onlyDead")&&!b(n,"onlyInternal"),h=l?s:[],p=d?a:[],f=m?c:[],g=h.reduce((F,Y)=>F+Y.loc,0),y=p.reduce((F,Y)=>F+Y.loc,0),v=f.reduce((F,Y)=>F+Y.loc,0),$=b(n,"full"),L=$?h:h.slice(0,So),_=$?p:p.slice(0,So),I=$?f:f.slice(0,So),T=L.reduce((F,Y)=>F+Y.loc,0),W=_.reduce((F,Y)=>F+Y.loc,0),E=I.reduce((F,Y)=>F+Y.loc,0),B={total:h.length+p.length+f.length,deadCode:h.length,fileInternal:p.length,implicitUsage:f.length,loc:g+y+v};if(b(n,"json")){P("dead",t,n,{...r,shown:{deadCode:h,fileInternal:p,implicitUsage:f},shownCounts:B,totals:{total:r.counts.total,deadCode:r.counts.deadCode,fileInternal:r.counts.fileInternal,implicitUsage:r.counts.implicitUsage,loc:r.counts.loc}},{analysisBudget:i.analysisBudget});return}if(h.length===0&&p.length===0&&f.length===0){A.empty("No matching dead-code symbols found.");return}h.length>0&&(ri(L,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
64
- Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,T,{count:h.length,loc:g}),!$&&h.length>L.length&&console.log(`
65
- Showing top ${L.length} by LOC. Re-run with --full for the remaining ${h.length-L.length}.`)),p.length>0&&(h.length>0&&console.log(""),ri(_,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
66
- single-use helper, an abstraction-in-progress, or a callback registered
67
- through a framework path that static analysis cannot trace (signal
68
- handlers, event listeners, dependency injection). NOT necessarily dead \u2014
69
- review case by case.`,W,{count:p.length,loc:y}),!$&&p.length>_.length&&console.log(`
70
- Showing top ${_.length} by LOC. Re-run with --full for the remaining ${p.length-_.length}.`)),f.length>0&&((h.length>0||p.length>0)&&console.log(""),ri(I,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
71
- consumer that the static reference graph cannot trace. Investigation
72
- signals only \u2014 not deletion candidates and not counted as dead code.`,E,{count:f.length,loc:v}),!$&&f.length>I.length&&console.log(`
73
- Showing top ${I.length} by LOC. Re-run with --full for the remaining ${f.length-I.length}.`));let J=[];l&&J.push(`${h.length} dead code (${g} LOC)`),d&&J.push(`${p.length} file-internal (${y} LOC)`),m&&J.push(`${f.length} implicit usage (${v} LOC)`),console.log(`
74
- \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: ${h.length+p.length+f.length} symbols \u2014 ${J.join(" + ")}`)}),Cu=Ie("unused-imports",{query:({db:e,args:t,budget:n})=>Gr(e,N(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
75
- ${e.length} unused import(s)`)}),ku=Qa("isolated",{query:({db:e,opts:t,budget:n})=>Zr(e,{scope:w(t,"scope"),minLoc:k(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ve(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
76
- ${e.length} isolated symbol(s)`)}),Eu=te("extract-candidates",({db:e,args:t,opts:n,budget:i})=>{let o=ys(e,{scope:w(n,"scope"),minLoc:k(n,"minLoc",10),minCallees:k(n,"minCallees",6),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(b(n,"json")){P("extract-candidates",t,n,o,{analysisBudget:i.analysisBudget});return}if(o.length===0)return A.empty("No extraction candidates found.");rt("extraction candidates");for(let r of o){console.log(`
77
- ${V(r.relativePath,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC, ${r.totalCallees} callees)`),console.log(` Kind: ${r.extractionKind}; tier: ${r.actionTier}`),console.log(` Recommendation: ${r.recommendation}`);for(let s of r.evidenceReasons)console.log(` - ${s}`);for(let s=0;s<r.clusters.length;s++){let a=r.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(`
78
- ${o.length} extraction candidate(s) found.`)}),Tu=te("locality-candidates",({db:e,args:t,opts:n,budget:i})=>{let o=bs(e,{target:H(t,0)||void 0,scope:w(n,"scope"),minConsumers:k(n,"minConsumers",1),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(b(n,"json")){P("locality-candidates",t,n,o,{analysisBudget:i.analysisBudget});return}if(o.length===0)return A.empty("No locality candidates found.");rt("locality candidates");for(let r of o){let s=r.sourceUnit.kind==="symbol"&&r.sourceUnit.startLine!==void 0&&r.sourceUnit.endLine!==void 0?V(r.sourceUnit.file,r.sourceUnit.startLine,r.sourceUnit.endLine):r.sourceUnit.file;if(console.log(`
79
- ${s} ${r.sourceUnit.shortName}`),console.log(` Current directory: ${r.currentDirectory}; tier: ${r.recommendedTier}; action: ${r.actionTier}`),console.log(` Consumer coverage: ${r.consumerCoverage}; consumers: ${r.consumerFiles.length}`),r.nearestCommonOwner&&console.log(` Nearest common owner: ${r.nearestCommonOwner}`),r.suggestedHome&&console.log(` Suggested home: ${r.suggestedHome}`),r.whyNoSuggestedHome&&console.log(` Suggested home withheld: ${r.whyNoSuggestedHome}`),r.boundaryMarkers.length>0&&console.log(` Boundary markers: ${r.boundaryMarkers.join("; ")}`),console.log(` Recommendation: ${r.recommendation}`),r.consumerFiles.length>0){for(let a of r.consumerFiles.slice(0,8))console.log(` - consumer: ${a}`);r.consumerFiles.length>8&&console.log(` - ... ${r.consumerFiles.length-8} more consumer(s)`)}for(let a of r.counterevidence)console.log(` - counterevidence: ${a}`)}console.log(`
80
- ${o.length} locality candidate(s) found.`)}),Iu=Ie("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>Vs(e,{scope:w(t,"scope"),maxLoc:k(t,"maxLoc",15),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
81
- Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
82
- Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
83
- ${e.length} wrapper candidate(s).`)}),Au=Ie("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>Is(e,{scope:w(t,"scope"),maxLoc:k(t,"maxLoc",15),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
84
- Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
85
- Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
86
- Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
87
- Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
88
- ${e.length} passthrough candidate(s).`)}),Pu=Ie("stale-abstractions",{query:({db:e,opts:t,budget:n})=>Gs(e,{scope:w(t,"scope"),minLoc:k(t,"minLoc",3),limit:D(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}] ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
89
- ${e.reason}
90
- Kind: ${e.stalenessKind}; tier: ${e.actionTier}
91
- Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
92
- ${e.length} stale abstraction(s).`)}),Lu=Ln("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Ks(e,{scope:w(t,"scope"),minLoc:k(t,"minLoc",10),limit:D(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]}),ju=Fe("similar",{query:({db:e,args:t,opts:n,budget:i})=>{if(b(n,"plan")){let r=H(t,0),s=H(t,1);if(!r||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:as(e,r,s,{scanLimit:i.scanLimit,semantic:i.semantic})}}let o=H(t,0);return o?{mode:"target",rows:ss(e,o,{minSimilarity:k(n,"minSimilarity",.4),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic})}:{mode:"all",rows:cs(e,{minSimilarity:k(n,"minSimilarity",.4),limit:D(n,"limit",20),scope:w(n,"scope"),minCallees:k(n,"minCallees",4),crossFileOnly:b(n,"crossFileOnly"),scanLimit:i.scanLimit,semantic:i.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(`
93
- ${Math.round(t.similarity*100)}% ${n}
94
- `),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}
95
- `),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let i of t.sharedEvidence)console.log(` ${i}`);if(t.uniqueToA.length>0){console.log(`
96
- Unique to A (${t.uniqueToA.length}):`);for(let i of t.uniqueToA)console.log(` ${i}`)}if(t.uniqueToB.length>0){console.log(`
97
- Unique to B (${t.uniqueToB.length}):`);for(let i of t.uniqueToB)console.log(` ${i}`)}console.log(`
98
- Strategy: ${t.consolidationStrategy}`);return}if(e.mode==="target"){A.list(e.rows,t=>{let n=t.similarityBasis??"callees",i=n==="source-tokens"?"Shared source tokens":"Shared callees",o=n==="source-tokens"?"Only tokens in":"Only in",r=[`
99
- ${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}`,` ${i}: ${t.sharedCallees.join(", ")}`];return t.evidenceClassReasons.length&&r.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.uniqueToA.length&&r.push(` ${o} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&r.push(` ${o} B: ${t.uniqueToB.join(", ")}`),r.join(`
100
- `)});return}A.list(e.rows,t=>`
101
- ${Math.round(t.similarity*100)}% similar:
102
- A: ${t.shortNameA} (${t.fileA})
103
- B: ${t.shortNameB} (${t.fileB})
104
- Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})
105
- Recommendation: ${t.recommendation}
106
- `+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
107
- `:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
108
- ${e.rows.length} similar pair(s) found.`)}}),Nu=ft({commandName:"similar-files",query:({db:e,args:t,opts:n})=>ls(e,{minSimilarity:k(n,"minSimilarity",.5),limit:D(n,"limit",20),scope:w(n,"scope"),minDeps:K(n,"minDeps"),filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{A.list(e,t=>{let n=[`
109
- ${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(`
110
- `)}),console.log(`
111
- ${e.length} similar pair(s) found.`)}}),Mu=ft({commandName:"similar-chains",query:({db:e,opts:t})=>gs(e,{minSimilarity:k(t,"minSimilarity",.5),limit:D(t,"limit",15),scope:w(t,"scope"),minChainLength:k(t,"minLength",3),maxChainLength:k(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(`
112
- \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 i of n.divergencePoints)console.log(` [${i.index}] ${i.nodeA} \u2194 ${i.nodeB}`)}console.log(`
113
- ${e.length} similar chain pair(s) found.`)}}),Ou=Fe("drift",{query:({db:e,args:t,opts:n,budget:i})=>Bs(e,{scope:H(t,0),minDeviation:k(n,"minDeviation",5),semantic:i.semantic,includePatternDeviations:b(n,"patterns"),includeArchitecture:b(n,"architecture"),limit:D(n,"limit",50)}),emptyMessage:e=>e.results.length===0&&!e.architecture?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{if(console.log(""),A.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="architecture-violation"||t.kind==="layer-violation"?"ARCH":"UNIQUE",i=t.policyBasis?`, policy: ${t.policyBasis}`:"",o=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${i}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&o.push(` ${t.detail}`),o.join(`
114
- `)},t=>t.file),e.architecture){let t=e.architecture,n=t.edges.filter(i=>i.policyStatus==="undeclared").length;if(console.log(`
115
- 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 i of t.reciprocalPairs)console.log(` ${i.boundaries[0]} <-> ${i.boundaries[1]}`)}if(t.cycles.length>0){console.log(` Connected boundary groups (${t.cycles.length}):`);for(let i of t.cycles){let o=i.violatesPolicy?" [violates requireAcyclic]":" [signal]";console.log(` { ${i.boundaries.join(", ")} }${o}`)}}}console.log(`
116
- ${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)`:""}`)}}),Du=Fe("convergence",{query:({db:e,args:t,budget:n})=>Xs(e,N(t,0),N(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(`
117
- ${Math.round(e.similarity*100)}% callee overlap
118
- `),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)
119
- `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
120
- Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
121
- Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
122
- Strategy: ${e.consolidationStrategy}`)}}}),qu=Ie("similar-signatures",{query:({db:e,opts:t,budget:n})=>ia(e,{scope:w(t,"scope"),minLoc:k(t,"minLoc",3),maxShapeFrequency:k(t,"maxShapeFrequency",12),limit:D(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
123
- Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,i=e.functions.map(o=>` ${V(o.file,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC)`).join(`
124
- `);return`${n}
125
- ${i}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
126
- ${e.length} group(s) found.`)}),Fu=Ie("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>Es(e,{scope:w(t,"scope"),maxLoc:k(t,"maxLoc",15),minLoc:k(t,"minLoc",3),limit:D(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
127
- Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((i,o)=>` ${(o===0?"canonical":"duplicate").padEnd(9)} ${V(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
128
- `);return`${t}
129
- ${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>console.log(`
130
- ${e.length} group(s) found.`)}),Wu=Ie("twin-drift",{query:({db:e,opts:t,budget:n})=>Ts(e,{scope:w(t,"scope"),minSimilarity:k(t,"minSimilarity",.3),includeHomonyms:b(t,"includeHomonyms"),limit:D(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
131
- ${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(o=>` ${V(o.file,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC)`).join(`
132
- `),i=e.firstDivergentTokens?`
133
- first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
134
- ${n}${i}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
135
- ${e.length} group(s) found.`)}),_u=Ie("not-implemented",{query:({db:e,opts:t,budget:n})=>Ls(e,{scope:w(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
136
- ${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
137
- ${e.length} reachable placeholder stub(s).`)}),Bu=Ie("decorative-checkers",{query:({db:e,opts:t,budget:n})=>js(e,{scope:w(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${V(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(`
138
- ${e.length} decorative checker candidate(s).`)}),Gu=te("test-quality",({db:e,args:t,opts:n,budget:i})=>{let o=Ns(e,{scope:w(n,"scope"),limit:D(n,"limit",30),scanLimit:i.scanLimit,rotDays:K(n,"rotDays")});if(b(n,"json")){P("test-quality",t,n,o,{analysisBudget:i.analysisBudget});return}if(rt("test-quality findings"),o.assertionFree.length+o.skipped.length+o.mockEcho.length===0){A.empty("No test-quality findings.");return}o.assertionFree.length>0&&(console.log(`
139
- ASSERTION-FREE (${o.assertionFree.length})`),A.list(o.assertionFree,s=>` ${V(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),o.skipped.length>0&&(console.log(`
140
- SKIPPED (${o.skipped.length})`),A.list(o.skipped,s=>` ${s.file}:${s.startLine+1} "${s.title}" (${s.blockKind}.${s.skipKind}, age: ${s.ageDays??"unknown"}d, ${s.rot})`)),o.mockEcho.length>0&&(console.log(`
141
- MOCK-ECHO (${o.mockEcho.length})`),A.list(o.mockEcho,s=>` ${V(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
142
- ${o.assertionFree.length} assertion-free, ${o.skipped.length} skipped, ${o.mockEcho.length} mock-echo.`)}),Vu=ft({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let i=N(t,0),o=N(t,1),r=w(n,"out")??As(i,o),s=Pe(e.config.projectRoot,r);if(!s)throw new Error(`twin-ab output path escapes the project root: ${r}`);let a=Ps(e,{refA:i,refB:o,outFile:s});if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=Fb(e.config.projectRoot,s);if(!b(n,"force")&&Mb(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return Ob(qb(s),{recursive:!0}),Db(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
143
- Wrote behavioral A/B scaffold: ${e.outPath}`),console.log(` A: ${e.a.shortName} (${V(e.a.file,e.a.startLine,e.a.startLine)})`),console.log(` B: ${e.b.shortName} (${V(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(`
144
- Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),Uu=te("cleanup-plan",({db:e,args:t,opts:n,budget:i})=>{let o=ws(e,{scope:w(n,"scope"),minLoc:k(n,"minLoc",1),maxDepth:k(n,"maxDepth",5),scanLimit:i.scanLimit}),r=ue(),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(o.batches.length===0){if(a){P("cleanup-plan",t,n,o,{analysisBudget:i.analysisBudget});return}return A.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=Hc(o),d=c?_c(r,o):void 0;if(a){P("cleanup-plan",t,n,{result:o,verification:d},{analysisBudget:i.analysisBudget});return}if(s){let m=Qc(d,l);if(m.length>0){for(let p of m)console.error(`error: ${p}`);process.exitCode=1;return}let h=Uc(r,l);if(h.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), ${o.totalLoc} LOC.`),console.log(h);return}console.log(`Cleanup plan: ${o.totalSymbols} symbol(s), ${o.totalLoc} LOC across ${o.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
145
- `);for(let m of o.batches){let h=m.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${m.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${m.depth}: dead once batch ${m.depth-1} lands (cascade, ${m.loc} LOC) \u2500\u2500`;console.log(h);for(let p of m.entries)console.log(` ${p.file}:${p.startLine+1}-${p.endLine+1} ${p.shortName} (${p.loc} LOC)`);m.filesEmptied.length>0&&console.log(` -> empties: ${m.filesEmptied.join(", ")}`),console.log("")}if(o.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let m of o.blocked)console.log(` ${m.shortName} (${m.file}) blocked by ${m.blockingFiles.join(", ")}`)}if(d){if(console.log(`
146
- Verifying batches against the project checker (isolated snapshot of committed 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 p of d.checkers)console.log(` Checker: ${p}`);if(d.unavailableReason){console.log(` UNAVAILABLE: ${d.unavailableReason}.`);return}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.workingTree.state==="unavailable"&&console.log(` WARNING: working-tree inspection unavailable: ${d.workingTree.reason}`),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 p=d.dirtyWorkingTree.slice(0,5),f=d.dirtyWorkingTree.length-p.length;console.log(` WARNING: verification ran at HEAD; ${d.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${p.join(", ")}${f>0?`, ... ${f} more`:""}`)}let m=Wb(d.checkers),h=_b(d.checkers);for(let p of d.batches)if(p.status==="verified")console.log(` Batch ${p.depth}: VERIFIED (${m})${h}`);else{console.log(` Batch ${p.depth}: FAILED${p.reason?` (${p.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let f of p.errors??[])console.log(` ${f}`)}}});function Wb(e){return e.join(", ")}function _b(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var Hu=te("recent-duplicates",({db:e,args:t,opts:n,budget:i})=>{let o=b(n,"full"),r=Ms(e,{windowCommits:k(n,"window",100),minSimilarity:K(n,"minSimilarity"),limit:D(n,"limit",30),scope:w(n,"scope"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:o?"full":"bounded"});if(b(n,"json")){P("recent-duplicates",t,n,r,{analysisBudget:i.analysisBudget});return}if(!r.available)return A.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return A.empty(`No recent re-implementations found (window: last ${r.windowCommits} commits).`);rt("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
147
- `);let s=r.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 r.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(`
148
- ${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Qu=Z(({db:e,args:t,opts:n})=>{let i=b(n,"full"),o=ks(e,{doc:t[0]===void 0?void 0:N(t,0),limit:D(n,"limit",20),minCoupling:k(n,"minCoupling",3),includeSnapshotExcluded:i,historyMode:i?"full":"bounded"});if(b(n,"json")){P("doc-drift",t,n,o);return}if(!o.available)return A.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return A.empty(`No drifting docs found across ${o.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);rt("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${o.docsScanned} docs scanned, ${o.commitsAnalyzed} commits analyzed):
149
- `);for(let r of o.findings){let s=r.snapshotExcluded?" [snapshot (excluded by policy)]":"",a=r.docLastChangedAtEstimated?" [docLastChangedAt estimated from file mtime]":"";console.log(` staleness ${r.staleness} ${r.doc}${s}${a}`);for(let c of r.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${c} \u2014 that file no longer exists`);for(let c of r.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 m=c.citationContexts?.[0];m&&console.log(` cited claim: ${Aa(m)}`)}}console.log(`
150
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),Ku=Ie("unused-params",{query:({db:e,opts:t,budget:n})=>Qs(e,{scope:w(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${V(e.file,e.startLine,e.endLine)} ${e.shortName}
151
- 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(`
152
- ${e.length} function(s) with trailing unused parameters.`)});var zu=Fe("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>ds(e,{minSimilarity:k(n,"minSimilarity",.62),minTokens:k(n,"minTokens",8),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{A.list(e,t=>{let n=[`
153
- ${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(`
154
- `)}),console.log(`
155
- ${e.length} duplicated React component pair(s) found.`)}}),Ju=Fe("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:i})=>us(e,{minSimilarity:k(n,"minSimilarity",.45),minSharedBehaviors:k(n,"minSharedBehaviors",6),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{A.list(e,t=>{let n=[`
156
- ${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(`
157
- `)}),console.log(`
158
- ${e.length} React hook candidate pair(s) found.`)}}),Yu=Fe("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:i})=>ps(e,{minComponentLines:k(n,"minComponentLines",300),minFileLines:k(n,"minFileLines",800),minJsxTokens:k(n,"minJsxTokens",80),minBehaviorTokens:k(n,"minBehaviorTokens",40),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{A.list(e,t=>[`
159
- ${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(`
160
- `)),console.log(`
161
- ${e.length} large React component(s) found.`)}}),Xu=Fe("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>ms(e,{minSimilarity:k(n,"minSimilarity",.62),minTokens:k(n,"minTokens",8),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{A.list(e,t=>{let n=[`
162
- ${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(`
163
- `)}),console.log(`
164
- ${e.length} duplicated Vue component pair(s) found.`)}}),Zu=Fe("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:i})=>hs(e,{minSimilarity:k(n,"minSimilarity",.45),minSharedBehaviors:k(n,"minSharedBehaviors",6),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{A.list(e,t=>{let n=[`
165
- ${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(`
166
- `)}),console.log(`
167
- ${e.length} Vue composable candidate pair(s) found.`)}}),ep=Fe("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:i})=>fs(e,{minTotalLines:b(n,"reviewThresholds")&&Ka(n,"minTotalLines")==="default"?300:k(n,"minTotalLines",800),minTemplateLines:k(n,"minTemplateLines",300),minScriptLines:k(n,"minScriptLines",300),minStyleLines:k(n,"minStyleLines",500),limit:D(n,"limit",20),scope:w(n,"scope"),scanLimit:i.scanLimit,filePattern:H(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{A.list(e,t=>{let n=[`
168
- ${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(`
169
- `)}),console.log(`
170
- ${e.length} large Vue view pressure file(s) found.`)}});function $e(e){return{docs:R("Cleanup"),...e}}function re({heuristicLabel:e,...t}){return $e({...t,heuristic:{label:e}})}var si=[$e({id:"unused-params",command:"unused-params",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Maximum findings",S,30),u("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:R("Cleanup",["scip-query unused-params -s src/services"]),handler:Ku}),$e({id:"cleanup-plan",command:"cleanup-plan",agent:C("What code can be deleted safely, and in what dependency order?","ordered cleanup batches, evidence, and optional verification outcomes",[],"bounded","repository",z("repository-preview")),description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Only include symbols >= N lines",S,1),u("--max-depth <n>","Maximum cascade depth",S,5),u("--verify","Apply batches in an isolated HEAD snapshot and run the project checker (tsc / cargo check)"),u("--patch","With --verify, print the compiler-verified deletion patch to stdout"),u("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:Uu}),$e({id:"recent-duplicates",command:"recent-duplicates",agent:C("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:x([u("--window <n>",'How many commits back counts as "recent"',S,100),u("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",Oe),u("-n, --limit <n>","Maximum findings",S,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:R("Cleanup",["scip-query recent-duplicates --window 50"]),handler:Hu}),$e({id:"doc-drift",command:"doc-drift [doc]",agent:C("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:x([u("-n, --limit <n>","Maximum docs to report",S,20),u("--min-coupling <n>","Minimum historical co-changes to track a subject",S,3),u("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:R("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Qu}),$e({id:"dead",command:"dead [scope]",agent:C("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:x([u("--min-loc <n>","Only show symbols >= N lines",S,1),u("--include-tests","Include definitions from test files (test references always count)"),u("--skip-barrels","Ignore refs from barrel re-export files"),u("--include-members","Include class members"),u("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),u("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["scip-query dead --min-loc 10"]),handler:xu}),$e({id:"unused-imports",command:"unused-imports <file>",agent:C("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:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Cu}),$e({id:"isolated",command:"isolated",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum lines of code",S,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:ku}),re({id:"similar",command:"similar [symbol] [other]",agent:C("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:x([u("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",Oe,.4),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-callees <n>","Minimum callees to consider",S,4),u("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),u("--plan","Render a consolidation preview for two symbols"),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:ju}),re({id:"similar-files",command:"similar-files [file]",agent:C("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:x([u("--min-similarity <n>","Minimum Jaccard similarity (0-1)",Oe,.5),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-deps <n>","Minimum dependencies to consider",S),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Nu}),re({id:"react-component-duplicates",command:"react-component-duplicates [file]",agent:C("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:x([u("--min-similarity <n>","Minimum JSX structure similarity (0-1)",Oe,.62),u("--min-tokens <n>","Minimum structural tokens to consider",S,8),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:zu}),re({id:"react-hook-candidates",command:"react-hook-candidates [file]",agent:C("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:x([u("--min-similarity <n>","Minimum behavior similarity (0-1)",Oe,.45),u("--min-shared-behaviors <n>","Minimum shared behavior tokens",S,6),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Ju}),re({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",agent:C("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:x([u("--min-component-lines <n>","Minimum component lines",S,300),u("--min-file-lines <n>","Minimum file lines",S,800),u("--min-jsx-tokens <n>","Minimum JSX structure tokens",S,80),u("--min-behavior-tokens <n>","Minimum behavior tokens",S,40),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Yu}),re({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",agent:C("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:x([u("--min-similarity <n>","Minimum template similarity (0-1)",Oe,.62),u("--min-tokens <n>","Minimum structural tokens to consider",S,8),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Xu}),re({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",agent:C("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:x([u("--min-similarity <n>","Minimum behavior similarity (0-1)",Oe,.45),u("--min-shared-behaviors <n>","Minimum shared behavior tokens",S,6),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Zu}),re({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",agent:C("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:x([u("--min-total-lines <n>","Minimum total component lines",S,800),u("--min-template-lines <n>","Minimum template lines",S,300),u("--min-script-lines <n>","Minimum script lines",S,300),u("--min-style-lines <n>","Minimum style lines",S,500),u("--review-thresholds","Use lower review thresholds without changing health scoring"),u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:ep}),re({id:"similar-chains",command:"similar-chains",agent:C("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:x([u("--min-similarity <n>","Minimum chain similarity (0-1)",Oe,.5),u("-n, --limit <n>","Number of results",S,15),u("-s, --scope <path>","Limit to files matching path"),u("--min-length <n>","Minimum chain length",S,3),u("--max-length <n>","Maximum chain length",S,8),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Mu}),re({id:"extract-candidates",command:"extract-candidates",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum function LOC",S,10),u("--min-callees <n>","Minimum callees to analyze",S,6),u("-n, --limit <n>","Number of results",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Eu}),re({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",agent:C("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:x([u("-s, --scope <path>","Limit scan mode to files matching path"),u("--min-consumers <n>","Minimum consumers in scan mode",S,1),u("-n, --limit <n>","Number of results",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:R("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:Tu}),re({id:"drift",command:"drift [module]",agent:C("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:x([u("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",pe,5),u("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),u("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),u("-n, --limit <n>","Number of results",S,50),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:Ou}),re({id:"wrapper-candidates",command:"wrapper-candidates",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC for candidates",S,15),u("-n, --limit <n>","Number of results",S,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:Iu}),re({id:"passthrough-candidates",command:"passthrough-candidates",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC for candidates",S,15),u("-n, --limit <n>","Number of results",S,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Au}),re({id:"stale-abstractions",command:"stale-abstractions",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC",S,3),u("-n, --limit <n>","Number of results",S,30),u("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:Pu}),re({id:"complexity-hotspots",command:"complexity-hotspots",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC",S,10),u("-n, --limit <n>","Number of results",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Lu}),$e({id:"convergence",command:"convergence <symbol1> <symbol2>",hidden:!0,agent:C("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:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:Du}),ru({id:"redundant-reexports",command:"redundant-reexports",agent:C("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:[u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",S,30),u("--full","Run unbounded analysis on large indexes")],docs:R("Cleanup"),query:({db:e,opts:t})=>ta(e,{scope:w(t,"scope"),limit:D(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
171
- barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
172
- Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
173
- Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
174
- ${e.length} redundant re-export(s).`)}),$e({id:"duplicate-bodies",command:"duplicate-bodies",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC per function body",S,15),u("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",S,3),u("-n, --limit <n>","Number of groups",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:Fu}),$e({id:"twin-drift",command:"twin-drift",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",Oe,.3),u("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),u("-n, --limit <n>","Number of groups",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:Wu}),re({id:"not-implemented",command:"not-implemented",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",S,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"reachable placeholder stubs",budget:"candidate-scan",renderShape:"list",docs:R("Cleanup",["scip-query not-implemented -s src/services"]),handler:_u}),re({id:"decorative-checkers",command:"decorative-checkers",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",S,30),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"decorative checker candidates",budget:"candidate-scan",renderShape:"list",docs:R("Cleanup",["scip-query decorative-checkers -s src/services"]),handler:Bu}),$e({id:"test-quality",command:"test-quality",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Maximum findings per sub-check",S,30),u("--rot-days <n>","Skips older than this many days are reported as rot",S,60),u("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"test-quality findings"},renderShape:"custom",docs:R("Cleanup",["scip-query test-quality -s tests/queries"]),handler:Gu}),$e({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",agent:C("How do these two twin implementations differ in structure and behavior?","side-by-side symbol evidence and divergence classification",["symbol","symbol"],"complete",void 0,z("mutation")),description:"Generate a behavioral A/B scaffold comparing two same-concept twins (cleanup integrity scenario) \u2014 a ready-to-fill vitest file, not an auto-executor",options:x([u("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),u("--force","Overwrite an existing scaffold file at the output path")]),evidence:"heuristic",renderShape:"custom",docs:R("Cleanup",["scip-query twin-ab src/a.ts/escapeRegex src/b.ts/escapeRegExp"]),handler:Vu}),$e({id:"similar-signatures",command:"similar-signatures",agent:C("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:x([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC per function",S,3),u("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",S,12),u("-n, --limit <n>","Number of groups",S,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:qu})];var Bb=Z(({db:e,args:t,opts:n})=>{let i=Gt(e);if(b(n,"json")){P("stats",t,n,i);return}console.log(`Documents: ${i.documents}`),console.log(`Symbols: ${i.symbols}`),console.log(`Definitions: ${i.definitions}`),console.log(`References: ${i.references}`),console.log(`Index size: ${ce(i.indexSizeBytes)}`),i.lastBuilt&&console.log(`Last built: ${i.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),tp=[{id:"stats",command:"stats",description:"Show index statistics",agent:C("How large and fresh is the current index?","document, symbol, definition, reference, size, and build-time totals",[],"complete","repository"),options:x(),renderShape:"custom",docs:R("Core"),handler:Bb}];var Gb=Ln("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Xr(e,{limit:D(t,"limit",20),scope:w(t,"scope"),minFanIn:k(t,"minFanIn",2),minFanOut:k(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."}),Vb=Z(({db:e,args:t,opts:n})=>{let i=H(t,0),o=D(n,"limit",30);if(i){let c=Ur(e,i);if(b(n,"json")){P("fan-in",t,n,{mode:"symbol",symbol:i,rows:c});return}if(c.length===0)return A.empty(`No fan-in for ${i}.`);A.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let r=Qr(e,{limit:o,scope:w(n,"scope")});if(b(n,"json")){P("fan-in",t,n,{mode:"top",rows:r});return}let s=new Map;for(let c of r)s.set(c.name,(s.get(c.name)??0)+1);let a=new Set([...s].filter(([,c])=>c>1).map(([c])=>c));A.table(["files","symbol"],r.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),Ub=Z(({db:e,args:t,opts:n})=>{let i=H(t,0),o=D(n,"limit",30);if(i){let s=Hr(e,i);if(b(n,"json")){P("fan-out",t,n,{mode:"file",file:i,rows:s});return}if(s.length===0)return A.empty(`No fan-out for ${i}.`);A.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let r=Kr(e,{limit:o,scope:w(n,"scope")});if(b(n,"json")){P("fan-out",t,n,{mode:"top",rows:r});return}A.table(["symbols","file"],r.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),Hb=Z(({db:e,args:t,opts:n})=>{let i=H(t,0),o=H(t,1),r=D(n,"limit",20);if(i&&o){let a=zr(e,i,o);if(b(n,"json")){P("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=Jr(e,{limit:r,scope:w(n,"scope")});if(b(n,"json")){P("coupling",t,n,{mode:"top",rows:s});return}A.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}`))}),Qb=ft({commandName:"cycles",query:({db:e,opts:t})=>Yr(e,{scope:w(t,"scope"),maxDepth:k(t,"maxDepth",10),edgeBasis:b(t,"importsOnly")?"imports":"symbol-references"}),emptyMessage:e=>e.cycles.length===0?`No cycles found in the ${e.edgeBasis} graph.`:void 0,toJson:e=>e,render:e=>{console.log(`Cyclic strongly connected components in the ${e.edgeBasis} graph:`);for(let t=0;t<e.cycles.length;t++){let n=e.cycles[t],i=n.component??[...new Set(n.path.slice(0,-1))].sort();console.log(`
175
- Component ${t+1} (${i.length} files; ${n.classification??n.kind}; one witness follows):`);for(let o=0;o<n.path.length;o++){let r=o<n.path.length-1?" \u2192":" (cycle witness)";console.log(` ${n.path[o]}${r}`)}i.length>new Set(n.path.slice(0,-1)).size&&console.log(` Full component: ${i.join(", ")}`)}console.log(`
176
- ${e.cycles.length} cyclic component(s) found; results are SCC-complete, not all simple cycles.`)}}),Kb=ft({commandName:"architecture",query:({db:e,opts:t})=>Tt(e,{scope:w(t,"scope")}),emptyMessage:e=>e.configured?void 0:"No architecture boundaries configured. Add architecture.boundaries to .scipquery.json.",render:e=>{let t=$t(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.`),t.length===0?console.log("Architecture policy passed."):console.log(`Architecture policy failed with ${t.length} enforced finding(s). Update the code or narrow the declared policy before treating the structure as clean.`),e.policyCoverage.missingRows.length>0){let n=e.policyCoverage.requiresCompletePolicy?" [violates requireCompletePolicy]":"";console.log(`Missing dependency rows: ${e.policyCoverage.missingRows.join(", ")}${n}`)}if(e.coverage.unmappedFiles.length>0){let n=e.policyCoverage.requiresCompleteCoverage?" [violates requireCompleteCoverage]":"";console.log(`Unmapped files: ${e.coverage.unmappedFiles.length}${n}`)}if(e.coverage.ambiguousFiles.length>0){let n=e.policyCoverage.requiresCompleteCoverage?" [violates requireCompleteCoverage]":"";console.log(`Ambiguous files: ${e.coverage.ambiguousFiles.length}${n}`);for(let i of e.coverage.ambiguousFiles.slice(0,5))console.log(` ${i.file} -> ${i.boundaries.join(", ")}`)}if(e.forbiddenEdges.length>0){console.log(`
177
- Forbidden boundary edges (${e.forbiddenEdges.length}):`);for(let n of e.forbiddenEdges){console.log(` ${n.from} -> ${n.to}: ${n.fileEdgeCount} file edge(s), ${n.importerCount} importer(s), ${n.importedFileCount} imported file(s)`);for(let i of n.examples)console.log(` ${i.fromFile} -> ${i.toFile}`)}}else console.log(`
178
- No forbidden dependency edges found.`);if(e.staleAllowances.length>0){let n=e.policyCoverage.requiresMinimalPolicy?" [violates requireMinimalPolicy]":"";console.log(`
179
- Stale dependency allowances (${e.staleAllowances.length}): declared but unused, so the policy is wider than the code requires.${n}`);for(let i of e.staleAllowances)console.log(` ${i.from} -> ${i.to}`)}if(e.boundaryLimits.length>0){console.log(`
180
- Boundaries over configured limits (${e.boundaryLimits.length}):`);for(let n of e.boundaryLimits)console.log(` ${n.boundary}: ${n.kind} ${n.observed} exceeds limit ${n.limit}`)}if(e.testBoundaryViolations.length>0){console.log(`
181
- Test boundary violations (${e.testBoundaryViolations.length}): a test reaches further than the boundary of the code it covers is allowed to reach.`);for(let n of e.testBoundaryViolations.slice(0,20)){let i=n.ownerBoundary??"(no subject found)";console.log(` ${n.testFile} [${i}] -> ${n.importedBoundary} (${n.importedFile})`)}e.testBoundaryViolations.length>20&&console.log(` ... +${e.testBoundaryViolations.length-20} more`)}if(e.fragileEdges.length>0){console.log(`
182
- 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 n of e.fragileEdges.slice(0,10)){let i=n.examples[0];console.log(` ${n.from} -> ${n.to}${i?` (${i.fromFile} -> ${i.toFile})`:""}`)}e.fragileEdges.length>10&&console.log(` ... +${e.fragileEdges.length-10} more`)}if(e.coarseBoundaries.length>0){console.log(`
183
- 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 n of e.coarseBoundaries){console.log(` ${n.boundary}: ${n.subUnits.join(" <-> ")}`);for(let i of n.narrowestEdges){console.log(` narrowest: ${i.from} -> ${i.to} (${i.fileEdgeCount} file edge(s))`);for(let o of i.examples.slice(0,3))console.log(` ${o.fromFile} -> ${o.toFile}`)}}}if(e.edges.length>0){console.log(`
184
- Boundary graph (${e.edges.length} directed edge(s)):`);for(let n of e.edges)console.log(` ${n.from} -> ${n.to} ${n.policyStatus.padEnd(10)} ${n.fileEdgeCount} file edge(s)`)}if(e.reciprocalPairs.length>0){console.log(`
185
- Reciprocal boundary pairs (${e.reciprocalPairs.length}):`);for(let n of e.reciprocalPairs)console.log(` ${n.boundaries[0]} <-> ${n.boundaries[1]} ${n.forward.fileEdgeCount}/${n.reverse.fileEdgeCount} file edge(s)`)}if(e.cycles.length>0){console.log(`
186
- Strongly connected boundary groups (${e.cycles.length}):`);for(let n of e.cycles){let i=n.violatesPolicy?" [violates requireAcyclic]":"";console.log(` { ${n.boundaries.join(", ")} }${i}`);for(let o of n.narrowestEdges)console.log(` inspect ${o.from} -> ${o.to}: ${o.fileEdgeCount} file edge(s)`)}}},after:e=>{$t(e).length>0&&(process.exitCode=1)}});function rp(e){return ft({commandName:e,query:({db:t,opts:n})=>ns(t,{limit:D(n,"limit",10),scope:w(n,"scope"),minDepth:k(n,"minDepth",3),edgeBasis:b(n,"importsOnly")?"imports":"symbol-references"}),emptyMessage:t=>t.length===0?"No deep chains found.":void 0,render:t=>{for(let n=0;n<t.length;n++){console.log(`
187
- Chain ${n+1} (condensed depth ${t[n].depth}; ${t[n].edgeBasis}):`);for(let i of t[n].components){let o=i.length===1?i[0]:`{ ${i.join(", ")} } (cycle)`;console.log(` \u2192 ${o}`)}console.log(` Tier: ${t[n].actionTier} Risk: ${t[n].chainKind}`),console.log(` Recommendation: ${t[n].recommendation}`),console.log(` Evidence: ${t[n].evidenceReasons.join("; ")}`)}}})}var zb=rp("deep-chains"),Jb=rp("dependency-depth"),Yb=Z(({db:e,args:t,opts:n})=>{let i=H(t,0),o=os(e,{search:i,scope:w(n,"scope")});if(b(n,"json")){P("entrypoints",t,n,o,{coverage:{complete:!0,totalKnown:!0,returned:o.length,total:o.length,omitted:0}});return}let r=w(n,"scope");if(console.log(`\u2550\u2550\u2550 REQUEST \u2550\u2550\u2550
188
- text=${i?JSON.stringify(i):"<all>"}; scope=${r??"<repository>"}`),o.length===0){console.log(`
189
- \u2550\u2550\u2550 OBSERVED FACTS \u2550\u2550\u2550
190
- ${i?`No detected entry candidate matched ${JSON.stringify(i)}.`:"No entry candidates were detected."}`),console.log(`
191
- \u2550\u2550\u2550 EVIDENCE CALIBRATION \u2550\u2550\u2550
192
- Absence from this detector does not prove that the repository has no runtime ingress.`),console.log(`
193
- \u2550\u2550\u2550 COVERAGE \u2550\u2550\u2550
194
- Complete within the detector's indexed source/compiler entry evidence.`);return}console.log(`
195
- \u2550\u2550\u2550 OBSERVED FACTS \u2550\u2550\u2550`),A.list(o,s=>` [${s.confidence}] ${s.file}:${j(s.startLine)} ${s.shortName}
196
- evidence: ${s.evidence.join(", ")}; indexed callers: ${s.indexedCallerCount}
197
- symbol: ${s.symbol}`),console.log(`
198
- \u2550\u2550\u2550 EVIDENCE CALIBRATION \u2550\u2550\u2550
199
- [root] has configured, framework-dispatched, Rust public-library, or entry-surface evidence. [candidate] is package-public or lacks indexed callers; neither label proves a runtime invocation.`),console.log(`
200
- \u2550\u2550\u2550 COVERAGE \u2550\u2550\u2550
201
- ${o.length} entry candidate(s); complete within indexed detector evidence.`),console.log(`
202
- \u2550\u2550\u2550 RECOVERY \u2550\u2550\u2550
203
- Any printed exact symbol can be projected with scip-query evidence using the family and direction required by the material question.`)}),Xb=Z(({db:e,args:t,opts:n})=>{let i=N(t,0),o=rs(e,i,{expand:O(n,"expand")});if(b(n,"json")){P("entry-map",t,n,o,{coverage:o.kind==="matched"?{complete:!0,totalKnown:!0,returned:o.regions.length,total:o.regions.length,omitted:0}:{complete:!0,totalKnown:!0,returned:0,total:0,omitted:0}});return}if(o.kind==="missing")return process.exitCode=1,A.empty(`No symbol matched '${i}'.`);if(o.kind==="ambiguous"){process.exitCode=1,console.error(`'${i}' is ambiguous across ${o.total} definitions:`);for(let s of o.candidates)console.error(` ${s.relativePath}:${j(s.startLine)} ${s.shortName}`),console.error(` symbol: ${s.symbol}`);return}if(o.kind==="not-entry")return process.exitCode=1,A.empty(`${o.shortName} (${o.file}) is not a detected entry point. ${o.reason}`);console.log(`Entry: ${o.entry.shortName} (${o.entry.file})`),console.log(`Evidence: ${o.entry.evidence.join(", ")}
204
- `),console.log("\u2550\u2550\u2550 COLLAPSED FILE REGIONS \u2550\u2550\u2550");for(let s of o.regions){let a=s.expanded?"expanded":`expand with --expand '${s.id}'`;console.log(` depth ${s.minDepth} ${s.id}
205
- ${s.symbolCount} symbol(s); ${s.internalEdgeCount} internal edge(s); ${s.externalCallCount} unresolved/external call(s); ${s.incomingRegionIds.length} incoming region(s); ${s.outgoingRegionIds.length} outgoing region(s)
206
- ${a}`)}if(o.regionEdges.length>0){console.log(`
207
- \u2550\u2550\u2550 CROSS-REGION CALLS \u2550\u2550\u2550`);for(let s of o.regionEdges)console.log(` ${s.fromRegionId} \u2192 ${s.toRegionId} (${s.callCount} edge(s); ${s.evidence.join(", ")})
208
- ${s.fromSymbols.join(", ")} \u2192 ${s.toSymbols.join(", ")}`)}let r=o.regions.filter(s=>s.expanded);if(r.length>0){console.log(`
209
- \u2550\u2550\u2550 EXPANDED REGIONS \u2550\u2550\u2550`);for(let s of r){console.log(` ${s.id}`);for(let a of s.symbols)console.log(` depth ${a.depth} ${a.shortName}
210
- ${a.symbol}`);for(let a of s.internalEdges)console.log(` call ${a.fromShortName} \u2192 ${a.toShortName} (${a.source})`);for(let a of s.externalCalls)console.log(` unresolved/external ${a.fromShortName} \u2192 ${a.toShortName} (${a.reportedFile}; ${a.source})`)}}o.unmatchedExpansions.length>0&&console.error(`
211
- Unmatched expansion id(s): ${o.unmatchedExpansions.join(", ")}`),console.log(`
212
- Coverage: ${o.coverage.symbolCount} symbol(s), ${o.coverage.symbolEdgeCount} call edge(s), ${o.coverage.regionCount} region(s), ${o.coverage.externalCallCount} unresolved/external call(s).`),console.log("Complete within indexed static call edges; dynamic dispatch is not represented.")}),Zb=Z(({db:e,args:t,opts:n})=>{let i=O(n,"selectionTerm"),o=Mr(e,{searches:O(n,"search"),symbols:O(n,"symbol"),behaviorFocusLocations:O(n,"focusAt").map(iv),maxDepth:k(n,"depth",5),expand:O(n,"expand"),relations:O(n,"relation"),evidenceFloor:w(n,"evidenceFloor"),sourceScopes:O(n,"sourceScope"),maxTopologyCharacters:k(n,"topologyCharacters",12e3),topologyFrontiers:O(n,"frontier"),routeIds:O(n,"route"),fullLiteralTraversal:b(n,"fullLiteralTraversal"),selectionTerms:i});if(i.length>0&&!b(n,"json")&&console.error("Deprecated: --selection-term is accepted as a no-op; graph selection is explicit and query-neutral."),b(n,"json")){P("system-map",t,n,o,{coverage:{complete:!1,totalKnown:!1,returned:o.regions.length}});return}if(b(n,"gapRecoveryOnly")){ev(o.nextAnchors,O(n,"gapCallee"));return}let r=new Set(o.presentation.regionIds),s=new Set(o.presentation.relationKeys),a=o.regions.filter(p=>r.has(p.id)),c=o.regionRelations.filter(p=>s.has(`${p.fromRegionId}\0${p.toRegionId}`)),l=a.some(p=>p.expanded),d=!!(o.behavior&&o.behavior.steps.length>0);console.log("\u2550\u2550\u2550 EXPLICIT ANCHORS \u2550\u2550\u2550");for(let p of o.anchors){let f=p.kind==="literal"?`${p.matchingLines??0} matching line(s); ${p.seedMatchingLines??0} materialized source seed(s), ${p.matchOnlyLines??0} match-only, ${p.withheldMatchingLines??0} withheld before traversal`:`${p.totalSymbolCandidates??0} candidate definition(s)`;console.log(` [${p.status}] ${p.kind} ${p.query} \u2014 ${f}`),(p.seedRegionIds??[]).length>0&&console.log(` traversal seed regions: ${p.seedRegionIds.join(", ")}`),(p.matchOnlyRegionIds??[]).length>0&&console.log(` retained match-only regions: ${p.matchOnlyRegionIds.join(", ")}`);for(let g of p.representativeMatches??[]){let y=g.ownerShortName?` ${se(g.ownerShortName)}`:"";console.log(` representative: ${g.file}:${j(g.line)}${y} \u2014 ${g.sourceLine.slice(0,160)}`)}for(let g of p.narrowingCommands??[])console.log(` narrow exactly: ${g}`);if(p.exhaustiveTraversalCommand&&console.log(` exhaustive recovery: ${p.exhaustiveTraversalCommand}`),p.kind==="symbol"&&p.matchedRegionIds.length>0&&console.log(` regions: ${p.matchedRegionIds.join(", ")}`),!l){let g=d?(p.symbolCandidates??[]).slice(0,3):p.symbolCandidates??[];for(let y of g)console.log(` ${y.relativePath}:${j(y.startLine)} ${se(y.shortName)}`)}(p.omittedSymbolCandidates??0)>0&&console.log(` ${p.omittedSymbolCandidates} additional candidate(s) omitted by symbol resolution.`)}if(o.topology){let p=new Map(o.topology.nodes.map(T=>[T.id,T])),f=o.topology.nodes.filter(T=>T.disposition==="emitted"),g=o.topology.edges.filter(T=>T.disposition==="emitted"&&T.kind!=="structural-membership"&&T.fromNodeId!==T.toNodeId),y=o.topology.frontiers.filter(T=>T.disposition==="folded");console.log(`
213
- \u2550\u2550\u2550 QUERY CONNECTOR GRAPH \u2550\u2550\u2550`),console.log(` ${f.length}/${o.topology.nodes.length} node(s) selected; ${g.length} typed connector edge(s); ${y.length} reversible frontier group(s).`),o.topology.completion&&console.log(` [${o.topology.completion.status}] ${o.topology.completion.explanation}`);for(let T of o.topology.paths){let W=T.nodeIds.map(E=>p.get(E)?.label??E);console.log(` [${T.status}] ${W.length>0?W.join(" \u2194 "):"no proved connector"}`)}let v=o.topology.routeCatalog;if(v){let T=new Set(v.selectedRouteIds);console.log(` Route catalogue [${v.coverage.status}]: ${v.routes.length} distinct proved public/runtime endpoint route(s); ${v.coverage.enumeration}; depth \u2264 ${v.coverage.maximumDepth}.`);for(let W of v.routes){let E=T.has(W.id)?"; selected":"",B=W.relatedEdgeFamilies.length>0?W.relatedEdgeFamilies.join(","):"control",J=W.nodeIds.map(F=>se(p.get(F)?.label??F)).join(" \u2192 ");console.log(` [${W.id}; ${W.endpointKind}; ${W.edgeIds.length} edge(s); families ${B}${E}] ${J} @ ${W.endpointLocation.file}:${j(W.endpointLocation.line)}`)}v.coverage.anchorsWithoutRoutes.length>0&&console.log(` [no proved public/runtime route] ${v.coverage.anchorsWithoutRoutes.length} anchor node(s): `+v.coverage.anchorsWithoutRoutes.join(", ")),v.routes.length>0&&v.selectedRouteIds.length===0&&console.log(` Select only routes whose interior behavior is a named missing fact; repeat --route to batch: ${nv(n,[])} --route '<route-id>'`)}let $=f.filter(T=>typeof T.attributes.upstreamCausalEndpoint=="string");if($.length>0){console.log(" Upstream causal roots are the earliest source-backed constructs selected on bounded proved paths into the anchors; a traversal root has no earlier proved caller in this query graph and is not necessarily a public application entry.");for(let T of $){let W=T.location?` @ ${T.location.file}:${j(T.location.line)}`:"",E=Number(T.attributes.upstreamCausalDistance??0);console.log(` [${String(T.attributes.upstreamCausalEndpoint)}; ${E} edge(s) to anchor] ${se(T.label)}${W}`)}}let L=d?4:8;for(let T of g.slice(0,L)){let W=p.get(T.fromNodeId)?.label??T.fromNodeId,E=p.get(T.toNodeId)?.label??T.toNodeId,B=[...new Set(T.evidence.map(J=>J.strength))].join("/");console.log(` ${W} \u2192 ${E} \u2014 ${T.kind} [${B}]`)}g.length>L&&console.log(` +${g.length-L} selected connector edge(s).`);let _=y.slice(0,d?1:2);for(let T of _){let W=T.memberNodeIds.slice(0,2).map(E=>p.get(E)?.label??E).join(", ");console.log(` [folded ${T.id}] ${T.memberCount} node(s), ${T.edgeIds.length} edge(s)${W?` \u2014 ${W}`:""}`)}let I=_.find(T=>T.expansion)?.expansion;if(I&&!d){let T=I.replace(/ --frontier '[^']+'$/u,"");console.log(` Expand shown frontiers together: ${T} ${_.map(W=>`--frontier '${W.id}'`).join(" ")}`)}y.length>_.length&&console.log(` +${y.length-_.length} frontier group(s); all exact members and expansion commands remain in the structured result.`),ov(o.topology,o.behavior)}if(o.behavior&&o.behavior.steps.length>0){if(console.log(`
214
- \u2550\u2550\u2550 CONNECTED BEHAVIOR \u2550\u2550\u2550`),console.log(` [${o.behavior.status}] ${o.behavior.steps.length}/${o.behavior.coverage.candidateNodes} selected construct(s); ${o.behavior.transitions.length} evidenced transition(s); ${o.behavior.coverage.withheldStatements} non-connector statement(s) withheld with exact-source recovery.`),o.behavior.coverage.requestedFocusLocations.length>0){console.log(` Question-aligned focus: ${o.behavior.coverage.matchedFocusLocations.length}/${o.behavior.coverage.requestedFocusLocations.length} exact location(s) fell inside selected constructs.`);for(let f of o.behavior.coverage.unmatchedFocusLocations)console.log(` [unmatched focus] ${f.file}:${j(f.line)}`)}console.log(" Read every relevant sibling branch under the explicit anchors before using optional gap recovery; the branch outcomes are jointly required behavior, not alternative search results.");let p=new Map(o.behavior.steps.map(f=>[f.id,f.order+1]));for(let f of o.behavior.steps){let g=f.location?` @ ${f.location.file}:${j(f.location.line)}`:"";if(console.log(` ${f.order+1}. [${f.role}; ${f.kind}] ${se(f.label)}${g}`),!f.behavior)continue;let y=[` [${f.behavior.kind}; ${f.behavior.constructKind}] ${f.behavior.signature} (${f.behavior.renderedCharacters}/${f.behavior.rawCharacters} chars; ${f.behavior.coverage.representedStatements}/${f.behavior.coverage.sourceStatements} detected behavior statements selected)`];for(let v of f.behavior.lines){let $=v.signals.length>0?` [${v.signals.join(",")}]`:"";y.push(` ${j(v.line)}${$} ${" ".repeat(v.depth)}${v.text}`)}for(let v of f.behavior.supportingDeclarations??[]){let $=v.text.replace(/\s*\n\s*/gu," ");y.push(` [support; ${v.kind}] ${v.label} @ ${v.file}:${j(v.line)} \u2014 ${$}`)}for(let v of f.behavior.omittedSupportingDeclarations??[])y.push(` [support omitted; ${v.reason}] ${v.label} @ ${v.file}:${j(v.line)}-${j(v.endLine)}`);console.log(Jt({kind:"unit",identity:f.nodeId,content:y.join(`
215
- `),label:se(f.label),indent:" "}))}if(o.behavior.transitions.length>0){console.log(" Transitions (arrows preserve repository-edge direction):");for(let f of o.behavior.transitions){let g=f.evidence.map(L=>`${L.method}/${L.strength}`).join(", "),y=f.kind==="runtime-boundary"?[...new Set(f.evidence.flatMap(L=>typeof L.identity=="string"&&L.identity.length>0?[L.identity]:[]))]:[],v=p.get(f.fromStepId)??"?",$=p.get(f.toStepId)??"?";console.log(Jt({kind:"edge",identity:f.edgeId,content:` ${v} \u2192 ${$} \u2014 ${f.kind}; path=${f.pathTraversal}; ${g}`+(y.length>0?`; key=${y.join(" | ")}`:""),label:`${v} \u2192 ${$} ${f.kind}`,indent:" "}))}}o.behavior.coverage.omittedNodeIds.length>0&&console.log(` ${o.behavior.coverage.omittedNodeIds.length} bounded emitted construct(s) were not materialized; their identities remain in behavior.coverage.omittedNodeIds.`),o.behavior.exactSourceCommand&&console.log(" Exhaustive exact-source recovery (usually unnecessary; never combine with the drill batch below): "+o.behavior.exactSourceCommand)}if(o.nextAnchors&&o.nextAnchors.candidateAnchors>0){console.log(`
216
- \u2550\u2550\u2550 ADJACENT RECOVERY INVENTORY \u2550\u2550\u2550`);let p=[...o.nextAnchors.anchors,...o.nextAnchors.withheldAnchors],f=new Map;for(let g of p){let y=`${g.direction}/${g.relationKind}/${g.causalRole}`;f.set(y,(f.get(y)??0)+1)}console.log(` ${o.nextAnchors.candidateAnchors} exact or candidate adjacent target(s) are recoverably folded.`);for(let[g,y]of[...f].sort(([v],[$])=>v.localeCompare($)))console.log(` ${g}: ${y}`);console.log(` Select a named missing callee without relevance inference: ${tv(n,["<callee-from-connected-behavior>"])}.`)}if(o.regions.length===0)console.log(`
217
- No structural regions matched the supplied anchors.`);else{console.log(`
218
- \u2550\u2550\u2550 COLLAPSED SYSTEM REGIONS \u2550\u2550\u2550`);for(let p of a){let f=p.expanded?"expanded":"collapsed",g=p.notableSymbols.slice(0,2);if(l){console.log(` d${p.minDepth} [${f}] ${p.id} \u2014 ${p.fileCount} file; ${p.symbolCount} sym; ${p.literalHitCount} hit; ${p.relationKinds.join(",")||"anchor-only"}; ${p.incomingRegionIds.length} in/${p.outgoingRegionIds.length} out${p.memberCallCandidateRelationCount>0?`; ${p.memberCallCandidateRelationCount} M-candidate`:""}`);continue}if(d){console.log(` d${p.minDepth} [${f}] ${p.id} \u2014 ${p.fileCount} file; ${p.symbolCount} sym; ${p.relationKinds.join(",")||"anchor-only"}; ${p.incomingRegionIds.length} in/${p.outgoingRegionIds.length} out`);continue}console.log(` depth ${p.minDepth} [${f}] ${p.id} \u2014 ${p.fileCount} file (${p.sourceFileCount} src/${p.testFileCount} test); ${p.symbolCount} sym; ${p.literalHitCount} hit; ${p.relationKinds.join(",")||"anchor-only"}; ${p.incomingRegionIds.length} in/${p.outgoingRegionIds.length} out${p.memberCallCandidateRelationCount>0?`; ${p.memberCallCandidateRelationCount} M-candidate`:""}
219
- anchors: ${p.anchorQueries.join(", ")||"none"}; drill: ${g.map(y=>`${se(y.shortName)} (${y.file})`).join(", ")||"none"}${p.symbolCount>g.length?`; +${p.symbolCount-g.length}`:""}`)}}if(o.presentation.complete||(console.log(`
220
- \u2550\u2550\u2550 TOPOLOGY WITHHELD MANIFEST \u2550\u2550\u2550`),console.log(` The ${o.presentation.maxCharacters}-character topology budget selected ${o.presentation.regionIds.length}/${o.regions.length} region(s) and ${o.presentation.relationKeys.length}/${o.regionRelations.length} cross-region relation(s).`),o.presentation.omittedRegionIds.length>0&&console.log(` Withheld region ids: ${op(o.presentation.omittedRegionIds,12)}.`),console.log(` Structured JSON retains all facts. Expand the human topology without paging: ${o.presentation.expansionCommand}`)),!l&&!d&&o.expansion?.command&&(console.log(`
221
- \u2550\u2550\u2550 NEXT ABSTRACTION LEVEL \u2550\u2550\u2550`),o.expansion.command)){let p=o.regions.length-o.expansion.regionCount,f=o.expansion.candidateRegionCount??o.expansion.regionCount,g=o.expansion.omittedRegionIds??[];console.log(` Expand ${o.expansion.regionCount}/${f} ranked traversal-relevant region(s) in one complete child-file summary; ${p} other observed region(s) remain visible above.`),console.log(` Expand together: ${o.expansion.command}`),g.length>0&&console.log(` Withheld traversal-relevant regions: ${g.join(", ")}. Add several --expand selectors to the command when they can change the decision.`)}if(c.length>0){console.log(`
222
- \u2550\u2550\u2550 CROSS-REGION RELATIONSHIPS \u2550\u2550\u2550`),d||console.log(" Evidence A=AST callsite; M=source candidate (receiver type unproved); S=semantic callee; C=SCIP chunk; K=cross-workspace contract symbol; I=index/source import; R=index/source reference; B=proven runtime-boundary join.");for(let p of c)console.log(` ${ip(p.fromRegionId)} \u2192 ${ip(p.toRegionId)} \u2014 ${p.relationCount} rel [${p.kinds.join(",")}; ${p.evidence.map(mv).join(",")}]`)}if(o.boundaryFrontiers.length>0){console.log(`
223
- \u2550\u2550\u2550 UNRESOLVED RUNTIME BOUNDARIES \u2550\u2550\u2550`);let p=lv(o.boundaryFrontiers),f=p.slice(0,d?3:8);for(let g of f){let y=g.frontiers.slice(0,d?1:2).map(v=>`${dv(v.address)} @ ${v.file}:${j(v.line)}`);console.log(` [${g.strength}] ${g.action} \xD7${g.frontiers.length} \u2014 ${y.join("; ")}`),d||console.log(` ${g.reason}`)}p.length>f.length&&console.log(` ${p.length-f.length} additional frontier bucket(s); every observation and reason remains in --json.`),d&&console.log(" These are disclosed candidate observations, not proven connector edges; expand only when a named missing fact crosses one of them.")}o.externalBoundaries.length>0&&(console.log(`
224
- \u2550\u2550\u2550 EXTERNAL IMPORT BOUNDARIES \u2550\u2550\u2550`),console.log(d?` ${o.externalBoundaries.length} imported external symbol(s) remain accounted in the structured result.`:` ${o.externalBoundaries.length} imported external symbol(s): ${op(o.externalBoundaries.map(p=>p.name),12)}. Use --json when the complete external-import list can change the decision.`));let m=a.filter(p=>p.expanded);if(m.length>0){console.log(`
225
- \u2550\u2550\u2550 EXPANDED REGIONS \u2550\u2550\u2550`),console.log(" Every child file is listed. d=depth; S/T/E/B/W=source/test/entry/barrel/worker; sym/hit/rel counts are complete; C/I/R/B=call/import/reference/runtime-boundary; x=connected-region count; final names are ranked symbol@line drill candidates.");for(let p of m)console.log(` ${p.label} (${p.id})`),cv(p);o.drilldown?.command&&(console.log(`
226
- \u2550\u2550\u2550 BATCHED DRILL-DOWN \u2550\u2550\u2550`),console.log(` ${o.drilldown.selectedAnchors}/${o.drilldown.candidateAnchors} coverage-diverse child-file anchor(s) selected${o.drilldown.omittedAnchors>0?`; ${o.drilldown.omittedAnchors} withheld by the ranked drill-down budget and still listed above`:""}.`),console.log(` Inspect the selected behavior together: ${o.drilldown.command}`),o.drilldown.definitionCommand&&console.log(` Full-source escalation for the selected exact units: ${o.drilldown.definitionCommand}`))}o.unmatchedExpansions.length>0&&console.error(`
227
- Unmatched expansion id(s): ${o.unmatchedExpansions.join(", ")}`),console.log(`
228
- Query plan: relations=${o.coverage.requestedRelationKinds.join(",")}; evidence>=${o.coverage.evidenceFloor}; scopes=${o.coverage.includedSourceScopes.join(",")}.`),console.log(`Query closure: ${o.closure.status}; emitted ${o.closure.emitted.regions} region(s), ${o.closure.emitted.relations} relation(s), and ${o.closure.emitted.runtimeLinks} runtime link(s); withheld ${o.closure.withheld.symbols} symbol(s), ${o.closure.withheld.files} file(s), ${o.closure.withheld.regions} region(s), and ${o.closure.withheld.drillAnchors} drill anchor(s); ${o.closure.ambiguous.anchors} ambiguous anchor(s), ${o.closure.external} external boundary(ies), ${o.closure.unresolved} unresolved runtime frontier(s).`),console.log(` ${o.closure.explanation}`),console.log(`
229
- Coverage: ${o.coverage.matchedAnchorCount}/${o.coverage.explicitAnchorCount} anchor(s) matched; ${o.regions.length} region(s); depth ${o.coverage.maxTraversalDepth}; ${o.coverage.frontierSymbols} untraversed symbol(s); ${o.coverage.frontierFiles} untraversed file(s); ${o.coverage.supportFilesNotTraversed} visible support file(s) not traversed; ${o.coverage.filteredUnverifiedCallEdges} unverified call edge(s) filtered; ${o.coverage.memberCallCandidateEdges} source-attributed member-call candidate edge(s); ${o.coverage.unresolvedMemberCallsites} unresolved member callsite(s); ${o.coverage.runtimeBoundaryTraversedLinks}/${o.coverage.runtimeBoundaryExactLinks+o.coverage.runtimeBoundaryDerivedLinks} map-relevant proven runtime-boundary link(s) traversed (${o.coverage.repositoryRuntimeBoundaryExactLinks+o.coverage.repositoryRuntimeBoundaryDerivedLinks} repository-wide); ${o.coverage.runtimeBoundaryCandidateLinks} candidate boundary link(s); ${o.coverage.runtimeBoundaryFrontiers} relevant unresolved boundary frontier(s); ${o.coverage.referenceExpansionEligibleSymbols} symbol(s) reverse-expanded and ${o.coverage.referenceExpansionSkippedSymbols} discovered symbol(s) not reverse-expanded.`),o.coverage.symbolCandidateSetsComplete||console.log(`Symbol resolution omitted ${o.coverage.omittedSymbolCandidates} ambiguous candidate(s).`),console.log("Blind spots:");let h=d?o.coverage.blindSpots.slice(0,2):o.coverage.blindSpots;for(let p of h)console.log(` - ${p}`);if(o.coverage.blindSpots.length>h.length&&console.log(` - ${o.coverage.blindSpots.length-h.length} additional disclosed limitation(s) remain in coverage.blindSpots.`),d){let p=new Map([["branch conditions",new Map],["structured payloads",new Map],["terminal outcomes",new Map]]);for(let f of o.behavior?.steps??[])if(!(!f.location||!f.behavior))for(let g of f.behavior.lines){let y=`${f.location.file}:${j(g.line)}`;g.signals.includes("branch")&&p.get("branch conditions")?.set(y,null),g.signals.includes("shape")&&(g.signals.includes("call")||g.signals.includes("mutation")||g.signals.includes("return"))&&p.get("structured payloads")?.set(y,g.text.replace(/\s*\n\s*/gu," ")),(g.signals.includes("return")||g.signals.includes("throw"))&&p.get("terminal outcomes")?.set(y,null)}console.log(`
230
- \u2550\u2550\u2550 ANSWER EVIDENCE CONTRACT \u2550\u2550\u2550`),console.log(" Before another query, account for each question-relevant condition and outcome already rendered above. Preserve exact ownership/lifetime (including singleton/shared/per-invocation scope), normalization and path rules, invocation arguments, working directory and standard I/O, bounds/defaults, returned fields or instructions, every condition that stops or continues the enclosing loop, policy or dispatch precedence and bypass scope, and rethrown-versus-rendered interruption behavior."),console.log(" Draft audit locations are mechanically derived from selected syntax. For every category material to the question, explicitly account for every listed location:");for(let[f,g]of p)if(g.size!==0)if(f==="structured payloads"){console.log(` Draft audit \u2014 ${f}:`);for(let[y,v]of g)console.log(` ${y} \u2014 ${v??""}`)}else console.log(` Draft audit \u2014 ${f}: ${[...g.keys()].join(", ")}`);console.log(" No causal target is automatically recommended. Use the adjacent recovery inventory only for a named material fact with no rendered evidence; otherwise answer from the map.")}});function ev(e,t){if(console.log("\u2550\u2550\u2550 OPTIONAL GAP RECOVERY (ONLY AFTER NAMING A MISSING FACT) \u2550\u2550\u2550"),!e||e.candidateAnchors===0){console.log(" No causal drill targets were resolved from the connected behavior.");return}if(t.length===0)throw new Error("--gap-recovery-only requires at least one --gap-callee named in connected behavior.");let n=new Set(t.map(np)),i=[...e.anchors,...e.withheldAnchors].filter(r=>[r.callsite.calleeLeaf,...r.alternatives.map(s=>s.label)].some(s=>n.has(np(s))));if(i.length===0){console.log(` No resolved target matched ${t.map(ee).join(", ")}. Copy callee names exactly from connected behavior.`);return}console.log(` ${i.length}/${e.candidateAnchors} causal target(s) matched the named callee selector(s); no English intent inferred.`);for(let r of i){let s=r.alternatives[0],a=s?`${se(s.label)} @ ${s.file}:${j(s.line)}`:r.callsite.calleeLeaf,c=r.callsite.signals.filter(d=>d!=="anchor"&&d!=="call").join(","),l=[r.direction,r.causalRole,r.relationKind].filter(Boolean).join("; ");if(console.log(` [${r.status}; ${r.source}${l?`; ${l}`:""}${c?`; ${c}`:""}] ${a}${r.alternativeCount>1?` \u2014 ${r.alternativeCount} possible identities`:""}`),console.log(` from ${se(r.fromLabel)} @ ${r.callsite.file}:${j(r.callsite.line)} \u2014 `+r.callsite.text.slice(0,220)),r.alternativeCount>1)for(let d of r.alternatives)console.log(` candidate: ${se(d.label)} @ ${d.file}:${j(d.line)}`)}let o=new Map;for(let r of i){if(r.alternativeCount!==1)continue;let s=r.alternatives[0];s&&o.set(`${s.file}:${s.line}`,s)}o.size>0&&console.log(` Inspect named targets together: scip-query inspect ${[...o.values()].map(r=>`--at ${ee(`${r.file}:${j(r.line)}`)}`).join(" ")} --view behavior`),i.some(r=>r.source==="leaf-identity-candidate"||r.status==="ambiguous")&&console.log(" Identity candidates locate possible definitions but do not prove the receiver-to-callee edge; confirm before making a relationship claim.")}function tv(e,t=O(e,"gapCallee")){let n=["scip-query","system-map"];for(let o of O(e,"search"))n.push("--search",ee(o));for(let o of O(e,"symbol"))n.push("--symbol",ee(o));for(let o of O(e,"focusAt"))n.push("--focus-at",ee(o));n.push("--depth",String(k(e,"depth",5)));for(let o of O(e,"relation"))n.push("--relation",ee(o));let i=w(e,"evidenceFloor");i&&n.push("--evidence-floor",ee(i));for(let o of O(e,"sourceScope"))n.push("--source-scope",ee(o));b(e,"fullLiteralTraversal")&&n.push("--full-literal-traversal");for(let o of O(e,"expand"))n.push("--expand",ee(o));for(let o of O(e,"frontier"))n.push("--frontier",ee(o));for(let o of O(e,"route"))n.push("--route",ee(o));for(let o of t)n.push("--gap-callee",ee(o));return n.push("--gap-recovery-only"),n.join(" ")}function nv(e,t){let n=["scip-query","system-map"];for(let o of O(e,"search"))n.push("--search",ee(o));for(let o of O(e,"symbol"))n.push("--symbol",ee(o));for(let o of O(e,"focusAt"))n.push("--focus-at",ee(o));n.push("--depth",String(k(e,"depth",5)));for(let o of O(e,"relation"))n.push("--relation",ee(o));let i=w(e,"evidenceFloor");i&&n.push("--evidence-floor",ee(i));for(let o of O(e,"sourceScope"))n.push("--source-scope",ee(o));b(e,"fullLiteralTraversal")&&n.push("--full-literal-traversal");for(let o of O(e,"expand"))n.push("--expand",ee(o));for(let o of O(e,"frontier"))n.push("--frontier",ee(o));for(let o of t)n.push("--route",ee(o));return n.join(" ")}function np(e){let t=e.replace(/\(\)$/u,"").replace(/^#/u,"");return(t.slice(Math.max(t.lastIndexOf(":"),t.lastIndexOf("."))+1)||t).toLocaleLowerCase()}function iv(e){let t=e.match(/^(.+):(\d+)$/u),n=t?Number(t[2]):Number.NaN;if(!t||!Number.isSafeInteger(n)||n<=0)throw new Error(`Invalid --focus-at location '${e}'; expected path:line with a positive line number.`);return{file:t[1],line:n-1}}function ov(e,t){let n=e.corridor;if(!n)return;let i=new Map(e.nodes.map(p=>[p.id,p])),o=new Map(e.edges.map(p=>[p.id,p])),r=p=>p.map(f=>se(i.get(f)?.label??f)).join(", "),s=new Map,a=new Map;for(let p of t?.steps??[]){if(!p.location||!p.behavior)continue;let f=a.get(p.location.file)??[];f.push(...p.behavior.lines.map(g=>({line:g.line,endLine:g.endLine}))),a.set(p.location.file,f)}let c=p=>p?.location?(a.get(p.location.file)??[]).some(f=>p.location.line>=f.line&&p.location.line<=f.endLine):!1,l=new Map,d=new Map,m=[],h=new Map;for(let p of n.edgeIds){let f=o.get(p);if(f)for(let g of f.semantics??[])if(g.family==="identity"){let y=s.get(f.fromNodeId)??[];y.push(f.toNodeId),s.set(f.fromNodeId,y)}else if(g.family==="control"&&!wo(g.subtype)){let y=i.get(f.fromNodeId),v=i.get(f.toNodeId),$=typeof y?.attributes.ownerNodeId=="string"?y.attributes.ownerNodeId:f.fromNodeId;if(c(y)&&c(v)){let T=l.get($)??new Map;T.set(g.subtype,(T.get(g.subtype)??0)+1),l.set($,T);continue}let L=d.get($)??new Map,_=L.get(f.fromNodeId)??{controllerLabel:y?.label??se(f.fromNodeId),controllerLocation:y?.location?{file:y.location.file,line:y.location.line}:null,outcomes:new Map},I=_.outcomes.get(g.subtype)??new Set;I.add(v?.label??se(f.toNodeId)),_.outcomes.set(g.subtype,I),L.set(f.fromNodeId,_),d.set($,L)}else if(rv(g.family,g.subtype)){let y=sv(f.fromNodeId,i),v=`${g.family}\0${g.subtype}\0${y.label}`,$=h.get(v)??{family:g.family,subtype:g.subtype,ownerLabel:y.label,ownerLocation:y.location,count:0,targetLabels:new Set,values:new Set};$.count+=1,$.targetLabels.add(se(i.get(f.toNodeId)?.label??f.toNodeId));let L=g.attributes?.value;(typeof L=="string"||typeof L=="number"||typeof L=="boolean")&&$.values.add(String(L)),h.set(v,$)}else m.push({edge:f,semantic:g})}console.log(`
231
- \u2550\u2550\u2550 CAUSAL CORRIDOR \u2550\u2550\u2550`),console.log(` [${n.status}] ${n.startNodeIds.length} anchor node(s) \u2192 ${n.outcomeNodeIds.length} mechanical outcome(s); ${n.coverage.protectedNodes} protected node(s), ${n.coverage.protectedEdges} protected edge(s).`),console.log(` Starts: ${r(n.startNodeIds)||"none proved"}`),console.log(` Outcomes: ${av(n.outcomeNodeIds,e)}`);for(let[p,f]of[...s].sort(([g],[y])=>g.localeCompare(y))){let g=new Map;for(let v of new Set(f)){let $=i.get(v)?.kind??"unknown";g.set($,(g.get($)??0)+1)}let y=[...g].sort(([v],[$])=>v.localeCompare($)).map(([v,$])=>`${v}\xD7${$}`).join(", ");console.log(` [owns] ${r([p])} \u2192 ${new Set(f).size} local construct(s) [${y}]`)}for(let[p,f]of[...l].sort(([g],[y])=>g.localeCompare(y))){let g=[...f].sort(([y],[v])=>y.localeCompare(v)).map(([y,v])=>`${y}\xD7${v}`).join(", ");console.log(` [local-control] ${r([p])} \u2014 ${g}; exact decisions are represented below`)}for(let[p,f]of[...d].sort(([g],[y])=>g.localeCompare(y)))for(let g of[...f.values()].sort((y,v)=>(y.controllerLocation?.file??"").localeCompare(v.controllerLocation?.file??"")||(y.controllerLocation?.line??-1)-(v.controllerLocation?.line??-1)||y.controllerLabel.localeCompare(v.controllerLabel))){let y=[...g.outcomes].sort(([$],[L])=>$.localeCompare(L)).flatMap(([$,L])=>[...L].sort().map(_=>`${$} \u2192 ${_}`)).join("; "),v=g.controllerLocation?` @ ${g.controllerLocation.file}:${j(g.controllerLocation.line)}`:"";console.log(` [local-control] ${r([p])}: ${g.controllerLabel} \u2014 ${y}${v}`)}for(let p of[...h.values()].sort((f,g)=>f.ownerLabel.localeCompare(g.ownerLabel)||f.family.localeCompare(g.family)||f.subtype.localeCompare(g.subtype))){let f=p.family==="control"?`; targets=[${[...p.targetLabels].sort().join(", ")}]`:p.family==="data"&&p.subtype==="constant-to-parameter"?`; values=[${[...p.values].sort().join(", ")}]`:p.family==="data"?`; ${p.targetLabels.size} parameter target(s)`:"",g=p.ownerLocation?` @ ${p.ownerLocation.file}:${j(p.ownerLocation.line)}`:"";console.log(` [${p.family}:${p.subtype}; grouped] ${p.ownerLabel} \u2014 ${p.count} proved edge(s)${f}${g}`)}for(let{edge:p,semantic:f}of m){let g={...f.context??{},...f.attributes??{}},y=Object.entries(g).map(([$,L])=>`${$}=${String(L)}`).join(", "),v=p.evidence.find($=>$.location)?.location;console.log(` [${f.family}:${f.subtype}] ${r([p.fromNodeId])} \u2192 ${r([p.toNodeId])}${y?`; ${y}`:""}${v?` @ ${v.file}:${j(v.line)}`:""}`)}console.log(` Frontier manifest: ${n.accountedFrontierIds.length} accounted; ${n.unresolvedFrontierIds.length} unsupported; ${n.unresolvedEdgeIds.length} candidate/unknown edge(s).`),h.size>0&&console.log(" Grouped edge identities remain in the structured corridor; inspect a named owner only when that flow is material."),n.status==="incomplete"&&console.log(` ${n.explanation}`)}function rv(e,t){return e==="control"&&wo(t)||e==="data"&&["argument-to-parameter","constant-to-parameter"].includes(t)||e==="temporal"&&["await-completion-before","awaits-completion","lexical-successor"].includes(t)}function sv(e,t){let n=t.get(e),i=typeof n?.attributes.ownerNodeId=="string"?n.attributes.ownerNodeId:null,o=i?t.get(i):null,r=typeof n?.attributes.ownerSymbol=="string"?n.attributes.ownerSymbol:null;return{label:se(o?.label??r??n?.label??e),location:o?.location??n?.location??null}}function wo(e){return["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e)}function av(e,t){if(e.length===0)return"none proved";let n=new Set(e),i=new Map(t.nodes.map(l=>[l.id,l])),o=new Set,r=new Set,s=0,a=0,c=new Set;for(let l of t.edges)if(n.has(l.toNodeId))for(let d of l.semantics??[])d.family==="state"?(o.add(se(i.get(l.toNodeId)?.label??l.toNodeId)),c.add(l.toNodeId)):d.family==="control"&&wo(d.subtype)?(r.add(se(i.get(l.toNodeId)?.label??l.toNodeId)),c.add(l.toNodeId)):d.family==="control"&&d.subtype==="returns"?(s+=1,c.add(l.toNodeId)):d.family==="control"&&d.subtype==="throws"&&(a+=1,c.add(l.toNodeId));return[r.size>0?`navigation=[${[...r].sort().join(", ")}]`:"",o.size>0?`resources=[${[...o].sort().join(", ")}]`:"",s>0?`return\xD7${s}`:"",a>0?`throw\xD7${a}`:"",e.length>c.size?`other-causal-sink\xD7${e.length-c.size}`:""].filter(Boolean).join("; ")}function ee(e){return`'${e.replaceAll("'","'\\''")}'`}function cv(e){let t=Ii(e.symbols,o=>o.file),n=Ii(e.literalHits,o=>o.file),i=new Map;for(let o of e.relations)for(let r of new Set([o.fromFile,o.toFile])){if(!e.files.some(a=>a.file===r))continue;let s=i.get(r)??[];s.push(o),i.set(r,s)}for(let o of e.files){let r=(t.get(o.file)??[]).sort(Nr),s=n.get(o.file)??[],a=i.get(o.file)??[],c=r.slice(0,4),l=[...new Set(a.map(h=>h.kind))].sort(),d=[...new Set(a.flatMap(h=>[h.fromRegionId,h.toRegionId].filter(p=>p!==e.id)))].sort(),m=c.length>0?c.map(h=>`${se(h.shortName)}@${j(h.startLine)}`).join(", ")+(r.length>c.length?`; +${r.length-c.length}`:""):"none";console.log(` d${o.depth} ${uv(o.kind)} ${o.file} | sym${r.length} hit${s.length} rel${a.length}${l.length>0?`:${l.map(pv).join("/")}`:""} x${d.length} | ${m}`);for(let h of s)console.log(` literal ${h.query}@${j(h.line)} ${h.sourceLine}`)}}function se(e){return e.split(":").at(-1)||e}function lv(e){let t=new Map;for(let n of e){let i=`${n.strength}\0${n.action}\0${n.reason}`,o=t.get(i)??{action:n.action,strength:n.strength,reason:n.reason,frontiers:[]};o.frontiers.push(n),t.set(i,o)}return[...t.values()].sort((n,i)=>i.frontiers.length-n.frontiers.length||n.action.localeCompare(i.action))}function dv(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=120?t:`${t.slice(0,117)}...`}function ip(e){return e.replace(/^region:(?:apps|packages)\//,"")}function uv(e){return{source:"S",test:"T",entry:"E",barrel:"B",worker:"W"}[e]??e}function pv(e){return{call:"C","contract-symbol":"K",import:"I",reference:"R","runtime-boundary":"B"}[e]??e}function mv(e){return e.startsWith("runtime-boundary:")?`B:${e.slice(17)}`:{"ast-callsite":"A","ast-member-import-candidate":"M","compiler-cross-workspace-symbol":"K","semantic-callee":"S","scip-chunk":"C","indexed-or-source-import":"I","indexed-or-source-reference":"R"}[e]??e}function op(e,t){let n=e.slice(0,t);return`${n.join(", ")}${e.length>n.length?`; ${e.length-n.length} more`:""}`}var sp=[ei({id:"hotspots",command:"hotspots",description:"Rank symbols by cross-file reference count; a reference metric, not runtime contention",agent:C("Which symbols have the most observed cross-file reference evidence?","ranked symbol identities with explicit evidence basis and counting units",[],"bounded","repository"),options:[u("-n, --limit <n>","Number of results",S,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")],docs:R("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>Wr(e,{limit:D(t,"limit",30),scope:w(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:{...st("How many files reference this symbol, or which symbols have highest fan-in?","exact symbols with referencing-file counts",["symbol"],"bounded","repository",fe,At(["symbol","construct"],["Entry-point detection reports evidenced external roots and candidates; it does not establish task relevance."])),resultUnits:{kind:"field",field:"rows"}},options:x([u("-n, --limit <n>","Number of results for top mode",S,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Vb},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",agent:C("How many external symbols does this file use, or which files have highest fan-out?","files with external-symbol counts",["file"],"bounded","repository"),options:x([u("-n, --limit <n>","Number of results for top mode",S,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Ub},{id:"coupling",command:"coupling [file1] [file2]",description:"Count shared-symbol coupling between two files, or rank file pairs by that metric",agent:C("How strongly are these files coupled, or which pairs are most coupled?","file pairs with coupling evidence and scores",["file","file"],"bounded","repository"),options:x([u("-n, --limit <n>","Number of results for top mode",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Hb},{id:"cycles",command:"cycles",description:"Find every cyclic file-dependency component and show one deterministic witness for each",agent:C("Which file dependency cycles exist?","dependency-cycle file chains",[],"complete","repository"),options:x([u("-s, --scope <path>","Limit to files matching path"),u("--imports-only","Analyze only resolved file imports instead of all cross-file symbol references"),u("--max-depth <n>","Deprecated compatibility option; SCC detection no longer truncates by depth",S,10)]),renderShape:"custom",docs:R("Graph"),handler:Qb},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",agent:C("Does the repository obey its declared architecture boundaries?","boundary coverage and dependency-rule violations",[],"complete","repository"),options:x([u("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",claims:Je(["index-generation","live-workspace"],[X("declared-policy","boundaries","repository-source"),X("dependency-observations","edges","compiler-graph"),X("policy-findings","forbiddenEdges","compiler-graph")]),renderShape:"custom",docs:R("Graph",["scip-query architecture --json"]),handler:Kb},{id:"bottlenecks",command:"bottlenecks",description:"Rank coordination hubs by incoming evidence files \xD7 outgoing cross-file callable targets",agent:C("Which callable symbols are high-connectivity coordination hubs?","ranked callable symbols with incoming evidence-file and outgoing callable-target counts",[],"bounded","repository"),options:x([u("-n, --limit <n>","Number of results",S,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-fan-in <n>","Minimum fan-in",S,2),u("--min-fan-out <n>","Minimum fan-out",S,2),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:R("Graph"),handler:Gb},{id:"deep-chains",command:"deep-chains",hidden:!0,description:"Deprecated alias for dependency-depth",agent:C("Which dependency chains are deepest and riskiest?","ranked component chains with depth, risk, and recommendation",[],"bounded","repository"),options:x([u("-n, --limit <n>","Number of chains to show",S,10),u("-s, --scope <path>","Limit to files matching path"),u("--min-depth <n>","Minimum chain depth",S,3),u("--imports-only","Measure the import graph instead of the symbol-reference dependency graph"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:zb},{id:"dependency-depth",command:"dependency-depth",description:"Find longest paths through the SCC-condensed file dependency graph",agent:C("Which file dependency paths have the greatest condensed depth?","ranked component paths with full cycle membership, edge basis, and condensed depth",[],"bounded","repository"),options:x([u("-n, --limit <n>","Number of paths to show",S,10),u("-s, --scope <path>","Limit to files matching path"),u("--min-depth <n>","Minimum condensed component depth",S,3),u("--imports-only","Measure the import graph instead of the symbol-reference dependency graph"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:R("Graph"),handler:Jb},{id:"entrypoints",command:"entrypoints [text]",description:"Find callables where control may enter from outside the indexed call graph",agent:{...st("Which detected external roots or entry-surface candidates match this text?","entry symbols with files, confidence, evidence, and indexed caller counts",["pattern"],"complete","repository",fe,At(["symbol","construct"],["A package-public export or zero indexed callers is an entry candidate, not proof of runtime ingress.","Entry classification does not establish that the callable executes."],{ranking:"identity-only",manualInput:"Optional exact text to filter candidates; otherwise the current indexed repository.",evidenceCeiling:"Source/compiler-grounded entry evidence and indexed caller counts; exported-only candidates remain candidates.",outputCost:"bounded",frontierClosure:["evidence","inspect","code"]})),contrasts:[{command:"entry-map",distinction:"entrypoints locates possible external roots; entry-map traverses static calls from one selected root."},{command:"search",distinction:"entrypoints classifies callable roots; search only locates exact text and ownership."}]},options:x([u("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:R("Graph",["scip-query entrypoints","scip-query entrypoints work-session"]),handler:Yb},{id:"entry-map",command:"entry-map <entry>",description:"Map the complete indexed call graph from one detected entry point, collapsed by file",agent:{...st("What statically reachable call structure begins at this detected entry point?","all reachable file regions, cross-region call edges, coverage, and selected expanded symbol details",["symbol"],"complete",void 0,fe,Yt({rootKinds:["symbol","construct"],edgeFamilies:["execution"],directions:["outgoing"],operations:["reachability"],compression:["topology"],nonClaims:["Static may-call reachability does not establish runtime execution."]})),contrasts:[{command:"entrypoints",distinction:"entry-map traverses one selected root; entrypoints locates and classifies candidate roots."},{command:"evidence",distinction:"entry-map is outgoing execution reachability; evidence projects explicitly selected families and directions."}]},options:x([u("--expand <region-id>","Expand one file region; repeat to expand several together",U,[])]),renderShape:"custom",docs:R("Graph",["scip-query entry-map start","scip-query entry-map start --expand 'file:src/routes.ts' --expand 'file:src/store.ts'"]),handler:Xb},{id:"system-map",command:"system-map",hidden:!0,description:"Deprecated compatibility view for collapsed regions and legacy route catalogues; use evidence",agent:st("Which components and proven compiler or runtime relationships connect these explicit literals or symbols?","all matched anchors, collapsed structural regions, compiler and exact runtime relationships, unresolved boundary frontiers, simultaneous drilldown summaries, and explicit coverage gaps",[],"bounded","repository",fe,Yt({rootKinds:["text","symbol","construct","runtime-key"],edgeFamilies:ot,directions:["incoming","outgoing","both"],operations:["reachability","connecting"],compression:["topology"],nonClaims:["Legacy region and next-anchor ranking does not establish task relevance.","Structural region membership does not establish execution."],compatibility:"deprecated"})),options:x([u("--search <literal>","Add an exact indexed-source anchor; repeat to include several",U,[]),u("--symbol <symbol>","Add a symbol anchor; repeat to include several",U,[]),u("--focus-at <file:line>","Focus connected behavior at one exact source location inside a selected construct; repeat to include several",U,[]),u("--depth <n>","Traverse this many relationship levels",S,5),u("--relation <kind>","Traverse one relation family; repeat for call, contract-symbol, import, reference, or runtime-boundary",U,[]),u("--evidence-floor <floor>","Runtime evidence floor: exact or derived"),u("--topology-characters <n>","Soft character budget for the first human topology view; complete JSON facts remain available",S,12e3),u("--source-scope <scope>","Include one source scope; repeat for production, test, fixture, example, generated, script, or unknown",U,[]),u("--full-literal-traversal","Traverse every literal match after deliberately accepting broad-selector expansion"),u("--expand <region-id>","Expand one structural region; repeat to expand several together",U,[]),u("--frontier <frontier-id>","Expand one accounted topology frontier; repeat to expand several together",U,[]),u("--route <route-id>","Select one proved upstream route; repeat to materialize several routes together",U,[]),u("--gap-callee <name>","Resolve one callee already shown in connected behavior; repeat to batch a named gap",U,[]),u("--selection-term <term>","Deprecated no-op retained for command compatibility; query vocabulary no longer changes graph selection",U,[]),u("--gap-recovery-only","Render only the --gap-callee targets and one exact batched recovery command")]),evidence:"mixed",claims:Je(["index-generation","live-workspace"],[X("matched-anchors","anchors","compiler-graph"),X("typed-relations","regionRelations","repository-source"),X("structural-grouping","regions","heuristic"),X("coverage","coverage","repository-source")]),renderShape:"custom",docs:R("Compatibility"),handler:Zb},xt({id:"call-graph",command:"call-graph <symbol>",description:"Show static may-call edges with exact/candidate evidence and explicit blind spots",agent:C("Who calls this symbol and what does it call?","caller and callee symbol identities, files, evidence strengths, and static-analysis blind spots",["symbol"],"bounded"),options:[u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:R("Graph"),query:({db:e,args:t,budget:n})=>Ut(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:me(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(de(t,String(n[0])),console.log(`Symbol: ${e.shortName}
232
- `))},toJson:(e,{db:t,args:n})=>Ae(t,String(n[0]),e,"callGraph"),sections:e=>e?[{title:`CALLERS (${e.callers.length})`,rows:e.callerEvidence?e.callerEvidence.map(t=>` [${t.evidenceStrength}:${t.relationship}] ${t.file} ${t.shortName} (${t.evidenceSource})`):e.callers.map(t=>` ${t.file} ${t.shortName}`)},{title:`CALLEES (${e.callees.length})`,rows:e.calleeEvidence?e.calleeEvidence.map(t=>` [${t.evidenceStrength}:${t.relationship}] ${t.file} ${t.shortName} (${t.evidenceSource})`):e.callees.map(t=>` ${t.file} ${t.shortName}`)},{title:"COVERAGE",rows:e.coverage?[` ${e.coverage.scope}`,...e.coverage.blindSpots.map(t=>` Blind spot: ${t}`)]:[" Legacy result: explicit static-analysis coverage was not reported."]}]:[]})];var hv=te("complexity",({db:e,args:t,opts:n,budget:i})=>{let o=N(t,0),r=Os(e,o,{semantic:i.semantic});if(b(n,"json")){P("complexity",t,n,Ae(e,o,r,"complexity"),{analysisBudget:i.analysisBudget});return}if(!r)return A.empty(me(e,o,"Symbol not found."));de(e,o),console.log(`${V(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
233
- `),console.log(` LOC: ${r.loc}`),console.log(` Branches: ${r.branches}`),console.log(` Cyclomatic estimate: ${r.cyclomaticEstimate}`),console.log(` Callees: ${r.calleeCount}`),console.log(` Fan-in: ${r.fanIn}`),console.log(` Fan-out: ${r.fanOut}`)}),fv=Z(({db:e,args:t,opts:n})=>{let i=na(e,{samples:k(n,"samples",50),scope:w(n,"scope")});if(b(n,"json")){P("self-audit",t,n,i);return}if(!i.available)return A.empty("No semantic or source-backed oracle available to audit against.");let o=i.oracleKind==="source"?"source facts":"compiler semantics";console.log(`Sampled ${i.sampleSize} symbols; ${o} oracle answered ${Math.round(i.oracleCoverage*100)}%.
234
- `),console.log(`Agreement with ${o} (file-level):`);for(let r of i.scores){let s=r.precision===null?`unverified ${r.unverified} (oracle partial \u2014 no precision claim)`:`precision ${r.precision}`;console.log(` ${r.question.padEnd(11)} ${s} recall ${r.recall} (${r.comparedSymbols} compared, ${r.skippedOraclePartial} skipped: oracle-partial)`)}if(i.topDisagreements.length>0){console.log(`
235
- Top disagreements (debugging targets):`);for(let r of i.topDisagreements)console.log(` ${r.symbol} [${r.question}]`),r.cheapOnly.length>0&&console.log(` cheap-only: ${r.cheapOnly.join(", ")}`),r.oracleOnly.length>0&&console.log(` oracle-only: ${r.oracleOnly.join(", ")}`)}}),ap=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",agent:C("How accurate are the fast evidence paths on a sample?","sample coverage, agreement scores, and disagreements",[],"sampled","repository"),options:x([u("--samples <n>","Number of symbols to sample",S,50),u("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:R("Health",["scip-query self-audit --samples 100"]),handler:fv},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",agent:C("How structurally complex and connected is this symbol?","LOC, branch, complexity, callee, fan-in, and fan-out counts",["symbol"],"bounded"),options:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Health"),handler:hv}];var gv=Z(({db:e,args:t,opts:n})=>{let i=N(t,0),o=b(n,"full"),r=K(n,"maxDepth");if(o&&r!==void 0)throw new Error("--full cannot be combined with --max-depth. Use --full for complete traversal or --max-depth N for a bounded traversal.");let s=vs(e,i,{maxDepth:o?Number.MAX_SAFE_INTEGER:r,scope:w(n,"scope")}),a=s.rows;if(b(n,"json")){P("affected",t,n,{...Ae(e,i,a,"affected"),coverage:s.coverage});return}if(a.length===0)return A.empty(me(e,i,"No possible impacts found in the bounded reverse caller/reference closure."));de(e,i);let c=-1;for(let l of a)l.depth!==c&&(console.log(`
236
- \u2500\u2500 Depth ${l.depth} \u2500\u2500`),c=l.depth),console.log(` ${l.file} ${l.shortName}`);console.log(`
237
- ${a.length} possible-impact symbol(s) across ${new Set(a.map(l=>l.file)).size} files; reachability does not prove breakage.`),console.log(` coverage: ${s.coverage.status} \u2014 ${s.coverage.reasons.join(" ")}`)}),yv=te("co-change",({db:e,args:t,opts:n,budget:i})=>{let o=t[0]===void 0?void 0:N(t,0),r=b(n,"full"),s=Cs(e,o,{minTogether:k(n,"minTogether",4),limit:D(n,"limit",30),includeLinked:n.all===!0,scanLimit:i.scanLimit,historyMode:r?"full":"bounded"});if(b(n,"json")){P("co-change",t,n,s,{analysisBudget:i.analysisBudget});return}if(!s.available)return A.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return A.empty(o?`No co-change partners found for ${o} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);rt("co-change candidates"),console.log(o?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
238
- `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
239
- `),o&&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.
240
- `);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 ${bv(a.lastTogetherAt)}`),console.log(` subjects: ${vv(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
241
- ${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function bv(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function vv(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",i=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(o=>`"${o}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${i}; external issue/PR labels ${e.externalIssueLabelStatus}`}var Sv=te("change-surface",({db:e,args:t,opts:n,budget:i})=>{let o=Ss(e,N(t,0),{semantic:i.semantic});if(b(n,"json")){P("change-surface",t,n,o,{analysisBudget:i.analysisBudget});return}if(!o)return A.empty("File not found in index.");console.log(`File: ${o.file}`),console.log(`External consumers: ${o.totalExternalConsumers}`),o.fileRisk&&o.fileRisk.reasons.length>0&&console.log(`File risk factors (${o.fileRisk.coverage} metadata): ${o.fileRisk.reasons.map(r=>`${r.kind}: ${r.detail}`).join("; ")}`),console.log(""),A.list(o.symbols,r=>{let s=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"",a=r.riskReasons??[],c=a.length===0?"":` [why: ${a.map(l=>`${l.kind}: ${l.detail}`).join("; ")}]`;return` ${ve(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${s}${c}`})}),wv=te("incomplete-migration",({db:e,args:t,opts:n,budget:i})=>{let o=xs(e,{base:w(n,"base"),minContainment:k(n,"minContainment",.7),maxHelpers:K(n,"maxHelpers"),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(b(n,"json")){P("incomplete-migration",t,n,o,{analysisBudget:i.analysisBudget}),(!o.available||o.findings.length>0)&&(process.exitCode=1);return}if(!o.available){console.error(`error: ${o.note??"Required Git history is unavailable."}`),process.exitCode=1;return}if(o.changedFiles.length===0)return A.empty(`No changes vs ${o.base}.`);console.log(`Incomplete migrations vs ${o.base}: ${o.changedFiles.length} changed file(s), ${o.helpersChecked} new helper(s) scored.`),o.note&&console.log(` note: ${o.note}`);for(let r of o.skipped)console.log(` skipped ${r.helperShortName} (${r.helperFile}): ${r.reason}`);if(o.findings.length===0){console.log(`
242
- No incomplete migrations detected.`);return}rt("incomplete migration candidates");for(let r of o.findings){console.log(`
243
- ${r.helperShortName} (${r.helperFile})`),console.log(` helper shape: ${r.helperShape} (${r.specificHelperCalleeCount}/${r.helperCalleeCount} specific callees)`),console.log(` wired into: ${r.migratedFiles.join(", ")}`);for(let s of r.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(`
244
- ${o.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)}),cp=[{id:"affected",command:"affected <symbol>",description:"Conservative reverse caller/reference closure of symbols that may be impacted by a change",agent:C("Which downstream symbols are statically reachable as possible change impacts?","possible-impact symbol identities, files, and traversal depths; not predicted failures",["symbol"],"bounded"),options:x([u("--full","Traverse without the default depth and per-frontier caller caps"),u("--max-depth <n>","Maximum traversal depth (default: 5)",S),u("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:R("Impact"),handler:gv},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: consumers, published API, operational roots, and explained change risk",agent:C("What public surface and consumers make this file risky to change?","defined symbols, external consumer counts, and risk levels",["file"],"bounded"),options:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:R("Impact"),handler:Sv},{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:C("Did this diff leave a helper extraction only partly migrated?","new helpers and similar unmigrated call sites",[],"bounded","diff"),options:x([u("--base <ref>","Git ref to diff against (default: HEAD)"),u("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",Oe,.7),u("--max-helpers <n>","Maximum new helpers to score (default: all)",S),u("-n, --limit <n>","Maximum findings to report",S,20),u("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:R("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:wv},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",agent:C("Which files repeatedly change together without a declared dependency?","file pairs, co-change counts, confidence, and history context",["file"],"bounded","repository"),options:x([u("--min-together <n>","Minimum commits where both files changed",S,4),u("-n, --limit <n>","Maximum pairs to report",S,30),u("--all","Include pairs that already have a dependency edge"),u("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},claims:Je(["index-generation","live-workspace"],[X("historical-pairs","findings[]","change-history"),X("structural-link-classification","findings[].structurallyLinked","compiler-graph")]),renderShape:"custom",docs:R("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:yv}];import{spawn as $v}from"child_process";import{createHash as Ro,randomUUID as Rv}from"crypto";import{existsSync as $o,realpathSync as xv}from"fs";import{tmpdir as Cv}from"os";import{join as xo,resolve as dn}from"path";import{fileURLToPath as kv}from"url";var Ct=18,Ev=1e3,Tv=2*Ev,Iv=4,Av=4,Pv=5,Lv=3,jv=3,Nv=4,Mv=3,Ov=3,Dv=8,lp=3e4,qv=5e3,up=5,Fv=10,Wv=1,_v=5,pp=64*1024*1024,Bv={maxItems:64,maxBytes:128*1024*1024,maxItemBytes:pp,maxBatch:1,responseRetentionMs:6e4};function mp(e,t,n={},i={}){return Gv(e,o=>({kind:"source-search",expectedGeneration:o,pattern:t,options:n}),zv,"search result",i)}function Gv(e,t,n,i,o){if(!Xv(o.allowDefault===!0))return null;try{let r=o.allowDefault===!0&&process.env.SCIP_QUERY_QUERY_SERVICE!=="1",s=r?Uo(e):void 0,a=qe(e,s);if(!$o(a.dbPath))return null;let c=Qe(a.dbPath);if(!c||r&&!Vv(a,s,c))return null;let l=Hv({projectRoot:a.projectRoot,dbPath:a.dbPath,generationIdentity:c},t(c),n,i);return{result:l.result,generationIdentity:c,observationReceipt:l.observationReceipt}}catch(r){return fp()&&console.error(`query-service fallback: ${r instanceof Error?r.message:String(r)}`),null}}function Vv(e,t,n){if(e.config.watch?.enabled!==!0)return!1;try{return gc(Pt({projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:Ve,gitContext:t}))===n}catch{return!1}}function hp(e){return Ro("sha256").update(Cn({kind:"scip-query-service-mailbox",protocolVersion:Ct,sessionDir:dn(e)})).digest("hex")}function ai(e){let t=xo(e,"server.json");try{let n=JSON.parse(Ce(t,{maxBytes:65536,inputKind:"query service state"}));if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n,o=i.processIdentity===void 0?void 0:mr(i.processIdentity);return i.protocolVersion!==Ct||typeof i.sessionIdentity!="string"||i.sessionIdentity!==hp(e)||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<=0||i.processIdentity!==void 0&&(!o||o.pid!==i.pid)||typeof i.generation!="string"||typeof i.heartbeatAtMs!="number"||!Number.isFinite(i.heartbeatAtMs)?null:{protocolVersion:Ct,sessionIdentity:i.sessionIdentity,pid:i.pid,...o?{processIdentity:o}:{},generation:i.generation,heartbeatAtMs:i.heartbeatAtMs}}catch{return null}}function ci(e,t=Date.now()){if(!Rn(e.pid))return!1;let n=t-e.heartbeatAtMs;if(n>=0&&n<=Tv||!e.processIdentity)return!0;let i=He(e.pid);return i!==null&&xn(e.processIdentity,i)}function Uv(e){let t=e<Fv;return{intervalMs:t?Wv:up,checkServerState:!t||e%_v===0}}function Hv(e,t,n,i){let o=Yv();if(!$o(o))throw new Error("Query service server executable is unavailable.");let r=Math.abs(process.pid)%eS(t),s=Jv(e,o,r),a=fr(s),c=Date.now(),l=c+lp,d=ke()+lp,m=Rv(),h=Qv(m,t),p=gr(h),f=hp(s),g=yr(a,{mailboxVersion:Ri,protocolVersion:Ct,id:p,operationKey:h,clientId:m,enqueuedAtMs:c,deadlineAtMs:l,sessionIdentity:f,request:t},{nowMs:c,limits:Bv,durability:"visibility"});dp(s,e.projectRoot,o,d);let y=0;for(;ke()<=d;){if($o(g.responsePath))return Kv(Ce(g.responsePath,{maxBytes:pp,inputKind:"query service response"}),{id:p,operationKey:h,clientId:m,deadlineAtMs:g.authoritativeDeadlineAtMs,generation:e.generationIdentity},n,i);let v=Uv(y);if(v.checkServerState){let $=ai(s);(!$||!ci($))&&dp(s,e.projectRoot,o,d)}gp(v.intervalMs),y+=1}throw new Error("Persistent query service timed out.")}function Qv(e,t){return Ro("sha256").update(Cn({namespace:"query-service-v18",payload:{clientId:e,request:t}})).digest("hex")}function dp(e,t,n,i){let o=ai(e);if(o&&ci(o))return;let r=Math.min(i,ke()+qv),s=oa(xo(e,"startup.lock"),{kind:"query-service-startup",detail:{projectRoot:dn(t)},directoryDurability:"recoverable"});try{if(s.kind==="acquired"){let a=ai(e);if(!a||!ci(a)){let c=fp();$v(process.execPath,[n,e,t],{cwd:t,detached:!c,stdio:c?["ignore","ignore","inherit"]:"ignore",env:{...process.env,SCIP_QUERY_QUERY_SERVICE_SERVER:"1"}}).unref()}}for(;ke()<=r;){let a=ai(e);if(a&&ci(a))return;gp(up)}}finally{s.kind==="acquired"&&s.lock.release()}throw new Error("Persistent query service did not become ready within 5s.")}function Kv(e,t,n,i){let o=JSON.parse(e);if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Invalid query service response.");let r=o;if(r.mailboxVersion!==Ri||r.protocolVersion!==Ct||r.id!==t.id||r.operationKey!==t.operationKey||r.clientId!==t.clientId||r.deadlineAtMs!==t.deadlineAtMs)throw new Error("Query service response identity does not match the request.");if(r.ok!==!0)throw new Error(typeof r.error=="string"?r.error:"Persistent query service rejected the request.");if(r.generation!==t.generation)throw new Error("Persistent query service generation changed.");if(!n(r.result))throw new Error(`Persistent query service returned an invalid ${i}.`);let s=sa(r.observationReceipt);if(s.kind!=="supported")throw new Error("Persistent query service returned an invalid observation receipt.");return{ok:!0,protocolVersion:Ct,id:t.id,generation:t.generation,result:r.result,observationReceipt:s.receipt}}function zv(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.pattern=="string"&&(t.mode==="literal"||t.mode==="regexp")&&Array.isArray(t.matches)&&typeof t.matchingLines=="number"&&Number.isSafeInteger(t.matchingLines)&&t.matchingLines>=0&&typeof t.omittedMatches=="number"&&Number.isSafeInteger(t.omittedMatches)&&t.omittedMatches>=0&&typeof t.scannedFiles=="number"&&Number.isSafeInteger(t.scannedFiles)&&t.scannedFiles>=0}function Jv(e,t,n){let i=tS(e.projectRoot),o=Ro("sha256").update(Cn({protocolVersion:Ct,projectRoot:i,dbPath:dn(e.dbPath),serverPath:dn(t),lane:n})).digest("hex");return xo(Cv(),"scip-query-query-service",o)}function Yv(){return process.env.SCIP_QUERY_QUERY_SERVICE_SERVER_PATH??kv(new URL("./query-service-server.js",import.meta.url))}function Xv(e){let t=process.env.SCIP_QUERY_QUERY_SERVICE;return process.env.SCIP_QUERY_QUERY_SERVICE_SERVER!=="1"&&t!=="0"&&(t==="1"||e)}function fp(){return process.env.SCIP_QUERY_QUERY_SERVICE_DEBUG==="1"}function Zv(){let e=Number(process.env.SCIP_QUERY_QUERY_SERVICE_POOL_SIZE);return Number.isInteger(e)&&e>=1&&e<=Dv?e:Iv}function eS(e){let t=Zv();return e.kind==="value-flow"?Math.min(t,Mv):e.kind==="dependence-slice"?Math.min(t,Ov):e.kind==="call-graph"?Math.min(t,Lv):e.kind==="system"?Math.min(t,Nv):e.kind==="reference-reachability"||e.kind==="slice"?Math.min(t,jv):e.kind==="refs"||e.kind==="trace"||e.kind==="reference-neighborhood"||e.kind==="dataflow"||e.kind==="imports"||e.kind==="unused-imports"?Math.min(t,Pv):e.kind==="imported-by"||e.kind==="hierarchy"||e.kind==="by-kind"||e.kind==="kind-counts"?Math.min(t,Av):t}function tS(e){try{return xv.native(e)}catch{return dn(e)}}function gp(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function nS(e){let t=b(e,"full"),n=D(e,"limit",12);return t?void 0:n}function yp(e){return{scope:w(e,"scope"),context:k(e,"context",2),limit:D(e,"limit",6),regexp:b(e,"regexp"),ignoreCase:b(e,"ignoreCase"),ranking:"structural"}}function iS(e){let t=w(e,"view")??"source";if(t!=="source"&&t!=="behavior")throw new Error(`Unknown inspect view: ${t}. Use source or behavior.`);return t}function oS(e){let t=[];for(let o of e.definitions){let r=o.signature?` \u2014 ${o.signature}`:"";o.source?t.push(ht({relativePath:o.relativePath,startLine:o.startLine,source:o.source,sessionPolicy:"exact-unit",headerSuffix:r,ownerSymbol:o.signature??void 0})):t.push(` ${V(o.relativePath,o.startLine,o.endLine)}${r}`)}let n=[],i="";for(let o of e.referencedBy){o.relativePath!==i&&(i&&n.push(""),n.push(` ${o.relativePath}`),i=o.relativePath);let r=Rp(e.referenceEvidence,o.relativePath,o.line);n.push(` line ${j(o.line)} in ${o.enclosingShort} [${xp(r)}]`),o.source!==void 0&&o.source!==null&&o.sourceStartLine!==void 0&&o.sourceStartLine!==null&&n.push(ht({relativePath:o.relativePath,startLine:o.sourceStartLine,source:o.source,sessionPolicy:"preview",focusLines:new Set([o.line]),ownerSymbol:o.enclosingShort??void 0,indent:" ",sourceIndent:" "}))}return[{title:"DEFINITION",rows:t,preserveRowNewlines:!0},{title:"REFERENCED BY",rows:n,preserveRowNewlines:!0},{title:"CLAIM SUPPORT",rows:Cp(e.claimSupport),skipIfEmpty:!0}]}function Rp(e,t,n){return e.find(i=>i.relativePath===t&&i.line===n)?.sourceKind}function xp(e){switch(e){case"complete-call-expression":return"complete call";case"non-call-reference":return"non-call reference";case"bounded-context":return"bounded context";case"unavailable":return"source unavailable";default:return"coverage unknown"}}function Cp(e){return e?[bp("Reference-absence claims",e.referenceAbsence),bp("Callsite-argument claims",e.callsitePredicates)]:[]}function bp(e,t){return t.status==="eligible"?` ${e}: eligible within ${t.scope}. ${t.limitations.join(" ")}`:[` ${e}: INELIGIBLE within ${t.scope}; ${t.reason}`,...t.followup?[` Inspect uncertain sites together: ${t.followup}`]:[]].join(`
245
- `)}var Co=["definition","references","callers","callees","dependencies","consumers"],Eo=["search","exact-source","definition","caller","callee","production-reference","test-reference","dependency","consumer"];function ko(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...Co];let n=t.filter(i=>!Co.includes(i));if(n.length>0)throw new Error(`Unknown evidence part: ${n.join(", ")}. Use ${Co.join(", ")}, or all.`);return[...new Set(t)]}function rS(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...ot];let n=t.filter(i=>!ot.includes(i));if(n.length>0)throw new Error(`Unknown graph evidence family: ${n.join(", ")}. Use ${ot.join(", ")}, or all.`);return[...new Set(t)]}function sS(e){if(e!==void 0){if(Ai.includes(e))return e;throw new Error(`Unknown evidence view: ${e}. Use ${Ai.join(", ")}.`)}}function aS(e){if(e!==void 0){if(["incoming","outgoing","both"].includes(e))return e;throw new Error(`Unknown evidence direction: ${e}. Use incoming, outgoing, or both.`)}}function cS(e){let t=[...new Set(e.flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean))];return t.length>0?t:void 0}function lS(e){if(e.length===0)return;let t={};for(let n of e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean)){let i=n.lastIndexOf("="),o=n.slice(0,i),r=n.slice(i+1);if(i<=0||!Eo.includes(o))throw new Error(`Unknown inspect evidence budget '${n}'. Use channel=n with ${Eo.join(", ")}.`);if(Object.hasOwn(t,o))throw new Error(`Duplicate inspect evidence budget: ${o}.`);if(!/^\d+$/u.test(r))throw new Error(`Inspect evidence budget ${o} must be a non-negative safe integer; received ${r}.`);let s=Number(r);if(!Number.isSafeInteger(s))throw new Error(`Inspect evidence budget ${o} must be a non-negative safe integer; received ${r}.`);t[o]=s}return t}function dS(e){let t=li(e),n=kp(e,t),i=e.matches.map(h=>pS(e,h)),o=i.map(h=>h.text),r=i.reduce((h,p)=>h+p.shortenedLines,0),s=i.reduce((h,p)=>h+p.omittedContextLines,0),a=yS(t),c=n.mode==="complete"?bS(e,t):[],l=e.textCoverage,d=To(e),m=n.mode==="bounded"?gS(e):c.length>0?[` Recover every unmaterialized owning unit in ${c.length} bounded batch command(s):`,...c.map(h=>` ${h}`)]:[" Every matching source window was materialized; no drilldown remains."];return[{title:"REQUEST",rows:[` exact-text=${JSON.stringify(e.pattern)}; mode=${e.mode}`]},{title:`OBSERVED MATCH IDENTITIES (${t.length}/${e.matchingLines}, ${n.mode.toUpperCase()})`,rows:a},{title:`OBSERVED SOURCE (${e.matches.length}/${e.matchingLines} WINDOWS)`,rows:o,preserveRowNewlines:!0},{title:"EVIDENCE CALIBRATION",rows:[` ${d?"Exact":"Observed"} cardinality is current project text; compiler ownership is an aligned semantic overlay. Neither ownership nor co-occurrence proves task relevance or a graph relationship.`,...r>0?[` ${r} overlong matched line(s) were shortened; every exact path:line identity remains recoverable with scip-query code.`]:[],...s>0?[` ${s} nonfocus context line(s) were omitted from expensive previews; the matched lines remain visible and JSON retains complete windows.`]:[]]},{title:"COVERAGE",rows:[` ${d?"Exact":"Observed"} cardinality: ${e.matchingLines} matching line(s) across ${e.matchingFiles??e.fileCoverage?.length??0} file(s). Identity manifest: ${t.length}/${e.matchingLines} matching line(s); ${n.mode==="complete"?"complete":`${n.omitted} lower-ranked identities withheld before rendering`}. Source materialization: ${e.matches.length}/${e.matchingLines} window(s); ${e.omittedMatches} exact match location(s) were not expanded into source.`,...l?[` Exact text: ${l.scannedTextFiles}/${l.candidateFiles} current project text file(s), ${l.scannedBytes.toLocaleString()} byte(s); semantic owners ${l.semanticFiles.aligned} aligned, ${l.semanticFiles.stale} stale, ${l.semanticFiles.unavailable} unavailable; exclusions ${l.skippedBinaryPaths.length} binary, ${l.skippedUnreadablePaths.length} unreadable, ${l.skippedOversizedPaths.length} oversized.`,...d?[]:[" Text coverage is incomplete: unreadable or oversized text may contain additional matches."]]:[]]},{title:"RECOVERY",rows:m}]}var ut=320,uS=1200;function pS(e,t){let n=t.source.split(`
246
- `);if(!(n.some(m=>m.length>ut)||t.source.length>uS)){let m=t.ownerShort?` in ${t.ownerShort}`:"";return{text:ht({relativePath:t.relativePath,startLine:t.startLine,source:t.source,sessionPolicy:"preview",focusLines:new Set([t.focusLine]),ownerSymbol:t.ownerShort??void 0,headerSuffix:m}),shortenedLines:0,omittedContextLines:0}}let r=t.ownerShort?` in ${t.ownerShort}`:"",s=Math.max(0,Math.min(n.length-1,t.focusLine-t.startLine)),a=n[s]??"",c=a.length>ut?1:0,l=` >${String(j(t.focusLine)).padStart(5)} ${mS(e,a)}`,d=Math.max(0,n.length-1);return{text:[` ${V(t.relativePath,t.startLine,t.endLine)}${r}`,l,...d>0?[` \u2026[${d} nonfocus context line(s) omitted]`]:[]].join(`
247
- `),shortenedLines:c,omittedContextLines:d}}function mS(e,t){if(t.length<=ut)return t;let n=hS(e,t);if(n<0){let l=ut/2,d=t.length-ut;return`${t.slice(0,l)}\u2026[${d} characters omitted]\u2026${t.slice(-l)}`}let i=e.mode==="literal"?Math.min(e.pattern.length,ut):1,o=n-Math.floor((ut-i)/2),r=Math.max(0,Math.min(o,t.length-ut)),s=r+ut,a=r>0?`\u2026[${r} characters omitted]\u2026`:"",c=s<t.length?`\u2026[${t.length-s} characters omitted]\u2026`:"";return`${a}${t.slice(r,s)}${c}`}function hS(e,t){if(e.mode==="literal"){let n=t.indexOf(e.pattern);return n>=0?n:t.toLowerCase().indexOf(e.pattern.toLowerCase())}try{return new RegExp(e.pattern,"u").exec(t)?.index??-1}catch{return-1}}function fS(e){let t=e.groups.flatMap((n,i)=>{let o=n.kind==="shared-callee-owners"?"shared callee":n.kind==="cross-boundary-flow"||n.kind==="parallel-paths"?"basis root":"root",r=n.roots.slice(0,6),s=r.map(c=>{let l=c.matches.map(d=>`${d.term}[${d.sources.join("+")}]`).join(", ");return` ${o} ${c.label} \u2014 ${c.file}:${j(c.line)} \u2014 ${l}`}),a=n.relations.map(c=>` ${c.fromLabel} \u2192 ${c.toLabel} [${c.kind}; ${c.strength}; ${c.evidence}; depth ${c.depth}${c.runtimeBoundaryKey?`; ${c.runtimeBoundaryKey}`:""}]`);return[` [${i+1}] ${n.kind}; terms: ${n.matchedTerms.join(", ")||"(structural only)"}`,...n.kind==="shared-callee-owners"?[` map owners: ${n.keyAnchors.map(c=>c.label).join(", ")}`,...n.omittedCandidateOwners.length>0?[` additional candidate owners: ${n.omittedCandidateOwners.map(c=>c.label).join(", ")}`,...n.ownerRecoveryCommands.map(c=>` additional owner map if those candidates can change the answer: ${c}`)]:[]]:n.kind==="cross-boundary-flow"||n.kind==="parallel-paths"?[` map anchors: ${n.keyAnchors.map(c=>c.label).join(", ")}`,...n.kind==="parallel-paths"?[` shared path vocabulary: ${n.parallelSharedPathTerms?.join(", ")||"(none)"}`,` causal evidence on ${n.parallelConnectedSides??0}/2 independently named path(s); matched orchestration roots on ${n.parallelOrchestrationSides??0}/2; no cross-path edge is claimed.`]:[],...n.upstreamEntries.map(c=>` upstream entry: ${c.name} \u2014 ${c.file}:${j(c.line)}; if command preconditions can change the answer, include this location in the one batched gap inspect after the map.`)]:[],...s,...n.roots.length>r.length?[` ... ${n.roots.length-r.length} additional basis owner(s) retained in the result.`]:[],...a,...n.omittedRelations>0?[` ... ${n.omittedRelations} additional relationship(s) withheld from this compact view.`]:[],` next abstraction (run to completion before any inspect): ${n.systemMapCommand}`]});return[{title:"REQUIRED NEXT STEP",rows:[" Choose one evidence-grounded anchor set below and run its exact next-abstraction system-map command to transport completion."," inspect, code, and evidence are intentionally unavailable until that map completes."]},{title:"NORMALIZED REPOSITORY VOCABULARY",rows:[` matched: ${e.matchedTerms.join(", ")||"(none)"}`,` unmatched: ${e.unmatchedTerms.join(", ")||"(none)"}`]},{title:`EVIDENCE-GROUNDED ANCHOR SETS (${e.groups.length} SHOWN)`,rows:t},{title:"ANCHOR DISCOVERY COVERAGE",rows:[` Repository scan: ${e.scannedFiles} current text file(s), ${e.scannedBytes.toLocaleString()} byte(s).`,` Lexical owners: ${e.candidateRootCount}; structurally analyzed: ${e.analyzedRootCount}; lower-ranked owners not graph-expanded: ${e.omittedRootCount}.`,` Displayed anchor sets: ${e.groups.length}; withheld sets or unanalyzed roots: ${e.omittedGroupCount}.`," cross-boundary-flow joins otherwise separate call groups only when an indexed runtime producer\u2192consumer link and bounded downstream calls connect them; parallel-paths batches disconnected regions only when the query names distinct path vocabulary shared by those regions and does not claim a causal edge; connected-flow follows calls forward from matched owners; shared-callee-owners finds callable owners that converge on common callees without claiming those callees are effects."," Ranking uses repository vocabulary, compiler ownership, and bounded call connectivity; it does not establish task relevance."," Selection gate: reject a set whose roots and matched terms omit an object, branch, or stage named by a material claim. Connectivity cannot make a partial set eligible. Among sets that cover every named part, use the first ranked eligible set; use parallel-paths when no connected-flow covers them together."," Anchor roots are locator evidence, not behavior evidence. Select one set, run its next-abstraction command to transport completion, and only then decide whether source inspection is necessary. Never run a map and inspect concurrently.",...e.recoveryCommand?[` Expand the ranked manifest only if the shown sets cannot establish the requested flow: ${e.recoveryCommand}`]:[" Every candidate owner was structurally analyzed and every resulting anchor set was shown."]]}]}function To(e){let t=e.textCoverage;return!!(t&&t.skippedUnreadablePaths.length===0&&t.skippedOversizedPaths.length===0)}function kp(e,t){return e.identityCoverage??{mode:t.length===e.matchingLines?"complete":"bounded",returned:t.length,total:e.matchingLines,omitted:Math.max(0,e.matchingLines-t.length)}}function gS(e){let t=e.fileCoverage??[],n=new Map;for(let o of t){let r=o.relativePath.indexOf("/"),s=r<0?"<root>":o.relativePath.slice(0,r),a=n.get(s)??[];a.push(o),n.set(s,a)}let i=[...n].sort(([o],[r])=>o.localeCompare(r)).flatMap(([o,r])=>{let s=[...r].sort((c,l)=>c.relativePath.localeCompare(l.relativePath)),a=s.reduce((c,l)=>c+l.matchingLines,0);return o==="<root>"?s.map(c=>` ${c.relativePath}: ${c.matchingLines} match(es); scip-query search ${Le(e.pattern)} --scope ${Le(c.relativePath)}`):[` ${o}: ${a} matching line(s) across ${s.length} file(s); scip-query search ${Le(e.pattern)} --scope ${Le(o)}`]});return[" Broad selector: identity enumeration stopped before output transport; there is no cursor to drain.",...i.length>0?[" Complete top-level recovery manifest:",...i]:[]," Narrow one structural region; ordering does not infer task relevance."]}function Ep(e){return e.identities??e.matches.map(t=>({relativePath:t.relativePath,focusLine:t.focusLine,ownerSymbol:t.ownerSymbol,ownerShort:t.ownerShort,ownerStartLine:t.ownerStartLine??null,ownerEndLine:t.ownerEndLine??null,fileKind:t.fileKind??"source",freshness:t.freshness}))}function li(e){return e.identityManifest??Ep(e)}function yS(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath)??[];i.push(n),t.set(n.relativePath,i)}return[...t.entries()].flatMap(([n,i])=>{let o=new Map;for(let r of i){let s=r.ownerSymbol??"<file>",a=r.ownerStartLine===null||r.ownerEndLine===null?"":` ${j(r.ownerStartLine)}-${j(r.ownerEndLine)}`,c=o.get(s)??{label:r.ownerShort?`${r.ownerShort}${a}`:"<file scope>",lines:[]};c.lines.push(j(r.focusLine)),o.set(s,c)}return[` ${n} [${i[0].fileKind}; ${i.length} match(es)]`,...[...o.values()].flatMap(r=>Tp(r.lines,24).map((s,a)=>` ${a===0?r.label:"\u21B3"} @ ${s.join(",")}`))]})}function bS(e,t){let n=new Set(e.matches.map(o=>vp(o))),i=new Set;for(let o of t){if(n.has(vp(o)))continue;let r=j(o.ownerStartLine??o.focusLine),s=j(o.ownerEndLine??o.focusLine);i.add(`${o.relativePath}:${r}-${s}`)}return Tp([...i],24).map(o=>`scip-query code ${o.map(r=>Le(r)).join(" ")}`)}function vp(e){return`${e.relativePath}\0${e.focusLine}`}function Tp(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function Le(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function vS(e){let t=["scip-query inspect"];for(let i of O(e,"search"))t.push(`--search ${Le(i)}`);for(let i of O(e,"symbol"))t.push(`--symbol ${Le(i)}`);for(let i of O(e,"at"))t.push(`--at ${Le(i)}`);let n=w(e,"scope");return n&&t.push(`--scope ${Le(n)}`),t.push("--view behavior"),t.join(" ")}function SS(e,t){if(!(e.view!=="source"||b(t,"allowLargeSource")||(e.returnedCharacters??0)<=2e4))throw new Error(["INSPECT SOURCE PACKET REFUSED",`${e.returnedCharacters??0} exact source character(s) across ${e.units?.length??0} selected unit(s) exceed the ${2e4}-character safe materialization ceiling.`,"No partial source was emitted.",`Read the same constructs with complete statement accounting: ${vS(t)}`,"Narrow to smaller exact selectors, or rerun with --allow-large-source only when the omitted syntax itself can change the decision."].join(`
248
- `))}function wS(e,t){if(e.view!=="behavior"||b(t,"allowLargeBehavior"))return;let n=(e.omissionGroups??[]).filter(r=>r.sourceCharacters>2e4&&r.roles.some(s=>s==="location"||s==="definition"));if(n.length===0&&(e.returnedViewCharacters??0)<=2e4)return;let i=n.flatMap(r=>r.anchors).map(r=>`${r.relativePath}:${j(r.line)}`),o=i.length>0?i.join(", "):O(t,"at").join(", ");throw new Error(["INSPECT BEHAVIOR FOCUS REQUIRED",`The selector set resolves to behavioral constructs above the ${2e4}-character evidence ceiling${o?` (${o})`:""}.`,"No partial behavior was emitted, and this refusal does not establish an exploration obligation.","Use one or more interior file:line locations already visible in connected behavior, and batch only the named gaps. Do not use --full to turn a broad construct into a focus.","Use --allow-large-behavior only when every statement in the construct can change the decision."].join(`
249
- `))}function $S(e){let t=e.units??[],n=e.searches.map(h=>{let p=[` ${h.pattern}: ${h.returnedMatches}/${h.matchingLines} matching line(s) materialized across ${h.returnedFiles??0}/${h.matchingFiles??0} file(s); ${h.selectedUnits??0}/${h.candidateUnits??0} deduplicated unit(s) selected`];return(h.omittedMatches>0||(h.omittedUnits??0)>0)&&(p.push(` Withheld: ${h.omittedMatches} matching line(s), ${h.omittedFiles??0} file(s) with no materialized match, and ${h.omittedUnits??0} materialized unit(s) outside the packet ceiling.`),(h.scopeHints?.length??0)>0&&(p.push(" Highest-coverage scopes available for focused expansion:"),p.push(...(h.scopeHints??[]).map(f=>` ${f.scope}: ${f.returnedMatches}/${f.matchingLines} matching line(s) materialized; ${f.exactFollowup}`)),(h.omittedScopeHints??0)>0&&p.push(` ... ${h.omittedScopeHints} additional matching scope(s).`)),h.exactFollowup&&p.push(` Expand this selector completely only if omitted matches can change the decision: ${h.exactFollowup}`)),p.join(`
250
- `)}),i=e.locations.map(h=>` ${h.matched?"matched":"missing"} ${h.target}`),o=t.map(ES),r=Pp(e.bindingClosure),s=(e.omissionGroups??[]).map(TS),a=RS(e),c=e.evidence.flatMap(h=>{let p=Ip(h,"inspect");return p?[` ${p}`]:[]}),l=e.packetCoverage,d=l?[` ${l.mode==="complete"?"Complete":"Ranked bounded"} semantic packet: ${l.returnedUnits}/${l.candidateUnits} materialized unit(s), ${e.returnedLines??0} underlying source line(s), and ${e.returnedViewCharacters??e.returnedCharacters??0} displayed evidence character(s).`,` Selection ceiling: ${l.maxUnits} unit(s) or ${l.maxCharacters} displayed evidence character(s); syntax units are never clipped.`,` Exact symbol/location evidence: ${l.exactSelectorsComplete?"complete within materialized compiler evidence":"some lower-ranked units withheld"}.`,...l.channels?[` Evidence channels: ${kS(l.channels)}.`]:[],...l.omittedUnits>0?[` Withheld materialized units by role: ${CS(l.omittedByRole)}.`]:[],...l.expansionCommand?[` Expand the complete selector set only if omitted evidence can change the decision: ${l.expansionCommand}`]:[]," Universal output transport may still page the rendered bytes; transport pages do not change this selection coverage."]:[` Complete semantic packet: ${t.length} deduplicated unit(s), ${e.returnedLines??0} source line(s), and ${e.returnedCharacters??0} source character(s).`],m=e.stoppingSummary?[` ${e.stoppingSummary.queryStatus??e.stoppingSummary.status}: ${e.stoppingSummary.guidance}`,...e.stoppingSummary.openEvidence>0?[` ${e.stoppingSummary.openEvidence} open evidence item(s); ${(e.omissionGroups??[]).length} recoverable omission group(s).`]:[]]:[];return[{title:"REQUEST",rows:[...n.map(h=>` search ${h.trimStart()}`),...i.map(h=>` location ${h.trimStart()}`),...c.map(h=>` symbol ${h.trimStart()}`)]},{title:"OBSERVED FACTS",rows:[...o,...r],preserveRowNewlines:!0,skipIfEmpty:!0},{title:"EVIDENCE CALIBRATION",rows:[` view=${e.view}; exact source is current working-tree text; behavioral outlines label whether they are statement-complete, partial, or verbatim source units.`," Source co-location and references do not become executable reachability. Runtime facts retain their displayed strength and resolution."]},{title:"COVERAGE",rows:[...d,...m]},{title:"RECOVERY",rows:[...s,...a],skipIfEmpty:!0}]}function RS(e){let t=e.causalFrontier;if(!t||t.candidateAnchors===0)return[];let n=t.anchors.filter(r=>r.alternativeCount===1),i=[` ${n.length}/${t.candidateAnchors} bounded downstream target(s) are uniquely resolved and visible; these targets are outside the materialized constructs, not evidence already inspected.`];for(let r of n){let s=r.alternatives[0],a=r.callsite.signals.length>0?` [${r.callsite.signals.join(",")}]`:"";i.push(` ${r.direction??"downstream"} ${r.causalRole??"callee"} from ${r.fromLabel} at ${r.callsite.file}:${j(r.callsite.line)}${a}`,` ${s.label} \u2014 ${s.file}:${j(s.line)}`)}let o=xS([...(e.omissionGroups??[]).flatMap(r=>r.anchors.map(s=>({file:s.relativePath,line:s.line}))),...n.map(r=>({file:r.alternatives[0].file,line:r.alternatives[0].line}))]).slice(0,24);return o.length>0&&i.push(` If any listed target or withheld requested construct remains material, run this one final recovery batch before answering: scip-query inspect ${o.map(r=>`--at ${Le(`${r.file}:${j(r.line)}`)}`).join(" ")} --view behavior`),t.omittedAnchors>0&&i.push(` ${t.omittedAnchors} additional downstream target(s) remain accounted in the frontier; use the printed remaining inspect commands only for a named unresolved fact.`),i}function xS(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}`,n);return[...t.values()]}function CS(e){return Object.entries(e).map(([t,n])=>`${t}=${n}`).join(", ")}function kS(e){return Eo.filter(t=>e[t].candidateUnits>0||e[t].omittedUnits>0).map(t=>{let n=e[t],i=n.maxUnits===Number.MAX_SAFE_INTEGER?"unbounded":String(n.maxUnits);return`${t} ${n.returnedUnits}/${n.candidateUnits} (limit ${i})`}).join("; ")}function ES(e){switch(e.kind){case"source":{let t=e.ownerShort?` in ${e.ownerShort}`:"";if(e.behavior){let o=e.behavior.coverage,s=[` representation: ${o.omittedStatements>0?"partial behavioral outline":o.copiedStatements===o.sourceStatements?"verbatim source unit (not compressed)":"statement-complete behavioral outline"}`,` ${e.behavior.constructKind}: ${e.behavior.signature}`,...e.behavior.lines.map(a=>` L${j(a.line)}${a.endLine>a.line?`-${j(a.endLine)}`:""} ${" ".repeat(a.depth)}${a.text}${a.copied?" [verbatim]":""}`),...e.behavior.testCases.length>0?[` related test cases: ${e.behavior.testCases.join("; ")}`]:[],...Sp(e.runtimeFacts??[]),` coverage: ${o.representedStatements}/${o.sourceStatements} source statement(s) represented; ${o.copiedStatements} verbatim; ${o.omittedStatements} omitted; ${e.behavior.outlineCharacters}/${e.behavior.rawCharacters} estimated characters`];return[` ${V(e.relativePath,e.startLine,e.endLine)}${t}`,` roles: ${e.roles.join(", ")}; selected by ${e.reasons.join(", ")}`,Jt({kind:"unit",identity:`inspect-behavior:${e.relativePath}:${e.startLine}:${e.endLine}`,content:s.join(`
251
- `),label:e.ownerShort??`${e.relativePath}:${j(e.startLine)}`,indent:" "})].join(`
252
- `)}let n=ht({relativePath:e.relativePath,startLine:e.startLine,source:e.source,sessionPolicy:"exact-unit",focusLines:new Set(e.focusLines),ownerSymbol:e.ownerShort??void 0,headerSuffix:t,afterHeader:[` roles: ${e.roles.join(", ")}; selected by ${e.reasons.join(", ")}`]}),i=Sp(e.runtimeFacts??[]);return i.length>0?`${n}
253
- ${i.join(`
254
- `)}`:n}case"path":return[` ${e.relationship}`,` ${e.roles.join(", ")} edge source was not located. Follow up exactly: ${e.exactFollowup}`].join(`
255
- `);default:return IS(e)}}function Sp(e){return e.map(t=>{let n=t.keyParts.map(i=>`${i.name}=${i.value}`).join(", ")||"no resolved key";return` runtime L${j(t.line)} [${t.strength}] ${t.action} (${t.role}; ${t.resolution}) ${n}; proof=${t.derivation.rule}`})}function TS(e){let t=e.anchors.slice(0,4).map(n=>{let i=n.ownerShort?` in ${n.ownerShort}`:"",o=n.behaviorSignals.length>0?` [${n.behaviorSignals.join(",")}]`:"";return` ${n.relativePath}:${j(n.line)}${i}${o}`});return e.anchors.length>t.length&&t.push(` ... ${e.anchors.length-t.length} additional anchor(s) represented by this group.`),[` ${e.id} ${e.scope} \u2014 ${e.candidateUnits} unit(s), ${e.sourceCharacters} source character(s)`,` channel: ${e.channel??"unclassified"}; roles: ${e.roles.join(", ")}; behavior: ${e.behaviorSignals.join(", ")||"not summarized"}`,...t,` Drill into this group together: ${e.drillCommand}`].join(`
256
- `)}function IS(e){throw new Error(`Unhandled source inspection unit: ${JSON.stringify(e)}`)}function Ip(e,t="evidence"){if(e.kind==="missing")return`No definition matched '${e.query}'.`;if(e.kind!=="ambiguous")return;let n=e.candidates.map(r=>{let s=`'${r.symbol.replaceAll("'","'\\''")}'`;return t==="inspect"?` scip-query inspect --symbol ${s}`:` scip-query evidence ${s}`}).join(`
257
- `),i=e.candidates.length,o=i<e.total?` Showing the highest-ranked ${i}; narrow by path or`:"";return`Target '${e.query}' is ambiguous across ${e.total} definitions.${o} run one listed exact command:
258
- ${n}`}function Io(e){if(e.kind!=="matched")return[];let t=e.definition?[ht({relativePath:e.definition.relativePath,startLine:e.definition.startLine,source:e.definition.source,sessionPolicy:"exact-unit",ownerSymbol:e.definition.shortName,headerSuffix:` ${e.definition.shortName}`}),...Pp(e.definition.bindingClosure)]:[],n=e.referenceWindows.map(o=>{let r=o.references.map(s=>`${j(s.line)} in ${s.enclosingShort} [${xp(Rp(e.referenceEvidence,o.relativePath,s.line))}]`).join(", ");return ht({relativePath:o.relativePath,startLine:o.startLine,source:o.source,sessionPolicy:"preview",focusLines:new Set(o.references.map(s=>s.line)),headerSuffix:` references: ${r}`})}),i=o=>o.map(r=>ht({relativePath:r.relativePath,startLine:r.startLine,source:r.source,sessionPolicy:"preview",ownerSymbol:r.shortName,headerSuffix:` ${r.shortName}${r.omittedLines>0?` (${r.omittedLines} line(s) omitted)`:""}`}));return[{title:"DEFINITION",rows:t,preserveRowNewlines:!0,skipIfEmpty:!0},{title:"REFERENCE SITES",rows:n,preserveRowNewlines:!0,skipIfEmpty:!0},{title:"CALLERS",rows:i(e.callers),preserveRowNewlines:!0,skipIfEmpty:!0},{title:"CALLEES",rows:i(e.callees),preserveRowNewlines:!0,skipIfEmpty:!0},{title:"DEPENDENCIES",rows:e.dependencies.map(o=>` ${o.relativePath}`),skipIfEmpty:!0},{title:"CONSUMERS",rows:e.consumers.map(o=>` ${o.relativePath}`),skipIfEmpty:!0},{title:"CLAIM SUPPORT",rows:Cp(e.claimSupport),skipIfEmpty:!0}]}function AS(e){if(e.kind!=="graph-packet")return Io(e);let t=e.graph.selection??{direction:"both",subtypes:[],connecting:!1,inventoryOnly:!1,foldIds:[]},n=[` direction=${t.direction}; subtypes=${t.subtypes.length>0?t.subtypes.join(","):"all"}; operation=${t.connecting?"connecting":"reachability"}; materialization=${t.inventoryOnly?"inventory-only":t.foldIds.length>0?`folds(${t.foldIds.join(",")})`:"edges"}`,...e.graph.targets.map(m=>{let h=m.omittedCandidates>0?`; ${m.omittedCandidates} candidate(s) omitted`:"";return` selector [${m.status}] ${m.kind} ${m.query}${h}`})],i=ot.flatMap(m=>{let h=e.graph.edges.filter(p=>p.family===m);return h.length===0?[]:[` ${m} (${h.length})`,...h.map(p=>` ${Ao(p)}`)]}),o=(e.graph.inventory??[]).map(m=>` inventory ${m.family}/${m.subtype}: incoming=${m.incoming}; outgoing=${m.outgoing}; both=${m.both}`);o.length>0&&o.unshift(" Inventory basis: incoming and outgoing are separately deduplicated reachable-edge sets around the selected roots; both is their deduplicated union, so it need not equal their sum.");let r=PS(e.graph.folds??[]),s=LS(e.graph.edges),a=e.graph.coverage,c=[` ${a.status}: ${a.returnedEdges}/${a.eligibleEdges} materialized relationship(s); ${a.matchedEdges??a.eligibleEdges} matched the projection; depth <= ${a.maxDepth}; ${a.frontierGroups} accounted frontier group(s); ${a.unsupportedFrontiers} unsupported frontier(s).`,` ${a.explanation}`,...Ap(a.blindSpots).map(m=>` Unsupported or unavailable: ${m}`)],l=e.source.flatMap(m=>m.kind!=="matched"?[{title:`SOURCE SELECTOR \u2014 ${m.query}`,rows:[` [${m.kind}]`]}]:Io(m).map(h=>({...h,title:`${m.shortName} \u2014 ${h.title}`}))),d=[...r,...a.omittedEdges>0&&r.length===0?[` Expand the same selectors only if an omitted relationship is material: add --max-edges ${a.eligibleEdges}.`]:[],...e.sourceRecovery?[` Graph traversal stays graph-sized; ${e.sourceRecovery.selectors} requested source selector(s) were not embedded.`,` Read the named source gap separately: ${e.sourceRecovery.command}`]:[]];return[{title:"REQUEST",rows:n},{title:"OBSERVED FACTS",rows:[...o,...i],skipIfEmpty:!0},...l,{title:"EVIDENCE CALIBRATION",rows:s},{title:"COVERAGE",rows:c},{title:"RECOVERY",rows:d,skipIfEmpty:!0}]}function PS(e){return e.length===0?[]:[" Rerun the same selectors and bounds with --fold <id>; each ID materializes exactly that folded edge set.",...[...e].sort((n,i)=>n.family.localeCompare(i.family)||(n.region??"").localeCompare(i.region??"")||n.id.localeCompare(i.id)).map(n=>{let i=n.subtypes??[n.subtype],o=i.length===1?i[0]:`${i.length} subtypes`;return` ${n.id} ${n.family}/${o} ${n.edgeCount} edge(s), ${n.nodeIds.length} node(s), ${n.mode} @ ${n.region??"unscoped"}`})]}function LS(e){let t=Ap(e.map(o=>o.evidenceStrength)),n=t.length===0?[" No relationships were materialized, so no edge evidence strength is claimed."]:t.map(o=>` ${o}: ${Ht[o]}`),i=new Map;for(let o of e){let r=(o.evidenceConstituents??o.evidenceMethods.map(a=>({method:a,strength:o.evidenceStrength}))).map(a=>`${a.method}=${a.strength}`).join(", "),s=`${o.family}/${o.subtype}\0${o.providerId}\0${o.evidenceStrength}\0${r}`;i.set(s,` ${o.family}/${o.subtype} [${o.evidenceStrength}] provider=${o.providerId}; ceiling=${o.supportCeiling}; constituents=${r||"none reported"}; establishes=${o.establishes}; does-not-establish=${o.nonClaims.join(" ")||"no additional provider non-claim"}`)}return[...n,...i.values()]}function Ap(e){return[...new Set(e)]}function Ao(e){let t=e.context?Object.entries(e.context).filter(([,o])=>o!==void 0).map(([o,r])=>`${o}=${wp(r)}`):[],n=e.attributes?Object.entries(e.attributes).map(([o,r])=>`${o}=${wp(r)}`):[],i=[...t,...n];return`[${e.evidenceStrength}] ${$p(e.from)} -> ${$p(e.to)} \u2014 ${e.subtype}${i.length>0?`; ${i.join(", ")}`:""}`}function wp(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}function $p(e){let t=e.location?` @ ${V(e.location.file,e.location.line,e.location.endLine??e.location.line)}`:"";return`${e.label}${t}`}function Pp(e){if(!e)return[];let t=[];for(let n of e.inline)t.push(` inline ${n.name} @ ${V(n.relativePath,n.startLine,n.endLine)}`,` ${n.source??""}`);return t}var jS=Ie("imports",{query:({db:e,args:t,budget:n})=>_r(e,N(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)."}),NS=te("dataflow",({db:e,args:t,opts:n,budget:i})=>{let o=N(t,0),r=qs(e,o,{semantic:i.semantic});if(b(n,"json")){P("dataflow",t,n,Ae(e,o,r,"dataflow"),{analysisBudget:i.analysisBudget});return}if(!r)return A.empty(me(e,o,"No dataflow found."));if(de(e,o),console.log(`${r.shortName} (${r.relativePath})
259
- `),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of r.definitionSites)console.log(` ${s.file}:${j(s.line)}`)}if(r.usageSites.length>0){console.log(`
260
- \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of r.usageSites)console.log(` ${s.file}:${j(s.line)} in ${s.enclosingShort}`)}if(r.producers.length>0){console.log(`
261
- \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let s of r.producers)console.log(` ${s.file} ${s.shortName}`)}if(r.consumers.length>0){console.log(`
262
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of r.consumers)console.log(` ${s.file} ${s.shortName}`)}}),MS=te("reference-neighborhood",({db:e,args:t,opts:n,budget:i})=>{let o=N(t,0),r=Ds(e,o,{semantic:i.semantic});if(b(n,"json")){P("reference-neighborhood",t,n,Ae(e,o,r,"reference-neighborhood"),{analysisBudget:i.analysisBudget});return}if(!r)return A.empty(me(e,o,"No reference neighborhood found."));if(de(e,o),console.log(`${r.shortName} (${r.relativePath})
263
- `),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINITION \u2550\u2550\u2550");for(let s of r.definitionSites)console.log(` ${s.file}:${j(s.line)}`)}if(r.referenceSites.length>0){console.log(`
264
- \u2550\u2550\u2550 REFERENCES \u2550\u2550\u2550`);for(let s of r.referenceSites)console.log(` ${s.file}:${j(s.line)} in ${s.enclosingShort}`)}if(r.incomingCalls.length>0){console.log(`
265
- \u2550\u2550\u2550 INCOMING CALLS \u2550\u2550\u2550`);for(let s of r.incomingCalls)console.log(` ${s.file} ${s.shortName}`)}if(r.outgoingCalls.length>0){console.log(`
266
- \u2550\u2550\u2550 OUTGOING CALLS \u2550\u2550\u2550`);for(let s of r.outgoingCalls)console.log(` ${s.file} ${s.shortName}`)}}),OS=Z(({db:e,args:t,opts:n})=>{let i=N(t,0),o=Zs(e,{symbols:[i]},{maxDepth:k(n,"depth",2),maxEdges:k(n,"maxEdges",48)});if(b(n,"json")){P("value-flow",t,n,o);return}de(e,i),o.edges.length===0?A.empty("No proved value transfers found. Missing output is not evidence that no value flow exists; inspect coverage."):A.list(o.edges,r=>` ${Ao(r)}`),console.log(`
267
- Coverage: ${o.coverage.status}; ${o.coverage.basis}.`);for(let r of o.coverage.graph.blindSpots.slice(0,3))console.log(` Blind spot: ${r}`)}),DS=te("slice",({db:e,args:t,opts:n,budget:i})=>{let o=N(t,0),r=b(n,"forward")?"forward":"backward",s=Ws(e,o,{direction:r,maxDepth:k(n,"depth",3),semantic:i.semantic});if(b(n,"json")){P("slice",t,n,Ae(e,o,s,"slice"),{analysisBudget:i.analysisBudget});return}if(!s)return A.empty(me(e,o,"No slice found."));if(de(e,o),console.log(`${s.direction} slice of ${s.shortName}
268
- `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}A.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
269
- ${a.relationship}`),console.log(`
270
- ${s.connectedSymbols.length} connected symbol(s).`)}),qS=te("reference-reachability",({db:e,args:t,opts:n,budget:i})=>{let o=N(t,0),r=b(n,"forward")?"forward":"backward",s=Fs(e,o,{direction:r,maxDepth:k(n,"depth",3),semantic:i.semantic});if(b(n,"json")){P("reference-reachability",t,n,Ae(e,o,s,"reference-reachability"),{analysisBudget:i.analysisBudget});return}if(!s)return A.empty(me(e,o,"No reference reachability found."));de(e,o),console.log(`${s.direction} reference/call reachability from ${s.shortName}
271
- `),A.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
272
- ${a.relationship}`),console.log(`
273
- ${s.connectedSymbols.length} connected symbol(s).`)}),FS=Z(({db:e,args:t,opts:n})=>{let i=N(t,0),o=ea(e,i,{direction:b(n,"forward")?"forward":"backward",maxDepth:k(n,"depth",3),maxEdges:k(n,"maxEdges",200)});if(b(n,"json")){P("dependence-slice",t,n,o);return}console.log(`${o.direction} dependence slice of ${i}
274
- `),o.edges.length===0?A.empty("No proved dependence path found. Missing output is not evidence of absence; inspect coverage."):A.list(o.edges,r=>` depth ${r.traversalDepth} ${r.supporting?"[support] ":""}${Ao(r)}`),console.log(`
275
- Coverage: ${o.coverage.status}; ${o.coverage.basis}; ${o.coverage.criterionKind}.`);for(let r of o.coverage.graph.blindSpots.slice(0,3))console.log(` Blind spot: ${r}`)}),WS=Z(({db:e,args:t,opts:n})=>{let i=N(t,0),o=Lr(e,{className:i});if(b(n,"json")){P("methods",t,n,o,{coverage:_S(o)}),o.kind!=="matched"&&(process.exitCode=1);return}if(o.kind==="matched"){A.list(o.methods,r=>` ${ve(r.startLine,r.endLine)} ${r.name}`);return}A.empty(BS(o)),process.exitCode=1});function _S(e){let t=e.kind==="matched"?e.methods.length:0,n=e.kind==="matched"?{state:"exact",totalCandidates:1}:e.kind==="missing"?{state:"missing",totalCandidates:0}:{state:"ambiguous",totalCandidates:e.total};return{complete:!0,totalKnown:!0,returned:t,total:t,omitted:0,resolution:n}}function BS(e){if(e.kind==="missing"){let n=`No class definition matched '${e.query}'.`;return e.suggestions.length>0?`${n} Suggestions: ${e.suggestions.join(", ")}`:n}let t=e.candidates.map(n=>`${n.relativePath}:${j(n.startLine)}`).join(", ");return`Class '${e.query}' is ambiguous across ${e.total} definitions (${t}). Qualify it with a path or exact SCIP symbol identity.`}var Lp=[...Ja,lt({id:"files",command:"files <pattern>",description:"Find current project files matching a path pattern",agent:C("Which current project files match this path pattern?","matching file paths",["pattern"],"complete"),docs:R("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>sr(e,N(t,0)),format:e=>e.relativePath}),xt({id:"inspect",command:"inspect",description:"Batch related searches, symbols, and source locations into one deduplicated source packet",options:[u("--search <text>","Find this literal text; repeat for related anchors",U,[]),u("--symbol <symbol>","Add definition and use evidence for this symbol; repeat for related owners",U,[]),u("--at <file:line>","Add the smallest readable source unit around this location; repeat as needed",U,[]),u("-s, --scope <path>","Limit literal searches to indexed paths matching this text"),u("-C, --context <n>","Fallback lines around a match with no syntax unit",ze,6),u("-n, --limit <n>","Set matching lines materialized per search (default 12)",pe),u("--max-units <n>","Set the ranked packet unit ceiling (default 48)",pe),u("--max-characters <n>","Set the displayed-evidence character ceiling (default 20000)",pe),u("--view <view>","Render exact source, or raw/normalized behavior chosen by token cost with complete statement accounting (source or behavior; default source)"),u("--allow-large-source",`Explicitly allow an exact-source packet above the ${2e4}-character safety ceiling`),u("--allow-large-behavior",`Explicitly allow a behavioral construct above the ${2e4}-character focus ceiling`),u("--unit-lines <n>","Deprecated compatibility option; inspect now returns complete syntax units",pe),u("--total-lines <n>","Deprecated compatibility option; inspect no longer has a packet line budget",pe),u("--include <part>","Choose symbol evidence; defaults to definition, callers, and callees; repeat or comma-separate",U,[]),u("--evidence-budget <channel=n>","Set an independent unit ceiling for one evidence channel; repeat or comma-separate",U,[]),u("--full","Return all selector matches and materialized units, and run unbounded semantic analysis")],budget:"semantic",agent:{...st("Which related source units across several known text, symbol, or location anchors should be read together?","one ranked, deduplicated semantic packet plus exact selector cardinality and explicit expansion coverage",[],"bounded","repository",fe,Ni(["behavior","construct","exact-source"],["A source packet does not choose which implementation details are relevant to the user task.","A reference mention does not establish executable reachability."],void 0,{manualInput:"One or more exact text, symbol, or file:line selectors naming the unresolved behavior.",evidenceCeiling:"Complete current source for every materialized syntax unit; bounded selector and packet coverage remain explicit."})),contrasts:[{command:"code",distinction:"inspect batches bounded behavior or source gaps; code materializes complete exact source."},{command:"evidence",distinction:"inspect reads implementation units; evidence projects typed relationships without source."}]},docs:R("Navigation",["scip-query inspect --search sessionStreamEvents --search work_session_stream_events --search 'agent:work_session' --view behavior","scip-query inspect --symbol appendEvent --symbol publishEvent --include definition,references,callers,callees","scip-query inspect --at src/api.ts:42 --at src/web.tsx:90"]),query:({db:e,opts:t,budget:n})=>{Li(e.config.projectRoot,"inspect",t.session!==!1);let i=b(t,"full"),o=Pr(e,{searches:O(t,"search"),symbols:O(t,"symbol"),locations:O(t,"at"),scope:w(t,"scope"),context:k(t,"context",6),searchLimit:nS(t),maxUnits:K(t,"maxUnits"),maxCharacters:K(t,"maxCharacters"),view:iS(t),full:i,unitLines:K(t,"unitLines"),totalLines:K(t,"totalLines"),evidence:{parts:ko(O(t,"include")),referenceContext:4,relatedSourceLines:60,semantic:n.semantic},evidenceBudgets:lS(O(t,"evidenceBudget"))});return wS(o,t),SS(o,t),o},coverage:(e,{budget:t})=>{let n=e.searches.reduce((o,r)=>o+r.omittedMatches,0),i=e.units?.length??e.slices.length;return t.analysisBudget||n>0||(e.omittedUnits??0)>0?{complete:!1,totalKnown:!1,returned:i}:{complete:!0,totalKnown:!0,returned:i,total:i,omitted:0}},agentResult:e=>({searches:e.searches,evidence:e.evidence.map(t=>({query:t.query,kind:t.kind})),locations:e.locations,returnedUnits:e.units?.length??e.slices.length,candidateUnits:e.candidateUnits??e.candidateSlices,omittedUnits:e.omittedUnits??e.omittedSlices,view:e.view,omissionGroups:e.omissionGroups,causalFrontier:e.causalFrontier,packetCoverage:e.packetCoverage,stoppingSummary:e.stoppingSummary}),sections:$S}),su({id:"search",command:"search <exact-text>",description:"Count current project text matches and preview a bounded, recoverable identity and source manifest",options:[u("-s, --scope <path>","Limit the search to current project paths matching this text"),u("-C, --context <n>","Source lines before and after each representative match",ze,2),u("-n, --limit <n>","Representative source windows to materialize; exact identity manifests remain separately accounted",pe,6),u("--full","Materialize source for every match after deliberately narrowing broad selectors"),u("--regexp","Treat the search text as a bounded regular expression"),u("-i, --ignore-case","Ignore case")],agent:{...st("Where does this exact text occur in current project text, and which aligned compiler symbol owns each line?","exact cardinality, bounded identities and source, and scope commands that recover withheld matches",["pattern"],"bounded",void 0,fe,At(["text","symbol","construct","runtime-key"],["Structural source ranking orders exact matches but does not establish task relevance.","A literal co-occurrence does not establish a graph relationship."],{ranking:"identity-only",manualInput:"One exact text literal or deliberately bounded regular expression; insert `--` before a literal that starts with a dash.",evidenceCeiling:"Exact current-text cardinality and locations within reported text coverage; compiler ownership only where aligned."})),contrasts:[{command:"outline",distinction:"search locates exact text across files; outline enumerates compiler-owned constructs in one known file."}]},docs:R("Navigation",["scip-query search 'eventName'","scip-query search -- '--config'","scip-query search 'send.*event' --regexp --scope src"]),query:({db:e,args:t,opts:n})=>ar(e,N(t,0),yp(n)),precomputed:({args:e,opts:t})=>mp(ue(),N(e,0),yp(t)),emptyMessage:e=>e.matchingLines===0?`${To(e)?"No current project text line":"No scanned project text line"} matched '${e.pattern}'.`:void 0,coverage:e=>{let t=Ep(e).length;return To(e)?{complete:!0,totalKnown:!0,returned:t,total:e.matchingLines,omitted:0}:{complete:!1,totalKnown:!1,returned:t}},agentResult:e=>({identityCoverage:e.identityCoverage,mode:e.mode,scannedFiles:e.scannedFiles,returnedMatches:li(e).length,totalMatches:e.matchingLines,omittedMatches:kp(e,li(e)).omitted,materializedSourceWindows:e.matches.length,unmaterializedSourceWindows:e.omittedMatches,matchIdentities:li(e).map(t=>`${t.relativePath}:${j(t.focusLine)}`),scopeHints:e.scopeHints,omittedScopeHints:e.omittedScopeHints,textCoverage:e.textCoverage}),sections:dS}),mo({id:"anchors",command:"anchors <question>",hidden:!0,description:"Deprecated compatibility view for query-vocabulary candidate groups; use exact locators plus evidence",options:[u("-s, --scope <path>","Limit candidate ownership and text evidence to indexed paths matching this text"),u("-n, --limit <n>","Connected anchor sets to return; omitted candidates remain counted",pe,4),u("--full","Analyze every candidate anchor group with semantic enrichment")],agent:st("Which small graph-connected code regions contain repository vocabulary from this question?","ranked candidate owners, two-hop compiler call evidence, exact map commands, and an omission ledger",["pattern"],"bounded",void 0,fe,At(["text","symbol","construct"],["Connected candidate groups are compatibility navigation hints, not inferred task relevance.","Candidate grouping does not establish implementation behavior."],{ranking:"identity-only",compatibility:"deprecated"})),docs:R("Compatibility"),query:({db:e,args:t,opts:n})=>{let i=kr(e,N(t,0),{scope:w(n,"scope"),limit:D(n,"limit",4),full:b(n,"full"),semantic:b(n,"full")});return Da(e.config.projectRoot,i.groups.map(o=>o.systemMapCommand),n.session!==!1),i},emptyMessage:e=>e.candidateRootCount===0?`No compiler-owned repository construct matched the normalized terms: ${e.normalizedTerms.join(", ")}.`:void 0,coverage:e=>e.omittedRootCount===0&&e.omittedGroupCount===0?{complete:!0,totalKnown:!0,returned:e.candidateRootCount,total:e.candidateRootCount,omitted:0}:{complete:!1,totalKnown:!0,returned:e.analyzedRootCount,total:e.candidateRootCount,omitted:e.omittedRootCount},agentResult:e=>({normalizedTerms:e.normalizedTerms,matchedTerms:e.matchedTerms,unmatchedTerms:e.unmatchedTerms,candidateRoots:e.candidateRootCount,analyzedRoots:e.analyzedRootCount,omittedRoots:e.omittedRootCount,omittedAnchorSets:e.omittedGroupCount,anchorSets:e.groups.map(t=>({roots:t.roots.map(n=>({symbol:n.symbol,file:n.file,line:j(n.line),matchedTerms:n.matchedTerms})),keyAnchors:t.keyAnchors.map(n=>({file:n.file,line:j(n.line)})),relations:t.relations,systemMapCommand:t.systemMapCommand})),recoveryCommand:e.recoveryCommand}),sections:fS}),{id:"methods",command:"methods <className>",description:"List methods of one exactly resolved class; ambiguity and missing targets fail explicitly",options:x(),agent:{...C("Which methods belong to this class?","method names and line ranges",["symbol"],"complete"),resultUnits:{kind:"field",field:"methods"}},docs:R("Navigation"),renderShape:"list",handler:WS},xt({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[u("--full","Run unbounded semantic analysis on large indexes"),ji()],budget:"semantic",agent:{operation:fe,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",semantic:Xt("Resolve one symbol definition and its indexed reference sites.","Definition source and signatures plus referencing files and line numbers.",["Flat reference sites do not establish runtime calls, data flow, or task relevance."]),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:R("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Ir(e,N(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?me(t,N(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>de(t,N(n,0)),toJson:(e,{db:t,args:n})=>({...Zt(t,N(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:oS}),xt({id:"evidence",command:"evidence",description:"Traverse selected typed relationships around exact referents; recover source separately when needed",options:[u("--symbol <symbol>","Add an exact compiler symbol; repeat to batch",U,[]),u("--at <file:line>","Add the construct owning an exact source location; repeat to batch",U,[]),u("--search <literal>","Add an exact source or runtime literal; repeat to batch",U,[]),u("--view <view>","Select causal, structure, or complete graph evidence"),u("--edge <family>","Select execution, runtime, dataflow, state, temporal, contract, identity, ownership, dependencies, or all; repeat or comma-separate",U,[]),u("--direction <direction>","Traverse incoming, outgoing, or both directed relationships"),u("--subtype <subtype>","Select exact relationship subtypes; repeat or comma-separate",U,[]),u("--connecting","Return deterministic shortest paths connecting the resolved roots"),u("--inventory-only","Count relationships by family, subtype, and direction without rendering edges"),u("--fold <id>","Materialize an exact recoverable fold from the same projection; repeat to batch",U,[]),u("--depth <n>","Required maximum graph traversal depth",ze),u("--max-edges <n>","Required maximum typed relationships to render",pe),{...u("--include <part>","Compatibility only: defer requested source parts to an exact inspect recovery command",U,[]),hidden:!0},u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",agent:{operation:fe,answers:["Which exact execution, runtime, data, state, temporal, contract, identity, ownership, or dependency relationships surround these referents?","Which related source must be read only when graph evidence leaves a named implementation gap?"],returns:["batched exact selectors and typed graph relationships","compact endpoints with exact locations and follow-up commands","coverage and recoverable omissions","exact source-recovery command when source was requested with a graph projection","explicit ambiguity failure with exact rerun commands"],inputs:[],scope:"repository",coverage:"bounded",semantic:Yt({rootKinds:["text","symbol","construct","runtime-key","state-resource"],edgeFamilies:ot,directions:["incoming","outgoing","both"],operations:["adjacency","reachability","connecting","slice"],compression:["none","linear","scc","topology"],nonClaims:["The projection does not infer which relationships are relevant to the user task.","Reference, dependency, data, state, temporal, contract, and identity edges do not become execution claims."],manualInput:"One or more exact symbol, file:line, or literal roots plus explicit family, direction, depth, and output bound.",evidenceCeiling:"Typed edges only to each registered provider ceiling within the explicitly selected projection and reported coverage."}),contrasts:[{command:"refs",distinction:"refs enumerates direct reference sites; evidence traverses explicitly selected typed relationships."},{command:"call-graph",distinction:"call-graph specializes in static calls; evidence can combine execution with other selected families."},{command:"value-flow",distinction:"value-flow specializes in proved transfers; evidence projects bounded dataflow alongside other families."},{command:"dependence-slice",distinction:"dependence-slice computes a program-dependence slice; evidence performs bounded graph projection."}]},docs:R("Navigation",["scip-query evidence --symbol 'exact-symbol' --edge execution --edge dataflow --direction both --depth 2 --max-edges 32","scip-query evidence --symbol 'first' --symbol 'second' --edge runtime --direction both --depth 3 --max-edges 32 --connecting","scip-query evidence --at 'src/file.ts:40' --edge runtime --edge state --edge contract --direction outgoing --depth 2 --inventory-only"]),query:({db:e,opts:t})=>{let n=O(t,"symbol"),i=O(t,"at"),o=O(t,"search"),r=sS(w(t,"view")),s=rS(O(t,"edge")),a=aS(w(t,"direction")),c=cS(O(t,"subtype")),l=b(t,"connecting"),d=b(t,"inventoryOnly"),m=O(t,"fold"),h=K(t,"depth"),p=K(t,"maxEdges");if(s===void 0)throw new Error("Graph evidence requires at least one explicit --edge <family>; repeat --edge to select several relationship families.");if(a===void 0)throw new Error("Graph evidence requires explicit --direction incoming, outgoing, or both.");if(h===void 0)throw new Error("Graph evidence requires an explicit finite --depth <n>.");if(!d&&p===void 0)throw new Error("Materialized graph evidence requires an explicit finite --max-edges <n>.");let f=ko(O(t,"include")),g=[...n,...i],y=f===void 0?null:{parts:f,selectors:g.length,command:["scip-query inspect",...n.map(v=>`--symbol ${Le(v)}`),...i.map(v=>`--at ${Le(v)}`),"--view source",`--include ${Le(f.join(","))}`].join(" ")};return{kind:"graph-packet",graph:Or(e,{symbols:n,locations:i,searches:o},{view:r,families:s,direction:a,subtypes:c,connecting:l,inventoryOnly:d,foldIds:m,maxDepth:h,maxEdges:p??1}),source:[],sourceRecovery:y}},before:e=>{e.graph.targets.some(t=>t.status!=="matched")&&(process.exitCode=1)},coverage:e=>{let t=e.graph.edges.length,n=e.graph.targets.every(r=>r.status==="matched"),i=e.sourceRecovery!==null;return e.graph.coverage.status==="accounted"&&n&&!i?{complete:!0,totalKnown:!0,returned:t,total:t,omitted:0}:e.graph.coverage.status==="incomplete"||!n||i?{complete:!1,totalKnown:!1,returned:t}:{complete:!1,totalKnown:!0,returned:t,total:t+e.graph.coverage.omittedEdges,omitted:e.graph.coverage.omittedEdges}},agentResult:e=>({view:e.graph.view,families:e.graph.families,selection:e.graph.selection,targets:e.graph.targets,inventory:e.graph.inventory,relationshipCount:e.graph.edges.length,coverage:e.graph.coverage,sourceSelectors:e.source.length,sourceRecovery:e.sourceRecovery}),sections:AS}),xt({id:"evidence-source",command:"evidence-source <symbol>",description:"Deprecated compatibility path for positional source evidence; use inspect or code",hidden:!0,options:[u("--include <part>","Source parts to include",U,[]),u("-C, --context <n>","Source lines before and after each reference",ze,2),u("--related-source-lines <n>","Maximum source lines for each caller or callee",pe,80),u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",agent:{operation:fe,answers:["Which legacy definition, reference, caller, callee, dependency, and consumer source surrounds this symbol?"],returns:["deprecated qualified source-evidence packet"],inputs:["symbol"],coverage:"bounded",semantic:Ni(["construct","exact-source"],["This compatibility read does not establish graph reachability beyond its rendered evidence."],"deprecated")},docs:R("Compatibility"),query:({db:e,args:t,opts:n,budget:i})=>(Li(e.config.projectRoot,"evidence",n.session!==!1),Ar(e,N(t,0),{parts:ko(O(n,"include")),referenceContext:k(n,"context",2),relatedSourceLines:k(n,"relatedSourceLines",80),semantic:i.semantic})),emptyMessage:e=>Ip(e),before:e=>{e.kind!=="matched"&&(process.exitCode=1)},coverage:(e,{budget:t})=>{if(e.kind!=="matched")return{complete:!0,totalKnown:!0,returned:0,total:0,omitted:0};let n=(e.definition?1:0)+e.referenceWindows.reduce((i,o)=>i+o.references.length,0)+e.callers.length+e.callees.length+e.dependencies.length+e.consumers.length;return t.analysisBudget?{complete:!1,totalKnown:!1,returned:n}:{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}},agentResult:e=>e.kind==="matched"?{symbol:e.symbol,file:e.file,parts:e.parts,referenceSites:e.referenceWindows.reduce((t,n)=>t+n.references.length,0),sourceWindows:e.referenceWindows.length,callers:e.callers.length,callees:e.callees.length,dependencies:e.dependencies.length,consumers:e.consumers.length}:e,sections:Io}),lt({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",agent:C("Which internal files does this file depend on?","dependency file paths",["file"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Er(e,N(t,0)),format:e=>e.relativePath}),lt({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",agent:C("Which internal files depend on this file?","reverse-dependency file paths",["file"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Tr(e,N(t,0)),format:e=>e.relativePath}),mo({id:"system",command:"system <module>",description:"One-hop module summary: matched files, documented symbols, and file reference dependencies",options:[ji()],agent:{operation:fe,answers:["Which files and documented symbols match this module selector?","What one-hop file reference dependencies cross the selected module?"],returns:["module file paths","documented indexed symbols with line ranges","internal dependencies","reverse dependencies"],inputs:["module"],coverage:"complete",semantic:Xt("Summarize files, documented symbols, and one-hop file reference dependencies for a module selector.","Matched files, documented indexed symbols, dependencies, and reverse dependencies.",["A one-hop module summary does not establish runtime execution or complete transitive behavior."]),contrasts:[{command:"surface",distinction:"system lists documented indexed symbols; surface lists callable symbols that external consumers actually use."},{command:"outline",distinction:"system is module-scoped; outline covers a single file."}]},docs:R("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Dr(e,N(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 documented indexed symbols with their line ranges"}}),sections:e=>[{title:"FILES",rows:e.files},{title:"DOCUMENTED INDEXED SYMBOLS",rows:e.symbols.map(t=>` ${ve(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}`)}]}),lt({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",agent:C("Which exported symbols do external consumers actually use?","consumer paths and consumed symbol identities",["module"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>qr(e,N(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",agent:C("Which symbols does this file import?","imported symbol identities and source files",["file"],"bounded"),options:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:R("Navigation"),handler:jS},lt({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",agent:C("Which files import this symbol?","importing file paths",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Br(e,N(t,0)),format:e=>` ${e.fromFile}`}),lt({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",agent:C("Which members or nested symbols belong to this symbol?","child symbol identities, kinds, and ranges",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>Vr(e,N(t,0)),format:e=>` ${ve(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>de(t,N(n,0)),emptyMessage:({db:e,args:t})=>me(e,N(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>Ae(t,N(n,0),e,"members")}),lt({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",agent:C("Which symbols have this SCIP kind?","symbol identities, kinds, files, and ranges",["pattern"],"bounded"),options:[u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",S,100),u("--full","Run unbounded analysis on large indexes")],docs:R("Navigation"),query:({db:e,args:t,opts:n})=>es(e,N(t,0),{scope:w(n,"scope"),limit:D(n,"limit",100)}),format:e=>` ${V(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${N(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
276
- ${e.length} symbol(s)`)}),ei({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",agent:C("How many indexed symbols exist for each kind?","symbol-kind counts",[],"complete","repository"),options:[u("-s, --scope <path>","Limit to files matching path")],docs:R("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>ts(e,{scope:w(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),lt({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",agent:C("What lexical ownership chain contains this symbol?","ancestor symbol identities and depths",["symbol"],"complete"),docs:R("Navigation"),query:({db:e,args:t})=>is(e,N(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>de(t,N(n,0)),emptyMessage:({db:e,args:t})=>me(e,N(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>Ae(t,N(n,0),e,"hierarchy")}),{id:"dataflow",command:"dataflow <symbol>",hidden:!0,description:"Deprecated compatibility alias for a reference/call neighborhood; use value-flow",agent:C("What definitions, references, incoming calls, and outgoing calls surround this symbol?","legacy reference sites and call-neighborhood rows; no value-flow claim",["symbol"],"bounded"),options:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:NS},{id:"reference-neighborhood",command:"reference-neighborhood <symbol>",description:"Show definition/reference sites and incoming/outgoing static calls without value-flow claims",agent:C("What exact references and static calls surround this symbol?","definition sites, reference sites, incoming calls, and outgoing calls",["symbol"],"bounded"),options:x([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:MS},{id:"value-flow",command:"value-flow <symbol>",description:"Show only proved argument/parameter and bounded static-value transfers around a symbol",agent:C("Which values are proved to flow into or through this symbol?","typed value-transfer edges with evidence strength and explicit unsupported relations",["symbol"],"bounded"),options:x([u("--depth <n>","Maximum graph depth",S,2),u("--max-edges <n>","Maximum typed value-transfer edges",S,48)]),renderShape:"custom",docs:R("Navigation"),handler:OS},{id:"slice",command:"slice <symbol>",hidden:!0,description:"Deprecated compatibility alias for reference/call reachability; use dependence-slice",agent:C("Which calls or reference owners are reachable from this symbol under the legacy traversal?","legacy connected symbols; no program-dependence claim",["symbol"],"bounded"),options:x([u("--forward","Forward slice (what does this affect). Default is backward."),u("--depth <n>","Max transitive depth for backward slice",S,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:DS},{id:"reference-reachability",command:"reference-reachability <symbol>",description:"Traverse legacy callee or reference-owner reachability without calling it a program slice",agent:C("Which call/reference nodes are reachable from this symbol?","connected symbols with relationship and traversal depth",["symbol"],"bounded"),options:x([u("--forward","Traverse reference owners. Default traverses callees."),u("--depth <n>","Maximum callee depth",S,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:R("Navigation"),handler:qS},{id:"dependence-slice",command:"dependence-slice <symbol-or-location>",description:"Directional slice over proved data/control dependencies with explicit supporting call edges",agent:C("What proved program dependencies can affect this criterion, or be affected by it?","directional dependence edges, supporting connectors, and coverage limits",[["symbol","path"]],"bounded"),options:x([u("--forward","Compute a forward slice. Default is backward."),u("--depth <n>","Maximum dependence traversal depth",S,3),u("--max-edges <n>","Maximum topology edges considered",S,200)]),renderShape:"custom",docs:R("Navigation"),handler:FS}];var GS=te("context",({db:e,args:t,opts:n,budget:i})=>{let o=D(n,"limit",20),r=qe(e.config.projectRoot).gitContext?.headCommit,s=_s(e,N(t,0),{semantic:i.semantic,impactDepth:k(n,"impactDepth",3),sliceDepth:k(n,"sliceDepth",3),scope:w(n,"scope"),...r?{gitHead:r}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(b(n,"json")){P("context",t,n,{...Zt(e,N(t,0)),...s},{analysisBudget:i.analysisBudget,coverage:jp(s),agentResult:Np(s)});return}return A.empty(me(e,N(t,0)))}if(b(n,"json")){let c=s.primaryCallable?.symbol??N(t,0);P("context",t,n,s.matched.symbol?{...Zt(e,c),...s}:s,{analysisBudget:i.analysisBudget,coverage:jp(s),agentResult:Np(s)});return}s.matched.symbol&&de(e,s.primaryCallable?.symbol??N(t,0));let a=b(n,"detail")?US(s,o):VS(s,N(t,0),o,k(n,"impactDepth",3),k(n,"sliceDepth",3));A.sectionedReport(a)}),Mp=[{id:"context",command:"context <target>",description:"Compiler-backed context for a symbol, file, or module",options:Fa([u("--impact-depth <n>","Maximum affected traversal depth",S,3),u("--slice-depth <n>","Maximum backward slice depth",S,3),u("-s, --scope <path>","Limit downstream impact to files matching path"),u("-n, --limit <n>","Rows per section",S,20),u("--detail","Render every planning component instead of the compact decision packet"),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",claims:Je(["index-generation","live-workspace"],[X("compiler-graph","trace","compiler-graph"),X("semantic-flow","dataflow","semantic-analysis"),X("change-history","history","change-history"),X("planning-notes","warnings[]","heuristic")]),agent:{operation:fe,answers:["How is this target connected to the rest of the repository?","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","reuse candidates with evidence class and action tier","possible shared owners found from a bounded scan of affected consumers"],inputs:[["symbol","file","module"]],coverage:"bounded",semantic:Xt("Assemble bounded compiler, semantic, history, and heuristic context around one explicit target.","A multi-section repository context report with each evidence family kept distinct.",["This composite report does not infer task relevance or prove that every returned candidate affects the requested change."]),contrasts:[{command:"change-surface",distinction:"change-surface is the exports/consumers/risk briefing alone; context includes flow, slices, history, and reuse signals."}]},renderShape:"custom",docs:R("Exploration",["scip-query context parseSymbol"]),handler:GS}];function VS(e,t,n,i,o){return[{title:"TARGET",rows:Dp(e)},{title:"CURRENT FLOW",rows:HS(e,n),skipIfEmpty:!0},{title:"AFFECTED CONSUMERS",rows:QS(e,n),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:Op(e,Math.min(n,12)),skipIfEmpty:!0},{title:"CHANGE CONSTRAINTS",rows:KS(e,n),skipIfEmpty:!0},{title:"RELATED SOURCE IDENTITIES",rows:zS(e,n),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:qp(e),skipIfEmpty:!0},{title:"COVERAGE AND RECOVERY",rows:JS(e,t,i,o)}]}function US(e,t){return[{title:"TARGET",rows:Dp(e)},{title:"DEFINITIONS",rows:Fp(e,t),skipIfEmpty:!0},{title:"REFERENCES",rows:ZS(e,t),skipIfEmpty:!0},{title:"CALL GRAPH",rows:Wp(e,t),skipIfEmpty:!0},{title:"DATAFLOW",rows:_p(e,t),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:Op(e,t),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:qp(e),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:ew(e,t),skipIfEmpty:!0},{title:"SURFACE",rows:tw(e,t),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:nw(e,t),skipIfEmpty:!0},{title:"CHANGE RISK",rows:iw(e,t),skipIfEmpty:!0},{title:"HISTORY",rows:Bp(e),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:Gp(e),skipIfEmpty:!0}]}function HS(e,t){return De(je([...Fp(e,Math.min(t,12)),...Wp(e,t),..._p(e,t)],t))}function QS(e,t){let n=e.trace.referencedBy.map(o=>` direct ${o.relativePath}:${j(o.line)} ${o.enclosingShort}`),i=e.affected.map(o=>` depth ${o.depth} ${o.file} ${o.shortName}`);return De(je(YS([...n,...i]),t))}function KS(e,t){let n=[...e.changeSurface?[` External consumers: ${e.changeSurface.totalExternalConsumers}`,` Changed-file risk factors: ${e.changeSurface.fileRisk?.reasons.length??0}`]:[],` Dependencies: ${e.deps.length}; reverse dependencies: ${e.rdeps.length}`,` Module files: ${e.system.files.length}; exported symbols: ${e.system.symbols.length}; external surface uses: ${e.surface.length}`,...Bp(e),...Gp(e)];return De(je(n,t))}function zS(e,t){let n=[...e.trace.definitions.map(i=>i.relativePath),...e.trace.referencedBy.map(i=>i.relativePath),...e.callGraph?.callers.map(i=>i.file)??[],...e.callGraph?.callees.map(i=>i.file)??[],...e.reuseCandidates?.map(i=>i.fileB)??[],...qt(e).candidates.map(({candidate:i})=>i.fileB)];return De(je([...new Set(n.filter(i=>i.trim().length>0))].map(i=>` ${i}`),Math.min(t,12)))}function JS(e,t,n,i){let o=qt(e).coverage,r=[` Direct compiler references observed: ${e.trace.referencedBy.length}.`,` Downstream and slice evidence is bounded at impact depth ${n} and slice depth ${i}.`,` Affected-consumer reuse scan: ${o.analyzedConsumers}/${o.totalConsumers} analyzed; ${o.omittedConsumers} omitted.`];return e.sourcePacket&&(r.push(` Source packet: ${e.sourcePacket.slices.length}/${e.sourcePacket.candidateSlices} slice(s); ${e.sourcePacket.omittedSlices} omitted; at most ${e.sourcePacket.maxSlices} slices, ${e.sourcePacket.maxLinesPerSlice} lines per slice, and ${e.sourcePacket.maxTotalLines} lines total.`),e.sourcePacket.targetLineLimit!==void 0&&e.sourcePacket.consumerContextLines!==void 0&&e.sourcePacket.reuseLineLimit!==void 0&&r.push(` Source roles: target up to ${e.sourcePacket.targetLineLimit} lines; consumer windows center on each use with ${e.sourcePacket.consumerContextLines} context lines; reuse candidates use up to ${e.sourcePacket.reuseLineLimit} lines.`)),e.warnings.length>0&&r.push(...e.warnings.map(s=>` Warning: ${s}`)),r.push(` Use scip-query refs ${t} --full only when a complete direct-consumer set can change the plan.`,` Use scip-query context ${t} --detail only when this packet leaves a named planning uncertainty.`),r}function YS(e){return[...new Set(e)]}function jp(e){return{complete:!1,totalKnown:!1,returned:XS(e)}}function XS(e){let t=qt(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+(e.reuseCandidates?.length??0)+t.coverage.analyzedConsumers+t.candidates.length+(e.sourcePacket?.slices.length??0)}function Np(e){let t=qt(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,reuseCandidates:e.reuseCandidates?.length??0,affectedConsumersAnalyzed:t.coverage.analyzedConsumers,consumerReuseCandidates:t.candidates.length,externalSurfaceUses:e.surface.length,coChangePartners:e.history.coChangePartners.length,sourceSlices:e.sourcePacket?.slices.length??0},warnings:e.warnings,changeSurface:e.changeSurface?{file:e.changeSurface.file,totalExternalConsumers:e.changeSurface.totalExternalConsumers,fileRisk:e.changeSurface.fileRisk,riskCounts:{high:e.changeSurface.symbols.filter(n=>n.riskLevel==="high").length,medium:e.changeSurface.symbols.filter(n=>n.riskLevel==="medium").length,low:e.changeSurface.symbols.filter(n=>n.riskLevel==="low").length}}:null,history:e.history,affectedConsumerReuse:t}}function Op(e,t){let n=(e.reuseCandidates??[]).flatMap(c=>[` target ${Math.round(c.similarity*100)}% ${c.evidenceClass} ${c.shortNameB} ${c.fileB}`,` basis=${c.similarityBasis??"unknown"}; ${c.evidenceClassReasons.join("; ")}`]),i=qt(e),o=i.candidates.flatMap(({candidate:c,consumers:l})=>[` consumer ${Math.round(c.similarity*100)}% ${c.evidenceClass} ${c.shortNameB} ${c.fileB}`,` basis=${c.similarityBasis??"unknown"}; observed from ${l.map(d=>d.shortName).join(", ")}; ${c.evidenceClassReasons.join("; ")}`]),r=i.coverage,s=r.totalConsumers>0?[` Affected-consumer scan: ${r.analyzedConsumers}/${r.totalConsumers} compiler-resolved consumer(s) analyzed; ${r.omittedConsumers} omitted; first ${r.perConsumerSearchLimit} similarity result(s) checked and up to ${r.perConsumerCandidateLimit} usable option(s) kept per consumer.`]:[],a=[...n,...s,...o];return De(je(a,t))}function Dp(e){let t=[`Target: ${e.target}`,`Matched: symbol=${Po(e.matched.symbol)} file=${Po(e.matched.file)} module=${Po(e.matched.module)}`];return e.primaryCallable&&t.push(`Primary callable: ${e.primaryCallable.shortName} ${e.primaryCallable.file}`),t}function qp(e){if(!e.sourcePacket||e.sourcePacket.slices.length===0)return[];let t=[];for(let n of e.sourcePacket.slices)t.push(` ${n.role.padEnd(15)} ${V(n.file,n.startLine,n.endLine)} ${n.shortName}`),t.push(...n.source.split(`
277
- `).map((i,o)=>{let r=n.startLine+o;return` ${n.focusLines?.includes(r)?">":" "}${String(j(r)).padStart(4)} ${i}`})),n.omittedLines>0&&t.push(` ... ${n.omittedLines} more line(s) in this callable`);return e.sourcePacket.omittedSlices>0&&t.push(` ... ${e.sourcePacket.omittedSlices} more candidate slice(s)`),t}function Fp(e,t){let n=[];for(let i of e.trace.definitions){let o=i.signature?` -- ${i.signature}`:"";n.push(` ${V(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&n.push(...i.source.split(`
278
- `).map((r,s)=>` ${String(j(i.startLine+s)).padStart(4)} ${r}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${ve(i.startLine,i.endLine)} ${i.shortName}`)),je(n,t).rows}function ZS(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${j(i.line)} in ${i.enclosingShort}`);return De(je(n,t))}function Wp(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(o=>` caller ${o.file} ${o.shortName}`),i=e.callGraph.callees.map(o=>` callee ${o.file} ${o.shortName}`);return De(je([...n,...i],t))}function _p(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(r=>` producer ${r.file} ${r.shortName}`),i=e.dataflow.consumers.map(r=>` consumer ${r.file} ${r.shortName}`),o=e.dataflow.usageSites.map(r=>` usage ${r.file}:${j(r.line)} in ${r.enclosingShort}`);return De(je([...n,...i,...o],t))}function ew(e,t){let n=[...e.deps.map(i=>` file depends on ${i.relativePath}`),...e.rdeps.map(i=>` file depended on by ${i.relativePath}`),...e.system.dependsOn.map(i=>` module depends on ${i}`),...e.system.dependedOnBy.map(i=>` module used by ${i}`)];return De(je(n,t))}function tw(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${ve(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return De(je(n,t))}function nw(e,t){let n=[],i=-1;for(let o of e.affected)o.depth!==i&&(n.push(` -- Depth ${o.depth} --`),i=o.depth),n.push(` ${o.file} ${o.shortName}`);return De(je(n,t))}function iw(e,t){let n=[];return e.changeSurface&&(n.push(` File: ${e.changeSurface.file}`),n.push(` External consumers: ${e.changeSurface.totalExternalConsumers}`),e.changeSurface.fileRisk&&e.changeSurface.fileRisk.reasons.length>0&&n.push(` File risk factors (${e.changeSurface.fileRisk.coverage} metadata): ${e.changeSurface.fileRisk.reasons.map(i=>`${i.kind}: ${i.detail}`).join("; ")}`),n.push(...e.changeSurface.symbols.map(i=>{let o=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"",r=i.riskReasons??[],s=r.length===0?"":` [why: ${r.map(a=>`${a.kind}: ${a.detail}`).join("; ")}]`;return` ${ve(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${o}${s}`}))),e.complexity&&(n.push(` Complexity: ${V(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}`)),De(je(n,t))}function Bp(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let i=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${i}`)}for(let i of t.coChangePartners)n.push(` Usually changes with: ${i.file} (${i.together}x, ${Math.round(i.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function Gp(e){let t=e.warnings.map(i=>` ${i}`);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(i=>i.riskLevel==="high")??[]).length>0&&t.push(" Inspect high-risk consumers before editing public behavior."),e.changeSurface?.fileRisk?.operationalRoot&&t.push(" This file is an operational root; validate its launch and shutdown path even when source fan-in is zero."),e.affected.length>0&&t.push(" Validate downstream consumers at the shallowest affected depths first."),e.reuseCandidates?.some(i=>i.actionTier==="direct")&&t.push(" A direct reuse option requires a responsibility and behavior comparison. Reuse the existing owner when they match. Current wiring or reachability alone does not justify separate ownership; rejection needs a concrete behavioral or boundary difference."),qt(e).candidates.length>0&&t.push(" An affected-consumer reuse option can own surrounding behavior that target-only comparison cannot see. Compare each direct option before editing, and keep duplicate ownership only for a concrete behavioral or boundary difference."),t}function qt(e){return e.affectedConsumerReuse??{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:0,perConsumerCandidateLimit:0,candidateLimit:0,returnedCandidates:0}}}function je(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function De(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function Po(e){return e?"yes":"no"}import{existsSync as hn}from"fs";import{existsSync as ow,mkdtempSync as rw,rmSync as sw}from"fs";import{tmpdir as aw}from"os";import{dirname as Lo,join as cw}from"path";import{performance as Vp}from"perf_hooks";import{spawnSync as lw}from"child_process";var dw=12e4,Qp="v1.8.0",uw=`https://github.com/tlaplus/tlaplus/releases/download/${Qp}/tla2tools.jar`,pw="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function ui(e){let t=e.spawn??lw,n=mw(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 i=e.timeoutMs??dw,o=Vp.now(),r;try{r=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:i,killSignal:"SIGKILL",maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])sw(l,{recursive:!0,force:!0})}let s=Math.round(Vp.now()-o),a=r.error?.name==="ETIMEDOUT"||r.signal==="SIGTERM"&&s>=i,c=a?"timed-out":r.status===0?"passed":"failed";return{checker:n.checker,status:c,command:n.command,durationMs:s,exitCode:r.status,signal:r.signal,timedOut:a,diagnostics:hw(c,r.stdout??"",r.stderr??""),stdout:r.stdout??"",stderr:r.stderr??""}}function mw(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"&&it(Up(e),t)){let r=Up(e);return it(r,t)?{checker:"apalache",command:[r,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:Lo(e.specPath)}:di("apalache",`Apalache binary is not available: ${r}`)}let i=jo(e),o=it("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!i)return di(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!o)return di(n==="sany"?"sany":"tlc","java is not available on PATH");let r=n==="sany"?"sany":n==="tlc"||e.configPath?"tlc":"sany";if(r==="sany")return{checker:r,command:["java","-cp",i,"tla2sany.SANY",e.specPath],cwd:Lo(e.specPath)};let s=e.metaDir??rw(cw(aw(),"scip-tla-tlc-"));return{checker:r,command:["java","-cp",i,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:Lo(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return di("none",`unknown checker mode: ${n}`)}function Up(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function jo(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Kp(t)].filter(i=>typeof i=="string"&&i.length>0).find(i=>ow(i))??null}function Kp(e=process.env){return Ya("tla2tools.jar",e)}async function zp(e={}){let t=e.cachePath??Kp(e.env),n=e.expectedSha256??pw,i=e.version??Qp,o=e.url??uw;return{...await Xa({cachePath:t,url:o,expectedSha256:n,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,maxBytes:e.maxBytes,signal:e.signal}),version:i,url:o}}function hw(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 i=[...Hp(n),...Hp(t)].slice(0,20);return i.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:i.map(o=>({severity:"error",message:o}))}function Hp(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function di(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as fw}from"crypto";var Yp=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),Xp=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),Zp=new Set(["readFileSync","existsSync","statSync"]),gw=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,yw=/^\s*SELECT\b/i;function em(e){return gw.test(e)?"write":yw.test(e)?"read":null}var bw=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function vw(e,t){let n=e.match(bw);if(!n)return!1;let i=e.slice(n[0].length);return new RegExp(`^${wt(t)}\\b`).test(i)}function tm(e,t,n,i=[],o=[]){let r=[],s=$w(e,t,r),a=s.aliases,c=Rw(t),l=xw(t),d=Cw(t),m=Tw(e,t,r),h=Aw(e,t,r);n&&Pw(t,n,o,r);let p=new Map((n?.actions??[]).map($=>[$.name,$])),f=new Set(m.flatMap($=>$.referents.map(L=>L.match?.symbol).filter(Boolean))),g=new Set((h?.referents??[]).map($=>$.match?.symbol).filter(Boolean)),y=Lw(e,t,m,a,c,l,d,f,g,r,p),v=Mw(e,m,a,c,l,d,r,p);return Dw(e,m,r),qw(t,i,r),{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:Mo(m.flatMap($=>$.referents))+Mo(s.referents)+Mo(h?.referents??[]),staticWrites:y,staticReads:v,waivers:o$(t),checkedInvariants:[...o],traceStepsChecked:i.length,findings:r,findingGroups:Sw(r)}}function Sw(e){let t=new Map;for(let n of e){let i=`${n.category}:${n.modelElement??"-"}`,o=t.get(i);o||(o={groupKey:i,category:n.category,modelElement:n.modelElement,severity:n.severity,count:0,findingIds:[]},t.set(i,o)),o.count+=1,o.findingIds.push(n.id),o.severity=ww(o.severity,n.severity)}return[...t.values()].sort((n,i)=>i.count-n.count||pi(i.severity)-pi(n.severity)||n.groupKey.localeCompare(i.groupKey))}function ww(e,t){return pi(t)>pi(e)?t:e}function pi(e){return e==="error"?2:e==="warning"?1:0}function $w(e,t,n){let i=[],o=[];for(let[r,s]of Object.entries(t.variables)){let a=new Set(s.aliases),c=!!s.waive;for(let l of s.code){let d=fi(e,l,n,r);o.push(d);let m=d.match;if(!m){c||n.push(Q("missing-referent","error","compiler-symbol",{modelElement:r,codeRef:l,message:`TLA+ variable ${r} 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.${r}.code to a live symbol, or remove the variable from the model mapping.`}));continue}Xw(e,r,l,m,n,c),s.aliases.length===0&&a.add(rr(m.symbol))}for(let l of a)i.push({variable:r,alias:l})}return{aliases:i$(i),referents:o}}function Rw(e){let t=[];for(let[n,i]of Object.entries(e.variables))i.resource&&t.push({variable:n,path:i.resource.path});return t}function xw(e){let t=[];for(let[n,i]of Object.entries(e.variables))for(let o of i.statements??[])t.push({variable:n,pattern:o.pattern,regex:gn(o.pattern,`variables.${n}.statements pattern`)});return t}function Cw(e){let t=[];for(let[n,i]of Object.entries(e.variables))for(let o of i.ormCalls??[]){let{write:r,read:s}=go(o);t.push({variable:n,table:o.table,writeMethods:new Set(r),readMethods:new Set(s)})}return t}function kw(e,t,n,i,o,r){return nm(e,t,(s,a,c)=>kt(e,s,a,c,n,i,o,r))}function Ew(e,t,n,i,o,r){return nm(e,t,(s,a,c)=>hi(e,s,a,c,n,i,o,r))}function nm(e,t,n){let i=Ut(e,t,{semantic:!1});if(!i)return[];let o=[],r=new Set;for(let s of i.callees){if(r.has(s.symbol))continue;r.add(s.symbol);let a=wn(e,s.symbol).match;if(a)for(let c of n(a.relativePath,a.startLine,a.endLine))o.push({...c,via:s.shortName})}return o}function Tw(e,t,n){return Object.entries(t.actions).map(([i,o])=>{let r=o.code.map(s=>{let a=yo(s),c="error"in a?s:a.ref,d=fi(e,c,n,i).match;return d?(Zw(e,i,s,d,n),"error"in a||!a.window?{ref:s,match:d}:Iw(a.window,d)?(n.push(Q("invalid-line-window","error","compiler-symbol",{modelElement:i,codeRef:s,file:d.relativePath,startLine:d.startLine,endLine:d.endLine,message:`TLA+ action ${i} codeRef line window L${a.window.startLine}-L${a.window.endLine} falls outside ${oe(d.symbol)}'s actual span L${d.startLine+1}-L${d.endLine+1} in ${d.relativePath}.`,why:[`${s} resolves to ${oe(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.${i}.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(Q("missing-referent","error","compiler-symbol",{modelElement:i,codeRef:s,message:`TLA+ action ${i} 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.${i}.code to a live function or method symbol.`})),{ref:s,match:null})});return{name:i,mapping:o,referents:r}})}function Iw(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function Aw(e,t,n){let i=t.init;if(!i)return;let o=!!i.waive,r=i.codeRefs.map(s=>{let a=fi(e,s,n,"Init"),c=a.match;return c?e$(e,s,c,n,o):o||n.push(Q("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:i,referents:r}}function Pw(e,t,n,i){let o=new Set(t.variables),r=new Set(t.operators),s=new Set(n);for(let a of Object.keys(e.variables))o.has(a)||i.push(Q("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))r.has(a)||i.push(Q("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&&(Jp({action:a.name,field:"writes",modelValues:a.writes,mappingValues:c.writes,missingInMappingCategory:"model-mapping-write",missingInModelCategory:"model-mapping-write",findings:i,file:t.path,isWaived:l=>!!c.waive?.writes.includes(l)}),Jp({action:a.name,field:"reads",modelValues:a.reads,mappingValues:c.reads,missingInMappingCategory:"model-mapping-read",missingInModelCategory:"model-mapping-read",findings:i,file:t.path}))}for(let a of e.invariants)s.has(a)||i.push(Q("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 Jp(e){let t=new Set(e.modelValues),n=new Set(e.mappingValues),i=e.isWaived??(()=>!1);for(let o of t)n.has(o)||i(o)||e.findings.push(Q(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"} ${o}, but the mapping does not declare that ${e.field.slice(0,-1)}.`,why:[`SANY-derived model facts list ${o} in ${e.action}.${e.field}, while the mapping omits it.`],remediation:`Add ${o} to actions.${e.action}.${e.field}, or update the TLA+ model if the ${e.field.slice(0,-1)} is unintended.`}));for(let o of n)t.has(o)||i(o)||e.findings.push(Q(e.missingInModelCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`Mapping declares ${e.action}.${e.field} includes ${o}, but the SANY model facts do not.`,why:[`The mapping says ${e.action} ${e.field==="writes"?"writes":"reads"} ${o}, but the parsed TLA+ action does not show that model-side fact.`],remediation:`Update the TLA+ action to ${e.field==="writes"?"prime":"reference"} ${o}, remove the mapping declaration, or add a waiver if static evidence cannot represent the model boundary.`}))}function Lw(e,t,n,i,o,r,s,a,c,l,d){let m=[];for(let p of n){let f=[];for(let g of p.referents){if(!g.match)continue;let y=g.window??{startLine:g.match.startLine,endLine:g.match.endLine},v=kt(e,g.match.relativePath,y.startLine,y.endLine,i,o,r,s);f.push(...v),m.push(...v);let $=new Set(p.mapping.writes),L=kw(e,g.match.symbol,i,o,r,s).filter(_=>$.has(_.variable));f.push(...L),m.push(...L)}Nw(p,f,l,d.get(p.name))}let h=t.unmappedWriteScope==="actions"?[]:zw(e,t);for(let p of h)for(let f of kt(e,p,0,Number.POSITIVE_INFINITY,i,o,r,s))m.push(f),jw(f)&&(f.enclosingSymbol&&(a.has(f.enclosingSymbol)||c.has(f.enclosingSymbol))||l.push(Q("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 qo(m)}function jw(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function Nw(e,t,n,i){let o=new Set(e.mapping.writes),r=new Set(t.map(a=>a.variable)),s=new Set(i?.writes??[]);for(let a of t)i&&!s.has(a.variable)&&!pn(e,"write",a.variable)&&n.push(Q("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}${mi(a.via)}.`,`SANY-derived model facts for ${e.name} list writes: ${i.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.`})),!o.has(a.variable)&&!pn(e,"write",a.variable)&&n.push(Q("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}${mi(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 o)!r.has(a)&&!pn(e,"write",a)&&n.push(Q("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 Mw(e,t,n,i,o,r,s,a){let c=[];for(let l of t){let d=[];for(let m of l.referents){if(!m.match)continue;let h=m.window??{startLine:m.match.startLine,endLine:m.match.endLine},p=hi(e,m.match.relativePath,h.startLine,h.endLine,n,i,o,r);d.push(...p),c.push(...p);let f=new Set(l.mapping.reads),g=Ew(e,m.match.symbol,n,i,o,r).filter(y=>f.has(y.variable));d.push(...g),c.push(...g)}Ow(l,d,s,a.get(l.name))}return Fo(c)}function Ow(e,t,n,i){let o=new Set(e.mapping.reads),r=new Set(t.map(a=>a.variable)),s=new Set(i?.reads??[]);for(let a of t)i&&!s.has(a.variable)&&n.push(Q("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}${mi(a.via)}.`,`SANY-derived model facts for ${e.name} list reads: ${i.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.`})),!o.has(a.variable)&&!pn(e,"read",a.variable)&&n.push(Q("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}${mi(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 o)!r.has(a)&&!pn(e,"read",a)&&n.push(Q("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 Dw(e,t,n){for(let i of t){if(i.mapping.calls.length===0)continue;let o=i.mapping.calls.map(s=>fi(e,s,n,i.name));for(let s of o)s.match||n.push(Q("missing-referent","error","compiler-symbol",{modelElement:i.name,codeRef:s.ref,message:`actions.${i.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.${i.name}.calls to a live symbol or remove the stale call expectation.`}));let r=new Set(o.map(s=>s.match?.symbol).filter(Boolean));for(let s of i.referents){if(!s.match)continue;let a=Ut(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of r)c.has(l)||n.push(Q("missing-call","error","compiler-symbol",{modelElement:i.name,codeRef:s.ref,file:s.match.relativePath,startLine:s.match.startLine,endLine:s.match.endLine,message:`TLA+ action ${i.name} no longer calls ${oe(l)} from ${s.ref}.`,why:["The mapping declares a call dependency that is absent from the current compiler-resolved call graph."],remediation:`Update actions.${i.name}.calls, update the TLA+ action, or restore the code path if the call is required.`}))}}}function qw(e,t,n){for(let[i,o]of t.entries()){let r=e.actions[o.action];if(!r){n.push(Q("trace","error","trace",{modelElement:o.action,codeRef:o.code,message:`Trace step ${i} uses action ${o.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.${o.action} to the mapping, or fix the trace action name.`}));continue}let s=n$(o),a=new Set(r.writes);for(let c of s)a.has(c)||n.push(Q("trace","error","trace",{modelElement:o.action,codeRef:o.code,message:`Trace step ${i} changed ${c}, but action ${o.action} does not declare that write.`,why:["The runtime trace observed a state change outside the action write set."],remediation:`Update actions.${o.action}.writes, update the TLA+ model, or investigate the code path that changed ${c}.`}))}}function kt(e,t,n,i,o,r=[],s=[],a=[]){let c=Fw(e,t,n,i,o,r,s,a);return c||Qw(e,t,n,i,o,r,s,a)}function hi(e,t,n,i,o,r=[],s=[],a=[]){let c=Ww(e,t,n,i,o,r,s,a);return c||Kw(e,t,n,i,o,r,s,a)}function Fw(e,t,n,i,o,r=[],s=[],a=[]){let c=Si(e,t);if(!c)return null;let l=[],d=m=>{if(!(m.startPosition.row>i||m.endPosition.row<n)){_w(e,t,m,o,l),im(e,t,m,r,"write",l),om(e,t,m,s,"write",l),rm(e,t,m,a,"write",l);for(let h of m.children)d(h)}};return d(c.rootNode),qo(l)}function Ww(e,t,n,i,o,r=[],s=[],a=[]){let c=Si(e,t);if(!c)return null;let l=[],d=m=>{if(!(m.startPosition.row>i||m.endPosition.row<n)){Vw(e,t,m,o,l),im(e,t,m,r,"read",l),om(e,t,m,s,"read",l),rm(e,t,m,a,"read",l);for(let h of m.children)d(h)}};return d(c.rootNode),Fo(l)}function _w(e,t,n,i,o){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let r=n.childForFieldName("left")??n.namedChild(0);r&&un(e,t,r,"assignment",i,o);return}if(n.type!=="variable_declarator"){if(n.type==="pair"){let r=n.childForFieldName("key")??n.namedChild(0);r&&un(e,t,r,"object-field",i,o);return}if(n.type==="update_expression"){let r=n.namedChildren.find(s=>s.type!=="++"&&s.type!=="--")??n.namedChild(0);r&&un(e,t,r,"update",i,o);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let r=n.namedChild(0);r&&un(e,t,r,"delete",i,o);return}if(n.type==="call_expression"){let r=n.childForFieldName("function")??n.namedChild(0);if(!r||!am(r))return;un(e,t,r,"mutation-call",i,o)}}}function im(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?Oo(s):null;if(!a||!(o==="write"?Xp:Zp).has(a))return;let d=n.childForFieldName("arguments")?.namedChild(0);if(!d)return;let m=d.text;for(let h of i){if(!m.includes(h.path))continue;let p=Ze(e,t,n.startPosition.row);r.push({variable:h.variable,alias:h.path,file:t,line:n.startPosition.row,target:`${a}(${m})`,kind:"resource",enclosingSymbol:p?.symbol,enclosingShort:p?oe(p.symbol):void 0})}}function Oo(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 om(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("arguments");if(s)for(let a of s.namedChildren){let c=Bw(a);if(c!==null&&em(c)===o)for(let l of i){if(!l.regex.test(c))continue;let d=Ze(e,t,n.startPosition.row),m=n.childForFieldName("function")??n.namedChild(0),h=(m&&Oo(m))??"call";r.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${h}(${Gw(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?oe(d.symbol):void 0})}}}function Bw(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function Gw(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function rm(e,t,n,i,o,r){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?Oo(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let d=l.text.trim();for(let m of i){if(!sm(m,a,d,o))continue;let h=Ze(e,t,n.startPosition.row);r.push({variable:m.variable,alias:m.table,file:t,line:n.startPosition.row,target:`${a}(${d})`,kind:"orm-call",enclosingSymbol:h?.symbol,enclosingShort:h?oe(h.symbol):void 0})}}function sm(e,t,n,i){return n!==e.table?!1:i==="write"?e.writeMethods.has(t):e.readMethods.has(t)||t==="from"&&e.readMethods.has("select")}function Vw(e,t,n,i,o){if(!(!Uw(n)||Hw(n)))for(let r of i){if(n.text!==r.alias)continue;let s=Ze(e,t,n.startPosition.row);o.push({variable:r.variable,alias:r.alias,file:t,line:n.startPosition.row,target:n.text,kind:"identifier",enclosingSymbol:s?.symbol,enclosingShort:s?oe(s.symbol):void 0})}}function Uw(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function Hw(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&&No(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&&No(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&am(n)&&No(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 No(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function am(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&Yp.has(t.text))}function un(e,t,n,i,o,r){for(let s of o){if(!t$(s.alias,n.text))continue;let a=Ze(e,t,n.startPosition.row);r.push({variable:s.variable,alias:s.alias,file:t,line:n.startPosition.row,target:n.text,kind:i,enclosingSymbol:a?.symbol,enclosingShort:a?oe(a.symbol):void 0})}}function Qw(e,t,n,i,o,r=[],s=[],a=[]){let l=St(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),d=[],m=Number.isFinite(i)?Math.min(l.length-1,i):l.length-1;for(let h=Math.max(0,n);h<=m;h+=1){let p=l[h]??"";for(let f of o){if(vw(p,f.alias))continue;let g=wt(f.alias);if(!new RegExp(`(?:\\b${g}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${g}\\b\\s*\\.\\s*(?:${[...Yp].join("|")})\\s*\\(|\\b${g}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(p))continue;let v=Ze(e,t,h);d.push({variable:f.variable,alias:f.alias,file:t,line:h,target:p.trim(),kind:"source-scan",enclosingSymbol:v?.symbol,enclosingShort:v?oe(v.symbol):void 0})}cm(e,t,h,p,r,Xp,d),lm(e,t,h,p,s,"write",d),dm(e,t,h,p,a,"write",d)}return qo(d)}function Kw(e,t,n,i,o,r=[],s=[],a=[]){let l=St(e.config.projectRoot,t,{inputKind:"indexed TLA conformance source file"}).split(/\r?\n/),d=[],m=Number.isFinite(i)?Math.min(l.length-1,i):l.length-1;for(let h=Math.max(0,n);h<=m;h+=1){let p=l[h]??"";for(let f of o){let g=wt(f.alias);if(!new RegExp(`\\b${g}\\b`).test(p)||new RegExp(`\\b${g}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(p))continue;let y=Ze(e,t,h);d.push({variable:f.variable,alias:f.alias,file:t,line:h,target:p.trim(),kind:"source-scan",enclosingSymbol:y?.symbol,enclosingShort:y?oe(y.symbol):void 0})}cm(e,t,h,p,r,Zp,d),lm(e,t,h,p,s,"read",d),dm(e,t,h,p,a,"read",d)}return Fo(d)}function cm(e,t,n,i,o,r,s){if(o.length!==0)for(let a of r){let c=i.indexOf(`${a}(`);if(c===-1)continue;let l=i.slice(c+a.length);for(let d of o){if(!l.includes(d.path))continue;let m=Ze(e,t,n);s.push({variable:d.variable,alias:d.path,file:t,line:n,target:i.trim(),kind:"resource",enclosingSymbol:m?.symbol,enclosingShort:m?oe(m.symbol):void 0})}}}function lm(e,t,n,i,o,r,s){if(o.length!==0&&em(i)===r)for(let a of o){if(!a.regex.test(i))continue;let c=Ze(e,t,n);s.push({variable:a.variable,alias:a.pattern,file:t,line:n,target:i.trim(),kind:"statement",enclosingSymbol:c?.symbol,enclosingShort:c?oe(c.symbol):void 0})}}function dm(e,t,n,i,o,r,s){if(o.length!==0)for(let a of i.matchAll(/\.([A-Za-z_$][\w$]*)\s*\(\s*([^,)\s][^,)]*?)\s*\)/g)){let c=a[1],l=a[2].trim();for(let d of o){if(!sm(d,c,l,r))continue;let m=Ze(e,t,n);s.push({variable:d.variable,alias:d.table,file:t,line:n,target:i.trim(),kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?oe(m.symbol):void 0})}}}function zw(e,t){let n=t.scope??[];return n.length===0?[]:e.all("SELECT relative_path FROM documents ORDER BY relative_path").map(o=>o.relative_path).filter(o=>n.some(r=>o.includes(r)))}function fi(e,t,n,i){let o=wn(e,t),r=o.match??(t.includes("#")?wn(e,t.replace("#","/")).match:null);return o.match&&o.total>1&&!Jw(t)&&n.push(Q("ambiguous-referent","warning","compiler-symbol",{modelElement:i,codeRef:t,file:o.match.relativePath,startLine:o.match.startLine,endLine:o.match.endLine,message:`Mapping referent ${t} resolved ambiguously to ${oe(o.match.symbol)}.`,why:[`${o.total} indexed definitions share this lookup shape.`,Yw(o.candidates)].filter(Boolean),remediation:`Qualify ${t} with a path or fuller symbol name so the mapping cannot drift to another definition.`})),{ref:t,match:r}}function Jw(e){return/[/#:]/.test(e)}function Yw(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function Xw(e,t,n,i,o,r=!1){let s=Do(e,i);if(s===null||r$.has(s)||r)return;let a=Wo.has(s);o.push(Q("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:i.relativePath,startLine:i.startLine,endLine:i.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${Vt(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${oe(i.symbol)} with SCIP kind ${Vt(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function Zw(e,t,n,i,o){let r=Do(e,i);r===null||um.has(r)||Wo.has(r)&&o.push(Q("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:i.relativePath,startLine:i.startLine,endLine:i.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${oe(i.symbol)} with SCIP kind ${Vt(r)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function e$(e,t,n,i,o){let r=Do(e,n);r===null||um.has(r)||o||Wo.has(r)&&i.push(Q("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 ${oe(n.symbol)} with SCIP kind ${Vt(r)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function Do(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function Ze(e,t,n){return Sn(e,t).filter(o=>o.startLine<=n&&o.endLine>=n).sort((o,r)=>o.endLine-o.startLine-(r.endLine-r.startLine))[0]??null}function t$(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${wt(e)}([^A-Za-z0-9_$]|$)`).test(t)}function n$(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 qo(e){let t=new Set,n=[];for(let i of e){let o=`${i.variable}:${i.file}:${i.line}:${i.target}:${i.enclosingSymbol??""}`;t.has(o)||(t.add(o),n.push(i))}return n}function Fo(e){let t=new Set,n=[];for(let i of e){let o=`${i.variable}:${i.file}:${i.line}:${i.target}:${i.enclosingSymbol??""}`;t.has(o)||(t.add(o),n.push(i))}return n}function i$(e){let t=new Set;return e.filter(n=>{let i=`${n.variable}:${n.alias}`;return t.has(i)?!1:(t.add(i),!0)})}function Mo(e){return e.filter(t=>t.match).length}function mi(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function pn(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function o$(e){let t=Object.entries(e.actions).flatMap(([r,s])=>{let a=s.waive;return a?[...(a.reads??[]).map(c=>({action:r,kind:"read",variable:c,reason:a.reason,legacy:a.legacy===!0})),...(a.writes??[]).map(c=>({action:r,kind:"write",variable:c,reason:a.reason,legacy:a.legacy===!0}))]:[]}),n=Object.entries(e.variables).flatMap(([r,s])=>{let a=s.waive;return a?[{kind:"referent",variable:r,reason:a.reason,legacy:!1}]:[]}),i=e.init?.waive,o=i?[{kind:"referent",variable:"Init",reason:i.reason,legacy:!1}]:[];return[...t,...n,...o]}var Wo=new Set(dr()),um=new Set(lr()),r$=new Set(ur());function Q(e,t,n,i){let o=JSON.stringify({category:e,evidence:n,...i});return{id:`TLA${fw("sha1").update(o).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...i}}import{basename as s$,join as a$}from"path";var _o=/^[A-Za-z_][A-Za-z0-9_]*$/;function pm(e,t,n={}){let i=[],o=Sn(e,t,{includeClassMemberFallbacks:!0});if(o.length===0)throw new Error(`no indexed definitions found for ${t}; run 'scip-query reindex' or check the path`);let s=St(e.config.projectRoot,t,{inputKind:"indexed TLA scaffold source file"}).split(/\r?\n/),a=E=>E.symbol.trimEnd().endsWith("()."),c=o.filter(E=>!a(E)&&!E.isTypeLike&&E.parentTypeName===null&&_o.test(E.leaf)),l=c.map(E=>({variable:E.leaf,alias:E.leaf})),d=l.length>0?kt(e,t,0,Number.POSITIVE_INFINITY,l):[],m=new Set(d.map(E=>E.variable)),h=c.filter(E=>m.has(E.leaf)?!0:d$(s,E)),p=null,f;if(h.length>0)f=o.filter(E=>a(E)&&E.parentTypeName===null);else{if(p=c$(e,t,o,a),!p){let E=o.some(B=>!a(B)&&!B.isTypeLike&&B.parentTypeName!==null&&_o.test(B.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 `+(E?"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.")}h=p.fields,f=p.methods,i.push(`state scoped to class ${p.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 g=h.map(E=>u$(E,s,t,i,p?.className)),y=g.map(E=>({variable:E.name,alias:E.leaf})),v=[],$=new Set;for(let E of f){let B=kt(e,t,E.startLine,E.endLine,y);if(B.length===0)continue;let J=hi(e,t,E.startLine,E.endLine,y),F=f$(mm(E.leaf),$);v.push({name:F,leaf:E.leaf,codeRef:l$(t,E,p?.className),startLine:E.startLine,writes:[...new Set(B.map(Y=>Y.variable))].sort(),reads:[...new Set(J.map(Y=>Y.variable))].sort()})}v.length===0&&i.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 L=n.moduleName??g$(t),_=n.specDir??a$("specs",L),I=y$(L,g,v,t),T=b$(),W=v$(L,_,t,g,v);return{moduleName:L,file:t,variables:g,actions:v,warnings:i,spec:I,cfg:T,map:W}}function c$(e,t,n,i){let o=new Map;for(let s of n){if(i(s)||s.isTypeLike||s.parentTypeName===null||!_o.test(s.leaf))continue;let a=o.get(s.parentTypeName);a?a.push(s):o.set(s.parentTypeName,[s])}let r=null;for(let[s,a]of o){let c=n.filter(h=>i(h)&&h.parentTypeName===s),l=a.map(h=>({variable:h.leaf,alias:h.leaf})),d=new Set;for(let h of c)for(let p of kt(e,t,h.startLine,h.endLine,l))d.add(p.variable);let m=a.filter(h=>d.has(h.leaf));m.length!==0&&(!r||m.length>r.fields.length)&&(r={className:s,fields:m,methods:c})}return r}function l$(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function d$(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function u$(e,t,n,i,o){let r=p$(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=m$(e.leaf,r);return a||i.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||i.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:o?`${n}/${o}#${e.leaf}`:`${n}/${e.leaf}`,declarationLine:e.startLine,initTla:l,domainTla:a,domainBasis:c}}function p$(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function m$(e,t){let i=t.match(new RegExp(`\\b${wt(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,r=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(i){let l=h$(i);l?(s=`{${l.map(d=>`"${d}"`).join(", ")}}`,a="union-literal"):/^boolean\b/.test(i)?(s="BOOLEAN",a="boolean"):(/\[\]\s*$/.test(i)||/^(Array|ReadonlyArray)</.test(i))&&(a="sequence",s=null)}let c=null;if(r){let l=r.match(/^['"]([^'"]*)['"]/);l?c=`"${l[1]}"`:/^(true|false)\b/.test(r)?c=r.startsWith("true")?"TRUE":"FALSE":/^-?\d+\b/.test(r)?c=r.match(/^-?\d+/)[0]:/^\[\s*\]/.test(r)&&(c="<<>>")}return{domainTla:s,domainBasis:a,initTla:c}}function h$(e){let t=e.split("|").map(i=>i.trim());if(t.length<2)return null;let n=[];for(let i of t){let o=i.match(/^['"]([^'"]*)['"]$/);if(!o)return null;n.push(o[1])}return n}function mm(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function f$(e,t){let n=e,i=2;for(;t.has(n);)n=`${e}${i++}`;return t.add(n),n}function g$(e){let n=s$(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return mm(n||"Model")}function y$(e,t,n,i){let o=t.map(s=>s.name),r=[];r.push(`---- MODULE ${e} ----`),r.push(`\\* Scaffolded by 'scip-query tla scaffold ${i}'.`),r.push("\\* Draft evidence tier: state from the static write scan, domains from"),r.push("\\* declared types, actions from top-level callables that write state."),r.push("\\* Review every TODO before trusting a green model-check run."),r.push("EXTENDS Naturals, Sequences, TLC"),r.push(""),r.push(`VARIABLES ${o.join(", ")}`),r.push(""),r.push(`vars == <<${o.join(", ")}>>`),r.push("");for(let s of t){if(s.domainBasis==="sequence")continue;let a=s.domainTla??'{ "TODO" } \\* TODO: declare the domain';r.push(`${s.name}Domain == ${a}`)}r.push(""),r.push("Init ==");for(let s of t){let a=s.initTla??`${s.name}Domain \\* TODO: replace with the concrete initial value (\\in used)`;r.push(s.initTla!==null?` /\\ ${s.name} = ${s.initTla}`:` /\\ ${s.name} \\in ${a}`)}r.push("");for(let s of n){let a=o.filter(c=>!s.writes.includes(c));r.push(`\\* Derived from ${s.codeRef} (writes: ${s.writes.join(", ")||"none"})`),r.push(`${s.name} ==`),r.push(` /\\ TRUE \\* TODO guard: encode the enabling condition of ${s.leaf}()`);for(let c of s.writes){let d=t.find(m=>m.name===c)?.domainBasis==="sequence"?'Seq({"TODO"})':`${c}Domain`;r.push(` /\\ ${c}' \\in ${d} \\* TODO: tighten to the concrete transition`)}a.length>0&&r.push(` /\\ UNCHANGED <<${a.join(", ")}>>`),r.push("")}if(r.push("Next =="),n.length===0)r.push(" FALSE \\* TODO: no state-writing callables were discovered");else for(let[s,a]of n.entries())r.push(` \\/ ${a.name}`);r.push(""),r.push("Spec == Init /\\ [][Next]_vars"),r.push(""),r.push("TypeOK ==");for(let s of t)s.domainBasis==="sequence"?r.push(` /\\ ${s.name} \\in Seq({"TODO"}) \\* TODO: element domain`):r.push(` /\\ ${s.name} \\in ${s.name}Domain`);return r.push("===="),r.push(""),r.join(`
279
- `)}function b$(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
280
- `)}function v$(e,t,n,i,o){let r={module:`${t}/${e}.tla`,config:`${t}/${e}.cfg`,scope:[n],derived:{generatedBy:"scip-query tla scaffold",basis:"static-scan",generatedFrom:n},variables:Object.fromEntries(i.map(s=>[s.name,{code:[s.codeRef],aliases:[s.leaf]}])),actions:Object.fromEntries(o.map(s=>[s.name,{code:[s.codeRef],reads:s.reads,writes:s.writes,calls:[]}])),invariants:["TypeOK"],traces:[]};return`${JSON.stringify(r,null,2)}
281
- `}function hm(e,t){let n=Object.keys(t.variables),i=Object.entries(t.actions).map(([o,r])=>{let s=r.code[0]??"",a=s?cr(e,s):null;return{action:o,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:r.writes}});return{recorderSource:S$(n),wiring:i,variables:n}}function S$(e){return`/**
282
- * Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
283
- *
284
- * Usage inside a mapped action (record the model-visible slice around the
285
- * mutation):
286
- *
287
- * import { tlaRecord } from './scip-tla-recorder.js';
288
- * export function enqueue(job: string) {
289
- * const before = snapshot();
290
- * queue.push(job);
291
- * tlaRecord('Enqueue', before, snapshot());
292
- * }
293
- *
294
- * where snapshot() projects the mapped variables to JSON scalars \u2014 fill in
295
- * each field with the real runtime value, e.g.
296
- * const snapshot = () => ({ ${e.map(t=>`${t}: undefined`).join(", ")} }); // fill in each field
297
- *
298
- * Recording is enabled only when SCIP_TLA_TRACE names an output path, so the
299
- * wiring is safe to leave in place. The output is a JSON array compatible
300
- * with 'scip-query tla trace-check --trace <path>'.
301
- */
302
- import { readFileSync, statSync, writeFileSync } from 'node:fs';
303
-
304
- interface TlaTraceStep {
305
- action: string;
306
- before: Record<string, unknown>;
307
- after: Record<string, unknown>;
308
- }
309
-
310
- const tracePath = process.env['SCIP_TLA_TRACE'];
311
- const TRACE_MAX_BYTES = 16 * 1024 * 1024;
312
- const TRACE_MAX_STEPS = 100_000;
313
-
314
- export function tlaRecord(action: string, before: Record<string, unknown>, after: Record<string, unknown>): void {
315
- if (!tracePath) return;
316
- let steps: TlaTraceStep[] = [];
317
- try {
318
- const size = statSync(tracePath).size;
319
- if (size > TRACE_MAX_BYTES) throw new Error(\`TLA trace exceeds \${TRACE_MAX_BYTES} bytes\`);
320
- steps = JSON.parse(readFileSync(tracePath, 'utf8')) as TlaTraceStep[];
321
- if (!Array.isArray(steps)) steps = [];
322
- } catch (error) {
323
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
324
- }
325
- if (steps.length >= TRACE_MAX_STEPS) throw new Error(\`TLA trace exceeds \${TRACE_MAX_STEPS} steps\`);
326
- steps.push({ action, before, after });
327
- const payload = JSON.stringify(steps, null, 2);
328
- const payloadBytes = Buffer.byteLength(payload);
329
- if (payloadBytes > TRACE_MAX_BYTES) throw new Error(\`TLA trace would exceed \${TRACE_MAX_BYTES} bytes\`);
330
- writeFileSync(tracePath, payload);
331
- }
332
- `}import{copyFileSync as w$,mkdtempSync as $$,readdirSync as R$,rmSync as x$,writeFileSync as fm}from"fs";import{tmpdir as C$}from"os";import{basename as k$,dirname as E$,join as mn}from"path";function gi(e,t){let n=new Map;for(let i of t)n.set(i.action,(n.get(i.action)??0)+1);return e.map(i=>({action:i,stepsObserved:n.get(i)??0}))}function T$(e,t,n,i="Next"){if(n.length===0)return{error:"trace has no steps"};let o=[],r=n[0];if(!r.before)return{error:"trace step 0 must include a full `before` state"};let s=[],a={...r.before},c=g=>{let y={};for(let[v,$]of Object.entries(g)){if(!t.includes(v))continue;let L=A$($);L!==void 0&&(y[v]=L)}return y};s.push(c(a));for(let g of n){if(g.before)for(let[y,v]of Object.entries(g.before))y in a||(a[y]=v);Object.assign(a,g.after??{}),s.push(c(a))}let l=t.filter(g=>s.every(y=>g in y)),d=t.filter(g=>!l.includes(g));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};d.length>0&&o.push(`variables not pinned by the trace (missing or non-scalar values): ${d.join(", ")} \u2014 divergence in these variables is NOT checked.`);let m=`${e}Trace`,h=s.map(g=>` [${l.map(y=>`${y} |-> ${ym(g[y])}`).join(", ")}]`).join(`,
333
- `),p=[`---- MODULE ${m} ----`,"\\* Generated trace-validation harness. Checks that the recorded execution",`\\* is a behavior of ${e}!${i}. TLC deadlocks at the first`,"\\* divergent step; a clean run means the model accepts the trace.",`EXTENDS ${e}, Naturals, Sequences`,"","VARIABLE traceIdx","","TraceStates ==","<<",h,">>","","TraceInit =="," /\\ traceIdx = 1",...l.map(g=>` /\\ ${g} = TraceStates[1].${g}`),"","TraceStep =="," /\\ traceIdx < Len(TraceStates)"," /\\ traceIdx' = traceIdx + 1",` /\\ ${i}`,...l.map(g=>` /\\ ${g}' = TraceStates[traceIdx + 1].${g}`),"","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(`
334
- `),f=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
335
- `);return{moduleName:m,moduleText:p,cfgText:f,variables:l,skippedVariables:d,states:s.length,warnings:o}}function gm(e){let t=e.mappedActions??[],n=T$(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:gi(t,[])};let i=$$(mn(C$(),"scip-tla-trace-"));try{let o=E$(e.specPath);for(let d of R$(o))d.endsWith(".tla")&&w$(mn(o,d),mn(i,d));let r=mn(i,`${n.moduleName}.tla`),s=mn(i,`${n.moduleName}.cfg`);fm(r,n.moduleText),fm(s,n.cfgText);let a=ui({...e.toolOptions,specPath:r,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:gi(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:gi(t,e.steps)};let c=I$(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:gi(t,l)}}finally{x$(i,{recursive:!0,force:!0})}}function I$(e,t){let n=null;for(let r of e.matchAll(/\btraceIdx = (\d+)/g)){let s=Number.parseInt(r[1],10);(n===null||s>n)&&(n=s)}if(n===null||!/deadlock/i.test(e))return null;let i=n-1,o=t[i];return{divergedAtState:n,divergedStep:{index:i,action:o?.action??"unknown"}}}function A$(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 ym(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>ym(t)).join(", ")}>>`}function bm(e){return k$(e).replace(/\.tla$/i,"")}import{mkdirSync as Sm,writeFileSync as wm}from"fs";import{dirname as P$,join as Ft}from"path";var L$=async(...e)=>{let{args:t,opts:n}=za(e),i=N(t,0);if(i==="fetch-tools"){let r=await zp();if(b(n,"json")){P("tla",t,n,r);return}console.log(`tla2tools.jar ${r.status}: ${r.path}`),console.log(`Version: ${r.version}`),console.log(`SHA-256: ${r.sha256}`);return}if(i==="scaffold"){let r=H(t,1);if(!r)throw new Error("tla scaffold requires a target source file");Me(s=>j$(s,t,n,r));return}if(i==="instrument"){let r=H(t,1);Me(s=>N$(s,t,n,r));return}if(i==="trace-check"){let r=H(t,1);if(!r)throw new Error("tla trace-check requires a spec path");Me(s=>M$(s,t,n,r));return}if(i!=="verify")throw new Error(`unknown tla operation: ${i}. Supported operations: verify, scaffold, instrument, trace-check, fetch-tools`);let o=H(t,1);if(!o)throw new Error("tla verify requires a spec path");Me(r=>q$(r,t,n,o))};function j$(e,t,n,i){let o=e.config.projectRoot,r=pm(e,i,{moduleName:w(n,"moduleName"),specDir:w(n,"out")}),s=w(n,"out")??Ft("specs",r.moduleName),a=Pe(o,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=b(n,"force"),l=[{path:Ft(a,`${r.moduleName}.tla`),body:r.spec},{path:Ft(a,`${r.moduleName}.cfg`),body:r.cfg},{path:Ft(a,`${r.moduleName}.scip-tla.json`),body:r.map}];for(let d of l)if(!c&&hn(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);Sm(a,{recursive:!0});for(let d of l)wm(d.path,d.body);if(b(n,"json")){P("tla",t,n,{operation:"scaffold",moduleName:r.moduleName,target:i,written:l.map(d=>d.path),variables:r.variables,actions:r.actions,warnings:r.warnings});return}console.log(`Scaffolded ${r.moduleName} from ${i} (draft \u2014 review every TODO):`);for(let d of l)console.log(` wrote ${d.path}`);console.log(`Variables (${r.variables.length}): ${r.variables.map(d=>`${d.name}${d.domainTla?"":" [TODO domain]"}`).join(", ")}`),console.log(`Actions (${r.actions.length}): ${r.actions.map(d=>`${d.name}(writes: ${d.writes.join(",")||"-"})`).join("; ")}`);for(let d of r.warnings)console.log(`WARNING: ${d}`);console.log(`Next: fill the TODO guards/domains, then run 'scip-query tla verify ${Ft(s,`${r.moduleName}.tla`)}'.`)}function N$(e,t,n,i){let o=e.config.projectRoot,r=w(n,"map")??(i?oi(i):void 0);if(!r)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=ii(o,r);if(!s.loaded)throw new Error(s.errors.join(`
336
- `));let{contract:a,mapDir:c}=s.loaded,l=hm(e,a),d=w(n,"out")??Ft(c,"scip-tla-recorder.ts"),m=Pe(o,d);if(!m)throw new Error(`instrument output escapes the project root: ${d}`);if(!b(n,"force")&&hn(m))throw new Error(`refusing to overwrite ${m} (pass --force to replace the recorder)`);if(Sm(P$(m),{recursive:!0}),wm(m,l.recorderSource),b(n,"json")){P("tla",t,n,{operation:"instrument",recorder:m,variables:l.variables,wiring:l.wiring});return}console.log(`Wrote trace recorder: ${m}`),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 h of l.wiring){let p=h.file?`${h.file}:${h.line}`:`UNRESOLVED (${h.codeRef})`;console.log(` - ${h.action} -> ${p} writes: ${h.writes.join(", ")||"-"}`)}}function M$(e,t,n,i){let o=e.config.projectRoot,r=Pe(o,i);if(!r||!hn(r))throw new Error(`TLA+ spec not found: ${i}`);let s=w(n,"map")??oi(i),a=ii(o,s);if(!a.loaded)throw new Error(a.errors.join(`
337
- `));let{contract:c}=a.loaded,l=O(n,"trace"),m=vo(o,[...c.traces,...l]).flatMap(f=>bo(o,f).steps);if(m.length===0)throw new Error("no trace steps found: pass --trace <file> (repeatable) or list traces in the mapping contract");let h=gm({specPath:r,baseModuleName:bm(r),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:m,nextOperator:w(n,"next"),toolOptions:{projectRoot:o,tlaToolsJar:w(n,"tlaTools"),timeoutMs:K(n,"timeoutMs")}}),p=h.status==="accepted"||h.status==="unavailable"&&b(n,"allowUnknown")?0:1;if(b(n,"json")){P("tla",t,n,{operation:"trace-check",...h,exitCode:p}),process.exitCode=p;return}if(console.log(`TLA+ trace-check: ${r}`),console.log(`Trace: ${m.length} step(s) -> ${h.states} pinned state(s)`),h.generation){console.log(`Pinned variables: ${h.generation.variables.join(", ")}`);for(let f of h.generation.warnings)console.log(`WARNING: ${f}`)}console.log(`${h.status.toUpperCase()}: ${h.detail}`),b(n,"coverage")&&O$(h.actionCoverage),process.exitCode=p}function O$(e){if(e.length===0)return;let t=e.filter(i=>i.stepsObserved>0),n=e.filter(i=>i.stepsObserved===0);console.log(`Action coverage: ${t.length}/${e.length} mapped action(s) exercised by this trace.`);for(let i of t)console.log(` - ${i.action}: ${i.stepsObserved} step(s)`);n.length>0&&console.log(` Unexercised: ${n.map(i=>i.action).join(", ")} \u2014 classify each as a pure modeling abstraction (no code twin, expected) or a real coverage gap (record another trace).`)}function D$(e,t,n,i){let o=w(i,"map");if(o)return{mapArg:o};let r=oi(t),s=Pe(e,r);if(s&&hn(s))return{mapArg:r};let a=Ru(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:r}}function q$(e,t,n,i){let o=e.config.projectRoot,r=Pe(o,i);if(!r||!hn(r))throw new Error(`TLA+ spec not found: ${i}`);let{mapArg:s,mappingDiscoveredBy:a}=D$(o,i,r,n),c=ii(o,s);if(!c.loaded)throw new Error(c.errors.join(`
338
- `));let{contract:l,mapPath:d,mapDir:m}=c.loaded,h=w(n,"config")??l.config,p=bu(o,m,h),f=W$(w(n,"checker")??"auto"),g=w(n,"tlaTools"),y=F$(o,i,r,g)??vu(o,i),v=wu(p),$=O(n,"trace"),_=vo(o,[...l.traces,...$]).map(F=>({tracePath:F,...bo(o,F)})),I=_.flatMap(F=>F.steps),T=new Set($),W=_.filter(F=>T.has(F.tracePath)).flatMap(F=>F.errors),E=tm(e,l,y,I,v);for(let F of[...c.errors,...W])E.findings.push({id:`TLA-CONTRACT-${E.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:F,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 B=ui({projectRoot:o,specPath:r,configPath:p??void 0,checker:f,tlaToolsJar:g,apalacheBin:w(n,"apalache"),length:k(n,"length",10),timeoutMs:K(n,"timeoutMs")});B.status==="skipped"&&f!=="none"&&E.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:B.diagnostics.map(F=>F.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 J={operation:"verify",specPath:r,mapPath:d,...a?{mappingDiscoveredBy:a}:{},...p?{configPath:p}:{},checker:B,conformance:E,exitCode:_$(B,E,b(n,"allowUnknown"))};if(b(n,"json")){P("tla",t,n,J),process.exitCode=J.exitCode;return}B$(J,b(n,"full")),process.exitCode=J.exitCode}function F$(e,t,n,i){let o=jo({projectRoot:e,specPath:n,tlaToolsJar:i,checker:"sany"});if(!o)return null;let r=cu({specPath:n,jarPath:o});return r?Su(e,t,r):null}var $m=[{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:ge("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",z("repository-observation",[{when:{kind:"argument",index:0,equals:"scaffold"},role:"mutation"},{when:{kind:"argument",index:0,equals:"instrument"},role:"mutation"},{when:{kind:"argument",index:0,equals:"fetch-tools"},role:"composite"}])),options:x([u("--map <file>","scip-query TLA mapping JSON file"),u("--config <file>","TLA+ checker config file"),u("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),u("--tla-tools <jar>","Path to tla2tools.jar"),u("--apalache <binary>","Path to apalache-mc binary"),u("--length <n>","Bounded checker length for Apalache",S,10),u("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",pe),u("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",U,[]),u("--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"),u("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),u("--allow-unknown","Exit zero when only unknown findings remain"),u("--out <path>","Output directory (scaffold) or file (instrument)"),u("--module-name <name>","Module name for scaffolded specs"),u("--force","Overwrite existing scaffold/instrument output"),u("--full","verify: print every finding ungrouped instead of (category, modelElement) groups with 3 exemplars each")]),renderShape:"custom",docs:R("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:L$}];function W$(e){if(!yu(e))throw new Error(`unknown checker mode: ${e}`);return e}function _$(e,t,n){return e.status==="failed"||e.status==="timed-out"||t.findings.some(i=>i.severity==="error")||!n&&t.findings.some(i=>i.evidence==="unknown")?1:0}var vm=3;function B$(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 r of e.checker.diagnostics)console.log(` [${r.severity}] ${r.message}`);let n=e.conformance.findings.filter(r=>r.severity==="error"),i=e.conformance.findings.filter(r=>r.evidence==="unknown"),o=V$(e);console.log(`
339
- Conformance: ${e.conformance.mappedVariables} variable(s), ${e.conformance.mappedActions} action(s), ${e.conformance.resolvedReferents} resolved referent(s).`),console.log(`Proof: ${o}`);for(let r of U$(e))console.log(`WARNING: ${r}`);if(e.conformance.waivers.length>0){console.log("Waivers:");for(let r of e.conformance.waivers){let s=r.legacy?" legacy":"",a=r.action?`${r.action} ${r.kind}`:`variable ${r.kind}`;console.log(` - ${a} ${r.variable}:${s} ${r.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), ${i.length} unknown(s), ${e.conformance.findings.length} total.`),t){for(let r of e.conformance.findings)Rm(r);return}G$(e.conformance)}function G$(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
340
- Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
341
- [${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let o of n.findingIds.slice(0,vm)){let r=t.get(o);r&&Rm(r)}let i=n.count-vm;i>0&&console.log(` ... and ${i} more in this group (use --full to show all)`)}}function V$(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,i=e.conformance.waivers.filter(s=>s.kind==="read").length,o=e.conformance.waivers.filter(s=>s.kind==="referent").length,r=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, ${i} waived`,`calls: ${r===0?"checked":`${r} missing`}`,`traces: ${e.conformance.traceStepsChecked} steps (key-diff; 'tla trace-check' proves acceptance)`,...o>0?[`referents: ${o} waived`]:[]].join(" | ")}function U$(e){let t=[],n=e.conformance.waivers.filter(o=>o.kind==="write").length,i=e.conformance.waivers.filter(o=>o.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."),i>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 Rm(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${V(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
342
- [${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 xm=["stats","files","session","inspect","search","anchors","methods","refs","trace","evidence","evidence-source","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","dependency-depth","deep-chains","hierarchy","entrypoints","entry-map","system-map","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","co-change","recent-duplicates","doc-drift","unused-params","incomplete-migration","tla","context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","reference-neighborhood","dataflow","value-flow","dependence-slice","reference-reachability","slice","redundant-reexports","duplicate-bodies","twin-drift","twin-ab","not-implemented","decorative-checkers","test-quality","similar-signatures"],H$=[tp,Lp,sp,si,cp,Mp,$m,ap],Cm=H$.flat(),Q$=new Map(Cm.map(e=>[e.id,e]));for(let e of Cm)if(!xm.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var km=xm.map(e=>K$(e));function K$(e){let t=Q$.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var JI=[qa,{id:"hook-architecture-stop",command:"hook-architecture-stop",hidden:!0,agent:ge("Did indexed source changes preserve the repository architecture policy?","architecture policy decision and enforced finding identities",[],"complete","diff",z("repository-observation")),description:"Internal architecture-only Stop hook",renderShape:"custom",handler:Ld},{id:"reindex",command:"reindex",agent:ge("Can the repository index be refreshed, and which language shards succeeded?","index generation, shard statuses, reuse diagnostics, and failures",[],"complete","repository",z("composite")),description:"Index the codebase and convert to SQLite",options:x([u("-l, --language <lang>","Index only this language (can be repeated)",U,[]),u("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),u("--force","Rebuild even if source inputs are unchanged"),u("--allow-partial","Write an incomplete index when one or more detected languages fail"),u("--allow-expensive-rebuild","Explicitly permit a whole-project indexer when incremental and shared-generation paths are unavailable"),u("--trust-project-tools","Permit reviewed indexers from this repository for this run"),u("--install-missing","Install missing global tools at reviewed immutable versions for this run"),u("--indexer-concurrency <n>","Number of language indexers to run at once",pe)]),renderShape:"custom",docs:R("Indexing",["scip-query reindex"]),handler:jd},{id:"augment-sources",command:"augment-sources",agent:ge("Can source files omitted by upstream indexers be added to the index?","added document counts and augmentation status",[],"complete","repository",z("composite")),description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:R("Indexing"),handler:Nd},{id:"augment-vue",command:"augment-vue",agent:ge("Can Vue SFC references be compiler-resolved and added to the index?","Vue augmentation counts, project, and diagnostics",[],"complete","repository",z("composite")),description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[u("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:R("Indexing"),handler:Md},...km,{id:zt,command:zt,description:"Internal diff-impact batch worker",hidden:!0,options:[u("--json","Emit the private worker envelope without transport pagination"),u("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Od},{id:"diff-impact",command:"diff-impact",agent:C("Which symbols changed in this diff and which downstream consumers are affected?","changed symbols, downstream consumer identities, and impact paths",[],"bounded","diff"),description:"Map changed symbols and downstream consumers from the current git diff",options:x([u("--base <ref>","Git ref to diff against (default: HEAD)")]),claims:Je(["index-generation","live-workspace"],[X("changed-files","changedFiles[]","repository-source"),X("changed-symbols","changedSymbols[]","compiler-graph"),X("downstream-consumers","affected[]","compiler-graph")]),renderShape:"custom",docs:R("Impact"),handler:Dd},{id:Qt,command:Qt,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[u("--json","Emit the private worker envelope without transport pagination"),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:qd},{id:Kt,command:Kt,description:"Internal health semantic prewarm worker",hidden:!0,options:[u("--json","Emit the private worker envelope without transport pagination"),u("-s, --scope <path>","Limit to files matching path"),u("--full","Materialize complete semantic evidence"),u("--shard-index <n>","Warm only this zero-based slice of the indexed files"),u("--shard-count <n>","Number of parallel prewarm slices")],renderShape:"custom",handler:Fd},{id:"health",command:"health",agent:ge("Where has this repository accumulated drift, duplication, complexity, or cleanup pressure?","health score, findings, priorities, baselines, and coverage notes",[],"bounded","repository",z("repository-observation",[{when:{kind:"option",name:"writeBaseline",equals:!0},role:"composite"}])),description:"Composite repository health report with React, Vue, and general cleanup findings",options:x([u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded candidate analyses on large indexes"),u("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),u("--write-baseline","Snapshot current finding identities to the baseline file")]),claims:Je(["index-generation","live-workspace","process"],[_a("actions","actions[]","evidence",{"graph-fact":"compiler-graph",heuristic:"heuristic","change-graph":"change-history"}),X("coverage-notes","coverage","repository-source")]),renderShape:"custom",docs:R("Health",["scip-query health --json","scip-query health --baseline"]),handler:Wd},{id:"install-skills",command:"install-skills",agent:ge("Which scip-query skills were installed, updated, skipped, or conflicted?","skill target paths and install outcomes",[],"complete","repository",z("mutation")),description:`Install skills (${Ac.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:R("Maintenance"),handler:_d},{id:"check-deps",command:"check-deps",agent:C("Which scip-query and language-indexer dependencies are runnable?","dependency readiness statuses and remediation",[],"complete","repository",z("environment-observation")),description:"Check whether scip-query and the detected language indexers are runnable",renderShape:"custom",docs:R("Maintenance"),handler:Bd},{id:"capabilities",command:"capabilities",agent:C("Which repository-mapping and analysis capabilities are available here?","capability matrix with availability and reasons",[],"complete","repository",z("environment-observation")),description:"Report which mapping and analysis capabilities are available in this project",options:x([u("--matrix","Add exhaustive provider and language support details")]),renderShape:"custom",docs:R("Maintenance"),handler:Gd},{id:"init",command:"init",agent:ge("Can a starter scip-query configuration be created for this project?","configuration path and creation outcome",[],"complete","repository",z("mutation")),description:"Create a .scipquery.json configuration file for this project",renderShape:"custom",docs:R("Maintenance"),handler:Vd},{id:"config-validate",command:"config-validate",agent:C("Is this project configuration valid and internally consistent?","validation diagnostics with configuration paths",[],"complete","repository"),description:"Validate .scipquery.json, structured suppressions, architecture, and coupling groups",options:x(),claims:Wa("repository-source",["live-workspace"]),renderShape:"custom",docs:R("Maintenance",["scip-query config-validate"]),handler:Ud},{id:"suppress",command:"suppress <id>",agent:ge("Can this accepted finding be recorded with an auditable reason?","suppression identity, path, scope, and expiry",["finding"],"complete",void 0,z("mutation")),description:"Record an accepted finding under .scipquery/suppressions with a required reason",options:x([u("--reason <text>","Required concrete claim explaining why the detector remediation is inapplicable"),u("--reason-code <code>","Required adjudication code"),u("--evidence <kind:referent>","Required counterevidence; repeat for more evidence",U,[]),u("--check <check>","Optional detector name to narrow the suppression"),u("--file <path>","Optional file path to narrow the suppression"),u("--expires-at <iso>","Optional ISO date after which the suppression expires"),u("--replace <revision>","Replace a prior decision with this exact SHA-256 revision")]),renderShape:"custom",docs:R("Maintenance"),handler:Hd},{id:"doctor",command:"doctor",agent:C("Why is scip-query unhealthy or unavailable in this project?","configuration, freshness, dependency, and capability diagnostics",[],"complete","repository",z("environment-observation")),description:"Diagnose configuration, index freshness, dependencies, and project capabilities",options:x(),renderShape:"custom",docs:R("Maintenance"),handler:Qd},{id:"setup",command:"setup",agent:ge("Can scip-query be bootstrapped end to end in this project?","setup step outcomes, files, capabilities, smoke tests, and warnings",[],"complete","repository",z("composite")),description:"Install skills, write agent guidance, refresh the index, and report readiness",options:x([u("--guided","Require and open the interactive terminal checklist"),u("--yes","Accept recommended setup defaults without prompting"),u("--no-skills","Skip user-level agent skill installation"),u("--no-parsers","Skip Tree-sitter AST parser installation and repair"),u("--install-missing","Install missing global tools at reviewed immutable versions"),u("--health","Run the optional full health report and write its dossier"),{flags:"--no-health",description:"Compatibility inverse of --health",hidden:!0},u("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:R("Maintenance",["scip-query setup","scip-query setup --health","scip-query setup --install-missing","scip-query setup --json"]),handler:Jd},{id:"setup-agent",command:"setup-agent",agent:ge("Can concise project guidance for scip-query be written?","written, unchanged, and skipped agent instruction files",[],"complete","repository",z("mutation")),description:"Write concise scip-query mapping and cleanup guidance to AGENTS.md and CLAUDE.md",renderShape:"custom",docs:R("Maintenance",["scip-query setup-agent"]),handler:zd},{id:"uninstall",command:"uninstall",agent:ge("Which scip-query-owned integrations can be removed without touching user-owned files?","removed, retained, skipped, and dry-run targets",[],"complete","repository",z("mutation",[{when:{kind:"option",name:"dryRun",equals:!0},role:"repository-preview"}])),description:"Remove selected scip-query-owned skills or project guidance",options:x([u("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),u("--project","Remove managed AGENTS.md and CLAUDE.md blocks"),u("--dry-run","List what would be removed without changing files"),u("--verbose","List every unrelated global skill entry left in place")]),renderShape:"custom",docs:R("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:Yd},{id:"watch",command:"watch",agent:ge("What is the watcher doing, or can background services be started, stopped, or pruned?","watcher state, generation, activity, and errors",[],"complete","repository",z("composite",[{when:{kind:"option",name:"status",equals:!0},role:"environment-observation"}])),description:"Watch in the foreground or manage the project refresh service",options:x([u("--daemon","Make sure that the background service is running"),u("--status","Show the watcher state"),u("--stop","Stop the watcher for this project"),u("--prune","Stop watcher services whose owned worktree roots no longer exist"),u("--debounce <ms>","Milliseconds after the last change",ze),u("--cooldown <ms>","Minimum milliseconds between indexes",ze),u("--git-poll <ms>","Milliseconds between Git state checks",ze),u("--idle-timeout <ms>","Milliseconds before a clean idle daemon exits",ze)]),renderShape:"custom",docs:R("Maintenance"),handler:Xd},{id:"status",command:"status",agent:C("Is the index fresh, complete, and usable for this project?","freshness, generation, language shards, and watcher state",[],"complete","repository",z("environment-observation")),description:"Show index status for this project",options:x([{...u("--capabilities","Compatibility: include a concise capability-readiness summary"),hidden:!0}]),renderShape:"custom",docs:R("Maintenance"),handler:tu}];export{JI as commandDescriptors};
343
- //# sourceMappingURL=command-descriptors-P34VABY5.js.map