scip-query 0.20.0 → 0.21.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 (586) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +255 -884
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-CI3O6PQG.js +2 -0
  5. package/dist/call-graph-6QTUTXH7.js +2 -0
  6. package/dist/call-graph-evidence-lZa2dwQA.d.ts +11 -0
  7. package/dist/change-analysis-types-CCtoCHbC.d.ts +9 -0
  8. package/dist/chunk-26CT72HM.js +2 -0
  9. package/dist/{chunk-7PIO7NKH.js → chunk-2COFMIVK.js} +2 -2
  10. package/dist/chunk-2H4IAJHO.js +2 -0
  11. package/dist/chunk-2I3RSUWX.js +16 -0
  12. package/dist/chunk-2RP27XLR.js +2 -0
  13. package/dist/chunk-2ZBMOQGG.js +3 -0
  14. package/dist/{chunk-HX4GQPZP.js → chunk-32A42O5B.js} +3 -3
  15. package/dist/chunk-35ELD3RM.js +2 -0
  16. package/dist/chunk-35IW3P4H.js +2 -0
  17. package/dist/{chunk-DQGFVPUV.js → chunk-3653GTR7.js} +3 -3
  18. package/dist/chunk-3EX7DNBC.js +2 -0
  19. package/dist/chunk-3FQ3KMCD.js +2 -0
  20. package/dist/{chunk-5E4WNAVD.js → chunk-3PII3JI5.js} +2 -2
  21. package/dist/chunk-3TNRNKAT.js +2 -0
  22. package/dist/chunk-3VLJ2DCA.js +2 -0
  23. package/dist/{chunk-XSRF6Q77.js → chunk-46JLFIGA.js} +2 -2
  24. package/dist/chunk-4DCKBY6T.js +5 -0
  25. package/dist/chunk-4EXFZP6H.js +2 -0
  26. package/dist/chunk-4IIMPWMR.js +29 -0
  27. package/dist/chunk-4ILHWBYF.js +2 -0
  28. package/dist/chunk-4N6QSEMZ.js +10 -0
  29. package/dist/chunk-4OE2JO6I.js +2 -0
  30. package/dist/{chunk-7BAVHKMJ.js → chunk-4S4DF62J.js} +9 -9
  31. package/dist/chunk-4UUCUASK.js +554 -0
  32. package/dist/chunk-5236NQV3.js +2 -0
  33. package/dist/chunk-54EOGFBR.js +2 -0
  34. package/dist/{chunk-LY4WC4AD.js → chunk-5H7IWVXJ.js} +2 -2
  35. package/dist/chunk-5IZTXSOL.js +117 -0
  36. package/dist/{chunk-AZJQQKDD.js → chunk-5SE323LF.js} +2 -2
  37. package/dist/chunk-5ZJH6DDE.js +2 -0
  38. package/dist/chunk-63MBA7EG.js +3 -0
  39. package/dist/chunk-6BJ7SOY7.js +2 -0
  40. package/dist/chunk-6GJAP4OE.js +2 -0
  41. package/dist/chunk-6IEVHGWG.js +26 -0
  42. package/dist/chunk-6SWA6B24.js +7 -0
  43. package/dist/chunk-6T7H2AFY.js +3 -0
  44. package/dist/chunk-73Z33VFI.js +4 -0
  45. package/dist/chunk-7COHFNJK.js +38 -0
  46. package/dist/chunk-7HU2IJ2T.js +3 -0
  47. package/dist/chunk-7IOAZRVL.js +60 -0
  48. package/dist/chunk-7KCZELVM.js +2 -0
  49. package/dist/chunk-7PPYXENX.js +2 -0
  50. package/dist/chunk-7TWP3MCP.js +2 -0
  51. package/dist/chunk-AA7K3XLM.js +21 -0
  52. package/dist/chunk-AJVMVE7X.js +7 -0
  53. package/dist/chunk-ANWGXPPN.js +4 -0
  54. package/dist/chunk-APLKXICZ.js +3 -0
  55. package/dist/{chunk-JDOEX4E6.js → chunk-AQDWTCDC.js} +2 -2
  56. package/dist/chunk-AUP6YI5M.js +2 -0
  57. package/dist/chunk-B7ECWJAZ.js +2 -0
  58. package/dist/{chunk-ZHXX42OH.js → chunk-BATIVRU2.js} +4 -4
  59. package/dist/chunk-BBEDPVPB.js +4 -0
  60. package/dist/chunk-BBWPOMGU.js +2 -0
  61. package/dist/chunk-BD6CV7PN.js +2 -0
  62. package/dist/{chunk-XKWKXZKW.js → chunk-BHE44MHT.js} +2 -2
  63. package/dist/chunk-BOJ5SVE2.js +2 -0
  64. package/dist/chunk-BZYSGZRK.js +2 -0
  65. package/dist/chunk-CA5RE6H7.js +2 -0
  66. package/dist/chunk-CKDOY6JA.js +2 -0
  67. package/dist/chunk-CN2WGM7D.js +2 -0
  68. package/dist/chunk-COTMS5KM.js +3 -0
  69. package/dist/chunk-CSDDOUA4.js +3 -0
  70. package/dist/chunk-CT5SI2I4.js +2 -0
  71. package/dist/chunk-D5EKVZPI.js +2 -0
  72. package/dist/{chunk-FKSELJQF.js → chunk-D5W4UZY5.js} +2 -2
  73. package/dist/{chunk-RUJURYSV.js → chunk-DEUGHURX.js} +2 -2
  74. package/dist/chunk-DHKBIOXF.js +7 -0
  75. package/dist/chunk-DMQ7ZKJG.js +81 -0
  76. package/dist/chunk-DMUGTKMD.js +2 -0
  77. package/dist/chunk-DOPCR5BY.js +2 -0
  78. package/dist/chunk-DRENNWRG.js +2 -0
  79. package/dist/chunk-E4EJBGDZ.js +2 -0
  80. package/dist/chunk-E7BJXRNV.js +2 -0
  81. package/dist/chunk-EA4SH4U5.js +5 -0
  82. package/dist/{chunk-L7AW2QB5.js → chunk-EKZRF57O.js} +2 -2
  83. package/dist/chunk-ELNRLMC5.js +29 -0
  84. package/dist/chunk-F4FNK44D.js +2 -0
  85. package/dist/chunk-F7WQ337U.js +308 -0
  86. package/dist/chunk-FEQIQ26E.js +2 -0
  87. package/dist/chunk-FGB567HK.js +23 -0
  88. package/dist/chunk-FHV7NMFU.js +29 -0
  89. package/dist/chunk-FN6EJM6Q.js +2 -0
  90. package/dist/chunk-FTSQNONX.js +2 -0
  91. package/dist/chunk-FUG6RPYY.js +6 -0
  92. package/dist/chunk-G2F6T5BV.js +2 -0
  93. package/dist/chunk-G6OGPXJW.js +9 -0
  94. package/dist/chunk-GFLTPNWV.js +3 -0
  95. package/dist/chunk-GTDP2SKQ.js +2 -0
  96. package/dist/chunk-H46QMB7E.js +2 -0
  97. package/dist/chunk-H5EXS3HM.js +2 -0
  98. package/dist/chunk-HEOMG7IM.js +8 -0
  99. package/dist/chunk-HG5YI7PV.js +2 -0
  100. package/dist/{chunk-7SQQWSY3.js → chunk-HGKEAP7F.js} +2 -2
  101. package/dist/chunk-HUZNZ3H2.js +2 -0
  102. package/dist/chunk-HWLCBKFE.js +2 -0
  103. package/dist/chunk-I3U2FN2T.js +13 -0
  104. package/dist/{chunk-JAYYFEQY.js → chunk-I7PFL5P3.js} +2 -2
  105. package/dist/{chunk-2HPVVXM5.js → chunk-ICHBVITH.js} +2 -2
  106. package/dist/chunk-ICUQONOG.js +38 -0
  107. package/dist/chunk-IDPLC3FI.js +5 -0
  108. package/dist/{chunk-A73XVBCR.js → chunk-IGKKTHJR.js} +2 -2
  109. package/dist/chunk-IOKWFRFQ.js +4 -0
  110. package/dist/chunk-IPAL6DP2.js +3 -0
  111. package/dist/chunk-IUJ3ZFEE.js +7 -0
  112. package/dist/chunk-IXJ26KJJ.js +16 -0
  113. package/dist/chunk-IYV2YBHM.js +2 -0
  114. package/dist/chunk-JVZNWJBH.js +2 -0
  115. package/dist/chunk-K5MZYZV7.js +3 -0
  116. package/dist/{chunk-3G66UZBH.js → chunk-KFK7GF5C.js} +2 -2
  117. package/dist/chunk-KTRGJLY7.js +18 -0
  118. package/dist/chunk-KW6B5OL4.js +2 -0
  119. package/dist/chunk-KWARB5FZ.js +2 -0
  120. package/dist/chunk-LHTT5C3Z.js +2 -0
  121. package/dist/chunk-LPGDO2XA.js +3 -0
  122. package/dist/chunk-LXLD46LH.js +21 -0
  123. package/dist/chunk-MEI3PTUK.js +2 -0
  124. package/dist/chunk-MJNV7OCG.js +5 -0
  125. package/dist/chunk-MO226P4Q.js +4 -0
  126. package/dist/{chunk-3CLX5EOX.js → chunk-MOBF2GH6.js} +2 -2
  127. package/dist/chunk-MXNGIEPU.js +3 -0
  128. package/dist/chunk-MYUKI5VN.js +4 -0
  129. package/dist/{chunk-TFRAYKN6.js → chunk-N5C65OFK.js} +2 -2
  130. package/dist/{chunk-PXY7F6Y4.js → chunk-O2RM7E7L.js} +5 -5
  131. package/dist/chunk-OFUBXBYX.js +3 -0
  132. package/dist/chunk-OFY4HTMI.js +2 -0
  133. package/dist/chunk-OIRWZIYL.js +38 -0
  134. package/dist/chunk-OIVZ7PW6.js +438 -0
  135. package/dist/chunk-ORBKAUCH.js +4 -0
  136. package/dist/chunk-OUB4J26T.js +2 -0
  137. package/dist/chunk-OVPS2ILI.js +20 -0
  138. package/dist/chunk-PHSPBQM6.js +5 -0
  139. package/dist/{chunk-JVYA47YU.js → chunk-PIZY2GX6.js} +2 -2
  140. package/dist/chunk-PNISDVYC.js +3 -0
  141. package/dist/chunk-PQOL42AW.js +2 -0
  142. package/dist/chunk-PUVZNFVY.js +11 -0
  143. package/dist/chunk-PZEI2TVL.js +4 -0
  144. package/dist/{chunk-ZK26BAQL.js → chunk-Q2J2VZZT.js} +2 -2
  145. package/dist/chunk-Q7HB7BFJ.js +2 -0
  146. package/dist/{chunk-ZTETIQ35.js → chunk-QBANU5BQ.js} +2 -2
  147. package/dist/chunk-QD7IFBCR.js +10 -0
  148. package/dist/chunk-QDCCHMVZ.js +2 -0
  149. package/dist/chunk-QLQBZOJH.js +3 -0
  150. package/dist/{chunk-PQCI4SQX.js → chunk-QXR5QPSF.js} +2 -2
  151. package/dist/chunk-R2MOKIVO.js +2 -0
  152. package/dist/{chunk-EN3O7VJA.js → chunk-RFWAUHVW.js} +2 -2
  153. package/dist/chunk-RGCJ4646.js +16 -0
  154. package/dist/{chunk-BPAPWKP6.js → chunk-S3RTPPLQ.js} +8 -8
  155. package/dist/chunk-S73HBCGI.js +11 -0
  156. package/dist/chunk-SDPA5DKN.js +210 -0
  157. package/dist/chunk-SEUJVWT2.js +3 -0
  158. package/dist/chunk-SF7X6QNW.js +2 -0
  159. package/dist/chunk-SKUMCCC5.js +2 -0
  160. package/dist/chunk-SSSJO4RG.js +2 -0
  161. package/dist/chunk-SWFAFA4G.js +49 -0
  162. package/dist/chunk-SYUNTKO2.js +2 -0
  163. package/dist/chunk-T6FRID7Y.js +3 -0
  164. package/dist/chunk-TGWNNMPF.js +3 -0
  165. package/dist/chunk-TM5XEDDR.js +4 -0
  166. package/dist/chunk-TNOHGHZQ.js +2 -0
  167. package/dist/chunk-U2GPTA5U.js +3 -0
  168. package/dist/{chunk-SXP2MBJH.js → chunk-U7DR7MJD.js} +2 -2
  169. package/dist/chunk-U7LRSQG6.js +3 -0
  170. package/dist/chunk-UL4VJUMD.js +2 -0
  171. package/dist/chunk-UNORWZIJ.js +16 -0
  172. package/dist/chunk-UQ7XPRWU.js +2 -0
  173. package/dist/{chunk-6SHPK5ZE.js → chunk-URMZLV2N.js} +2 -2
  174. package/dist/chunk-URTX2BEA.js +6 -0
  175. package/dist/chunk-UZFCZ7SJ.js +2 -0
  176. package/dist/{chunk-KMKTIO2G.js → chunk-V7LQZTTZ.js} +2 -2
  177. package/dist/chunk-VETXXOYU.js +3 -0
  178. package/dist/chunk-VGRUM7JI.js +3 -0
  179. package/dist/{chunk-WXZLAAWK.js → chunk-VNKYRJKN.js} +2 -2
  180. package/dist/chunk-VWLIOEEF.js +11 -0
  181. package/dist/chunk-WB6LGCFB.js +6 -0
  182. package/dist/{chunk-W4ETQAXM.js → chunk-WK4FD4PG.js} +2 -2
  183. package/dist/{chunk-O64IZ6UX.js → chunk-WKPZCQLI.js} +2 -2
  184. package/dist/chunk-WSG3DK5H.js +2 -0
  185. package/dist/chunk-WULAPQUD.js +38 -0
  186. package/dist/chunk-WZQFY5S7.js +4 -0
  187. package/dist/chunk-X434XZAI.js +2 -0
  188. package/dist/chunk-X7PJJYKX.js +29 -0
  189. package/dist/chunk-XDAUYDFT.js +2 -0
  190. package/dist/chunk-XITQLISP.js +2 -0
  191. package/dist/chunk-XRXCANFQ.js +4 -0
  192. package/dist/chunk-XVDMJMES.js +3 -0
  193. package/dist/chunk-XXJ7WL3F.js +35 -0
  194. package/dist/chunk-Y4XQ7LES.js +9 -0
  195. package/dist/chunk-YIEFEPG6.js +16 -0
  196. package/dist/chunk-YRVERHJR.js +49 -0
  197. package/dist/{chunk-CJST5ETY.js → chunk-YUFWLWIC.js} +2 -2
  198. package/dist/chunk-YUKYB54I.js +1 -0
  199. package/dist/chunk-Z3GCK3PD.js +3 -0
  200. package/dist/chunk-ZBNL3QCY.js +4 -0
  201. package/dist/chunk-ZD3Z54IW.js +2 -0
  202. package/dist/chunk-ZDVDSDFG.js +4 -0
  203. package/dist/{chunk-32LVLCLN.js → chunk-ZHSARYVS.js} +3 -3
  204. package/dist/{chunk-BDCC2NPY.js → chunk-ZW44MCJM.js} +2 -2
  205. package/dist/{chunk-N5W4YZMK.js → chunk-ZYREOING.js} +2 -2
  206. package/dist/cli-main.js +8 -0
  207. package/dist/cli.js +1 -3
  208. package/dist/code-CczEvHui.d.ts +121 -0
  209. package/dist/code-EQL6ZBLH.js +2 -0
  210. package/dist/code-result-json-6E4J6LGZ.js +2 -0
  211. package/dist/command-descriptors-QH3G2OVD.js +346 -0
  212. package/dist/{config-types-jVM3D7MA.d.ts → config-types-Cm-VSEBb.d.ts} +189 -23
  213. package/dist/dataflow-2BLMUZBP.js +2 -0
  214. package/dist/{db-B5PM5yNk.d.ts → db-LKJXAlNS.d.ts} +1 -1
  215. package/dist/dependence-slice-MGAJDZXB.js +2 -0
  216. package/dist/deps-GQMUYVKW.js +2 -0
  217. package/dist/direct-navigation-6RUJKLAV.js +3 -0
  218. package/dist/entry-map-V2NQP5JU.js +2 -0
  219. package/dist/exploration-topology-BG4v30HZ.d.ts +256 -0
  220. package/dist/file-dep-graph-Bqg3t3Px.d.ts +4 -0
  221. package/dist/file-kind-BKCVMNUf.d.ts +10 -0
  222. package/dist/files-VM53I4IU.js +2 -0
  223. package/dist/graph-evidence-CbUPCSKV.d.ts +126 -0
  224. package/dist/graph-exploration-contract-CqDsnPQL.d.ts +7 -0
  225. package/dist/{health-Do5TKSJI.d.ts → health-Wl5G_LRt.d.ts} +33 -34
  226. package/dist/hierarchy-D553WRSZ.js +2 -0
  227. package/dist/imports-DOZAJWLW.js +2 -0
  228. package/dist/index.d.ts +4 -31
  229. package/dist/index.js +1 -1
  230. package/dist/members-HE67475K.js +2 -0
  231. package/dist/methods-K5JK4PPH.js +2 -0
  232. package/dist/next-anchor-candidates-BwMczMvX.d.ts +90 -0
  233. package/dist/output-continuation-command-LKBUTNRL.js +3 -0
  234. package/dist/output-pagination-VAWOGX4R.js +19 -0
  235. package/dist/postinstall.js +1 -1
  236. package/dist/project-reindex-4ARU6QCM.js +3 -0
  237. package/dist/queries/affected.d.ts +22 -4
  238. package/dist/queries/affected.js +1 -1
  239. package/dist/queries/anchors.d.ts +123 -0
  240. package/dist/queries/anchors.js +2 -0
  241. package/dist/queries/architecture.d.ts +3 -2
  242. package/dist/queries/architecture.js +1 -1
  243. package/dist/queries/bottlenecks.d.ts +26 -7
  244. package/dist/queries/bottlenecks.js +1 -1
  245. package/dist/queries/by-kind.d.ts +2 -2
  246. package/dist/queries/by-kind.js +1 -1
  247. package/dist/queries/call-graph.d.ts +17 -3
  248. package/dist/queries/call-graph.js +1 -1
  249. package/dist/queries/change-surface.d.ts +2 -2
  250. package/dist/queries/change-surface.js +1 -1
  251. package/dist/queries/cleanup-plan.d.ts +2 -2
  252. package/dist/queries/cleanup-plan.js +1 -1
  253. package/dist/queries/co-change.d.ts +2 -2
  254. package/dist/queries/co-change.js +1 -1
  255. package/dist/queries/code.d.ts +5 -26
  256. package/dist/queries/code.js +1 -1
  257. package/dist/queries/complexity-hotspots.d.ts +2 -2
  258. package/dist/queries/complexity-hotspots.js +1 -1
  259. package/dist/queries/complexity.d.ts +2 -2
  260. package/dist/queries/complexity.js +1 -1
  261. package/dist/queries/context.d.ts +145 -0
  262. package/dist/queries/context.js +2 -0
  263. package/dist/queries/convergence.d.ts +2 -2
  264. package/dist/queries/convergence.js +1 -1
  265. package/dist/queries/coupling.d.ts +8 -3
  266. package/dist/queries/coupling.js +1 -1
  267. package/dist/queries/cycles.d.ts +34 -7
  268. package/dist/queries/cycles.js +1 -1
  269. package/dist/queries/dataflow.d.ts +40 -14
  270. package/dist/queries/dataflow.js +1 -1
  271. package/dist/queries/dead.d.ts +2 -2
  272. package/dist/queries/dead.js +1 -1
  273. package/dist/queries/decorative-checkers.d.ts +3 -3
  274. package/dist/queries/decorative-checkers.js +1 -1
  275. package/dist/queries/deep-chains.d.ts +4 -38
  276. package/dist/queries/deep-chains.js +1 -1
  277. package/dist/queries/dependence-slice.d.ts +47 -0
  278. package/dist/queries/dependence-slice.js +2 -0
  279. package/dist/queries/dependency-depth.d.ts +49 -0
  280. package/dist/queries/dependency-depth.js +2 -0
  281. package/dist/queries/deps.d.ts +4 -2
  282. package/dist/queries/deps.js +1 -1
  283. package/dist/queries/diff-impact.d.ts +3 -3
  284. package/dist/queries/diff-impact.js +1 -1
  285. package/dist/queries/doc-drift.d.ts +4 -4
  286. package/dist/queries/doc-drift.js +1 -1
  287. package/dist/queries/drift.d.ts +2 -2
  288. package/dist/queries/drift.js +1 -1
  289. package/dist/queries/duplicate-bodies.d.ts +2 -2
  290. package/dist/queries/duplicate-bodies.js +1 -1
  291. package/dist/queries/entry-map.d.ts +121 -0
  292. package/dist/queries/entry-map.js +2 -0
  293. package/dist/queries/evidence.d.ts +70 -0
  294. package/dist/queries/evidence.js +2 -0
  295. package/dist/queries/extract-candidates.d.ts +2 -2
  296. package/dist/queries/extract-candidates.js +1 -1
  297. package/dist/queries/fan.d.ts +18 -5
  298. package/dist/queries/fan.js +1 -1
  299. package/dist/queries/files.d.ts +2 -2
  300. package/dist/queries/files.js +1 -1
  301. package/dist/queries/health.d.ts +4 -3
  302. package/dist/queries/health.js +1 -1
  303. package/dist/queries/hierarchy.d.ts +5 -3
  304. package/dist/queries/hierarchy.js +1 -1
  305. package/dist/queries/hotspots.d.ts +11 -5
  306. package/dist/queries/hotspots.js +1 -1
  307. package/dist/queries/imports.d.ts +2 -2
  308. package/dist/queries/imports.js +1 -1
  309. package/dist/queries/incomplete-migration.d.ts +4 -4
  310. package/dist/queries/incomplete-migration.js +1 -1
  311. package/dist/queries/index.d.ts +56 -136
  312. package/dist/queries/index.js +1 -1
  313. package/dist/queries/isolated.d.ts +2 -2
  314. package/dist/queries/isolated.js +1 -1
  315. package/dist/queries/locality-candidates.d.ts +2 -2
  316. package/dist/queries/locality-candidates.js +1 -1
  317. package/dist/queries/members.d.ts +2 -2
  318. package/dist/queries/members.js +1 -1
  319. package/dist/queries/methods.d.ts +2 -2
  320. package/dist/queries/methods.js +1 -1
  321. package/dist/queries/not-implemented.d.ts +3 -3
  322. package/dist/queries/not-implemented.js +1 -1
  323. package/dist/queries/outline.d.ts +2 -2
  324. package/dist/queries/outline.js +1 -1
  325. package/dist/queries/passthrough-candidates.d.ts +5 -9
  326. package/dist/queries/passthrough-candidates.js +1 -1
  327. package/dist/queries/plan-context.d.ts +27 -64
  328. package/dist/queries/plan-context.js +1 -1
  329. package/dist/queries/react-component-duplicates.d.ts +2 -2
  330. package/dist/queries/react-component-duplicates.js +1 -1
  331. package/dist/queries/react-hook-candidates.d.ts +2 -2
  332. package/dist/queries/react-hook-candidates.js +1 -1
  333. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  334. package/dist/queries/react-large-component-pressure.js +1 -1
  335. package/dist/queries/recent-duplicates.d.ts +2 -2
  336. package/dist/queries/recent-duplicates.js +1 -1
  337. package/dist/queries/redundant-reexports.d.ts +2 -2
  338. package/dist/queries/redundant-reexports.js +1 -1
  339. package/dist/queries/reference-neighborhood.d.ts +4 -0
  340. package/dist/queries/reference-neighborhood.js +2 -0
  341. package/dist/queries/reference-reachability.d.ts +48 -0
  342. package/dist/queries/reference-reachability.js +2 -0
  343. package/dist/queries/refs.d.ts +2 -2
  344. package/dist/queries/refs.js +1 -1
  345. package/dist/queries/self-audit.d.ts +2 -2
  346. package/dist/queries/self-audit.js +1 -1
  347. package/dist/queries/similar-chains.d.ts +2 -2
  348. package/dist/queries/similar-chains.js +1 -1
  349. package/dist/queries/similar-files.d.ts +2 -2
  350. package/dist/queries/similar-files.js +1 -1
  351. package/dist/queries/similar-signatures.d.ts +2 -2
  352. package/dist/queries/similar-signatures.js +1 -1
  353. package/dist/queries/similar.d.ts +2 -2
  354. package/dist/queries/similar.js +1 -1
  355. package/dist/queries/slice.d.ts +3 -36
  356. package/dist/queries/slice.js +1 -1
  357. package/dist/queries/source-inspection.d.ts +209 -0
  358. package/dist/queries/source-inspection.js +2 -0
  359. package/dist/queries/source-search.d.ts +13 -0
  360. package/dist/queries/source-search.js +2 -0
  361. package/dist/queries/stale-abstractions.d.ts +2 -2
  362. package/dist/queries/stale-abstractions.js +1 -1
  363. package/dist/queries/stats.d.ts +2 -2
  364. package/dist/queries/surface.d.ts +13 -4
  365. package/dist/queries/surface.js +1 -1
  366. package/dist/queries/symbols.d.ts +2 -2
  367. package/dist/queries/symbols.js +1 -1
  368. package/dist/queries/system-map.d.ts +449 -0
  369. package/dist/queries/system-map.js +2 -0
  370. package/dist/queries/system.d.ts +5 -3
  371. package/dist/queries/system.js +1 -1
  372. package/dist/queries/test-quality.d.ts +2 -2
  373. package/dist/queries/test-quality.js +1 -1
  374. package/dist/queries/trace.d.ts +47 -3
  375. package/dist/queries/trace.js +1 -1
  376. package/dist/queries/twin-ab.d.ts +3 -3
  377. package/dist/queries/twin-ab.js +1 -1
  378. package/dist/queries/twin-drift.d.ts +3 -3
  379. package/dist/queries/twin-drift.js +1 -1
  380. package/dist/queries/unused-imports.d.ts +2 -2
  381. package/dist/queries/unused-imports.js +1 -1
  382. package/dist/queries/unused-params.d.ts +2 -2
  383. package/dist/queries/unused-params.js +1 -1
  384. package/dist/queries/value-flow.d.ts +43 -0
  385. package/dist/queries/value-flow.js +2 -0
  386. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  387. package/dist/queries/vue-component-duplicates.js +1 -1
  388. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  389. package/dist/queries/vue-composable-candidates.js +1 -1
  390. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  391. package/dist/queries/vue-large-view-pressure.js +1 -1
  392. package/dist/queries/wrapper-candidates.d.ts +2 -2
  393. package/dist/queries/wrapper-candidates.js +1 -1
  394. package/dist/query-service-fastpath.js +6 -0
  395. package/dist/query-service-server.js +5 -0
  396. package/dist/refs-NBHKL4UQ.js +2 -0
  397. package/dist/refs-pagination-BBVTIHMH.js +2 -0
  398. package/dist/reindex-worker.js +27 -45
  399. package/dist/reindex.d.ts +62 -42
  400. package/dist/reindex.js +32 -33
  401. package/dist/repository-text-C0Q8VYdN.d.ts +19 -0
  402. package/dist/runtime.d.ts +286 -7
  403. package/dist/runtime.js +4 -3
  404. package/dist/rust-semantic-session-server.js +1 -1
  405. package/dist/rust-semantic-session-worker.js +1 -1
  406. package/dist/rust-semantic-worker.js +1 -1
  407. package/dist/{scip-cli-BnEwZRLJ.d.ts → scip-cli-CppzF5MK.d.ts} +33 -2
  408. package/dist/slice-U6S6LBSB.js +2 -0
  409. package/dist/source-search-types-Dwz8KeuW.d.ts +79 -0
  410. package/dist/source-snippet-_wrcgmZc.d.ts +15 -0
  411. package/dist/stats-OOJ74B32.js +2 -0
  412. package/dist/surface-C7SS5CDQ.js +2 -0
  413. package/dist/symbol-resolution-3FVEKDTJ.js +2 -0
  414. package/dist/system-6K2NOO5C.js +2 -0
  415. package/dist/trace-II5K2TMH.js +2 -0
  416. package/dist/typescript-mailbox-worker.js +1 -1
  417. package/dist/value-flow-MKFUUE5B.js +2 -0
  418. package/dist/watch-server.js +3 -2
  419. package/docs/AGENT_GUIDE.md +133 -476
  420. package/docs/AI_FAILURE_MODES.md +30 -301
  421. package/docs/API.md +1 -1
  422. package/docs/API_EVOLUTION.md +6 -0
  423. package/docs/CLI_JSON_OUTPUT.md +207 -29
  424. package/docs/COMMAND_REFERENCE.md +255 -154
  425. package/docs/CONFIGURATION_WRITE_SAFETY.md +14 -13
  426. package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +84 -0
  427. package/docs/DETECTOR_GUIDE.md +46 -138
  428. package/docs/DURABILITY.md +7 -1
  429. package/docs/INDEX_GENERATIONS.md +6 -0
  430. package/docs/LOCK_PROTOCOL.md +8 -0
  431. package/docs/REINDEX_METADATA_COMPATIBILITY.md +13 -3
  432. package/docs/SECURITY_MODEL.md +39 -42
  433. package/docs/accuracy-audit-checklist.md +4 -0
  434. package/docs/accuracy-hardening-goal.md +9 -2
  435. package/docs/analyzer-inventory.md +59 -264
  436. package/docs/analyzer-validation-protocol.md +62 -170
  437. package/docs/architecture-coherence-vision.md +18 -12
  438. package/docs/locality-analyzer-design.md +1 -1
  439. package/docs/schemas/cli-json-envelope.schema.json +212 -27
  440. package/docs/schemas/cli-json-export-receipt.schema.json +25 -0
  441. package/docs/schemas/cli-output-page.schema.json +1 -1
  442. package/docs/schemas/observation-receipt.schema.json +164 -0
  443. package/docs/schemas/project-config.schema.json +27 -45
  444. package/docs/schemas/suppression-record.schema.json +1 -34
  445. package/package.json +65 -8
  446. package/skills/concrete-plan/SKILL.md +8 -0
  447. package/skills/concrete-plan/agents/openai.yaml +4 -0
  448. package/skills/scip-explore/SKILL.md +3 -85
  449. package/skills/scip-explore/agents/openai.yaml +3 -3
  450. package/skills/scip-integrity-audit/SKILL.md +185 -0
  451. package/skills/scip-integrity-audit/agents/openai.yaml +4 -0
  452. package/skills/scip-plan/SKILL.md +67 -49
  453. package/skills/scip-plan/agents/openai.yaml +3 -3
  454. package/skills/scip-query/SKILL.md +77 -77
  455. package/skills/scip-query/agents/openai.yaml +3 -3
  456. package/skills/scip-setup/SKILL.md +10 -102
  457. package/skills/scip-setup/agents/openai.yaml +3 -3
  458. package/dist/chunk-26QA6FAI.js +0 -8
  459. package/dist/chunk-2KAZEZ6M.js +0 -2
  460. package/dist/chunk-3ORVDL3H.js +0 -2
  461. package/dist/chunk-46XGSFNI.js +0 -2
  462. package/dist/chunk-4MAK2HOY.js +0 -6
  463. package/dist/chunk-4TURLRL5.js +0 -16
  464. package/dist/chunk-4UQVNCQE.js +0 -2
  465. package/dist/chunk-55Q3WLZX.js +0 -2
  466. package/dist/chunk-5I5G2QOX.js +0 -3
  467. package/dist/chunk-6LDJQXAH.js +0 -2
  468. package/dist/chunk-6O5TICIZ.js +0 -3
  469. package/dist/chunk-7O5IKBTZ.js +0 -16
  470. package/dist/chunk-7S5E7KWT.js +0 -2
  471. package/dist/chunk-7WPLAODU.js +0 -5
  472. package/dist/chunk-AFHORGLH.js +0 -42
  473. package/dist/chunk-AIE7TFJW.js +0 -9
  474. package/dist/chunk-AQOFWNQJ.js +0 -1
  475. package/dist/chunk-B2PX5I6M.js +0 -2
  476. package/dist/chunk-B75HZHUP.js +0 -2
  477. package/dist/chunk-B7PBSLZN.js +0 -2
  478. package/dist/chunk-BBW6JFHN.js +0 -2
  479. package/dist/chunk-BNXCIFVY.js +0 -2
  480. package/dist/chunk-BS2NMXQZ.js +0 -4
  481. package/dist/chunk-C3KV2II6.js +0 -2
  482. package/dist/chunk-C43RDDP4.js +0 -20
  483. package/dist/chunk-DAFAHMNB.js +0 -42
  484. package/dist/chunk-DQLPXMH6.js +0 -8
  485. package/dist/chunk-EKZTZXHZ.js +0 -117
  486. package/dist/chunk-EW2NTSFA.js +0 -18
  487. package/dist/chunk-F3Z4OUDS.js +0 -8
  488. package/dist/chunk-FJH2NW7J.js +0 -66
  489. package/dist/chunk-FTFP6O3L.js +0 -11
  490. package/dist/chunk-FYLK2DEJ.js +0 -2
  491. package/dist/chunk-GH74ASD6.js +0 -11
  492. package/dist/chunk-GMXWZP2B.js +0 -2
  493. package/dist/chunk-GOUBFH5O.js +0 -3
  494. package/dist/chunk-HLF2TX6R.js +0 -2
  495. package/dist/chunk-HX7M4BDI.js +0 -30
  496. package/dist/chunk-HZ72SESS.js +0 -128
  497. package/dist/chunk-IB2N4FIY.js +0 -10
  498. package/dist/chunk-IZYYAFN5.js +0 -2
  499. package/dist/chunk-JFGGXWQF.js +0 -947
  500. package/dist/chunk-JN4NMBEX.js +0 -8
  501. package/dist/chunk-JW56N3KI.js +0 -4
  502. package/dist/chunk-JZ2OXNWB.js +0 -2
  503. package/dist/chunk-KFZNKUNT.js +0 -2
  504. package/dist/chunk-L5GJNV2T.js +0 -8
  505. package/dist/chunk-L7JDSCDF.js +0 -4
  506. package/dist/chunk-LU47HG23.js +0 -14
  507. package/dist/chunk-LVY7NPF7.js +0 -2
  508. package/dist/chunk-MKCDWWGV.js +0 -4
  509. package/dist/chunk-MNE7YG56.js +0 -2
  510. package/dist/chunk-MRXBEXSY.js +0 -26
  511. package/dist/chunk-MV7OWDUX.js +0 -2
  512. package/dist/chunk-NGEXCJJW.js +0 -11
  513. package/dist/chunk-NIW6JDC5.js +0 -29
  514. package/dist/chunk-PBUQFCNB.js +0 -16
  515. package/dist/chunk-POAVPHH7.js +0 -2
  516. package/dist/chunk-QZ4JVECJ.js +0 -2
  517. package/dist/chunk-RDO52JGY.js +0 -2
  518. package/dist/chunk-RJT3TUUZ.js +0 -2
  519. package/dist/chunk-RVLDN63O.js +0 -4
  520. package/dist/chunk-RXOXSKY3.js +0 -2
  521. package/dist/chunk-S7OYBOCK.js +0 -2
  522. package/dist/chunk-SMNXQT5Z.js +0 -3
  523. package/dist/chunk-SRAFT254.js +0 -2
  524. package/dist/chunk-T7YQSHPQ.js +0 -3
  525. package/dist/chunk-UJCOIXDY.js +0 -2
  526. package/dist/chunk-UJPRPGCO.js +0 -13
  527. package/dist/chunk-WCCFZ7V7.js +0 -113
  528. package/dist/chunk-WUPW3UN3.js +0 -3
  529. package/dist/chunk-X54AGLVX.js +0 -2
  530. package/dist/chunk-Y2MVPNKY.js +0 -5
  531. package/dist/chunk-YKUU5AIC.js +0 -3
  532. package/dist/chunk-YLCJLTPL.js +0 -2
  533. package/dist/chunk-YTQVETEO.js +0 -2
  534. package/dist/chunk-Z4N3MZYA.js +0 -38
  535. package/dist/chunk-ZJOOT3BG.js +0 -2
  536. package/dist/command-descriptors-DSS46KXI.js +0 -642
  537. package/dist/diff-gate-types-B0QYpDv1.d.ts +0 -11
  538. package/dist/direct-navigation-6YHV6IB5.js +0 -3
  539. package/dist/queries/diff-gate.d.ts +0 -253
  540. package/dist/queries/diff-gate.js +0 -2
  541. package/docs/COMMITTED_RECORD_COMPATIBILITY.md +0 -154
  542. package/docs/analyzer-validation-ledger.md +0 -516
  543. package/docs/schemas/outcome-event-record.schema.json +0 -95
  544. package/skills/_shared/SKILL.md +0 -101
  545. package/skills/_shared/agents/openai.yaml +0 -4
  546. package/skills/_shared/references/agent-contract-catalog.md +0 -105
  547. package/skills/_shared/references/command-catalog.md +0 -118
  548. package/skills/_shared/references/detector-precision-and-diffgate.md +0 -59
  549. package/skills/_shared/references/evidence-and-dead-code.md +0 -25
  550. package/skills/scip-audit/SKILL.md +0 -77
  551. package/skills/scip-audit/agents/openai.yaml +0 -4
  552. package/skills/scip-audit/references/claims.md +0 -98
  553. package/skills/scip-audit/references/cleanup.md +0 -100
  554. package/skills/scip-audit/references/directory.md +0 -222
  555. package/skills/scip-audit/references/frontend.md +0 -130
  556. package/skills/scip-audit/references/integrity.md +0 -154
  557. package/skills/scip-audit/references/maintainability.md +0 -162
  558. package/skills/scip-audit/references/twin-drift.md +0 -104
  559. package/skills/scip-diagnose/SKILL.md +0 -52
  560. package/skills/scip-diagnose/agents/openai.yaml +0 -4
  561. package/skills/scip-diagnose/references/debug.md +0 -117
  562. package/skills/scip-diagnose/references/probe-reachability.md +0 -77
  563. package/skills/scip-diagnose/references/root-cause.md +0 -145
  564. package/skills/scip-diagnose/references/triage.md +0 -119
  565. package/skills/scip-explore/references/diagrams.md +0 -40
  566. package/skills/scip-explore/references/language-playbook.md +0 -49
  567. package/skills/scip-improve/SKILL.md +0 -56
  568. package/skills/scip-improve/agents/openai.yaml +0 -4
  569. package/skills/scip-improve/references/cleanup-batches.md +0 -53
  570. package/skills/scip-improve/references/directory-moves.md +0 -53
  571. package/skills/scip-improve/references/doc-reconcile.md +0 -30
  572. package/skills/scip-improve/references/frontend-extraction.md +0 -39
  573. package/skills/scip-improve/references/maintainability-mechanism.md +0 -43
  574. package/skills/scip-improve/references/twin-drift.md +0 -35
  575. package/skills/scip-plan/references/api-impact.md +0 -19
  576. package/skills/scip-plan/references/conductor.md +0 -41
  577. package/skills/scip-plan/references/high-assurance.md +0 -43
  578. package/skills/scip-plan/references/hyper-optimization.md +0 -50
  579. package/skills/scip-plan/references/tla-model.md +0 -88
  580. package/skills/scip-setup/references/bootstrap-workflow.md +0 -119
  581. package/skills/scip-setup/references/language-verification.md +0 -61
  582. package/skills/scip-setup/references/lifecycle-commands.md +0 -119
  583. package/skills/scip-setup/references/per-repo-triage.md +0 -24
  584. package/skills/scip-verify/SKILL.md +0 -229
  585. package/skills/scip-verify/agents/openai.yaml +0 -4
  586. package/skills/scip-verify/references/calibrate-detectors.md +0 -170
@@ -0,0 +1,346 @@
1
+ #!/usr/bin/env node
2
+ import{a as va,b as Sa,c as $a,f as vt,g as gn,h as fn,j as wa,k as Ra,m as xa,o as yn}from"./chunk-6T7H2AFY.js";import{a as Ys}from"./chunk-PNISDVYC.js";import"./chunk-OVPS2ILI.js";import{a as W,b as S,c as De,d as le,e as ke,f as u,g as ni,h as Xs,i as x,j as w,k as Me,l as Zs,m as J,n as ea,o as Qe,p as C,q as he,r as bt,s as Mt,t as ii,u as qt,v as Ft,w as ae,x as ue,y as $e,z as la}from"./chunk-FHV7NMFU.js";import{A as b,B as O,C as k,D,E as aa,F as I,G as ca,H as de,a as me,b as z,i as Y,j as ee,k as ta,l as na,m as ia,n as nt,o as oi,p as oa,q as Ie,r as ra,s as Se,t as mn,u as sa,v as j,x as U,y as $,z as K}from"./chunk-COTMS5KM.js";import{$ as Sr,$a as Ss,$b as He,A as Jn,Aa as Qr,Ab as Xn,B as Yo,Ba as Kr,C as Xo,Ca as zr,D as Yn,Da as Jr,E as Zo,Ea as Yr,Eb as Fs,F as er,Fa as Xr,Fb as Ce,G as tr,Ga as Zr,H as nr,Ha as es,Hb as se,I as ir,Ia as ts,Ib as Zn,J as or,Ja as ns,K as rr,Ka as is,L as sr,La as os,M as ar,Ma as rs,N as cr,Na as ss,O as lr,Oa as as,Ob as Ws,P as dr,Pa as cs,Q as ur,Qa as ls,R as pr,Ra as ds,S as mr,Sa as us,Sb as Vs,T as hr,Ta as ps,Tb as ei,U as ft,Ua as ms,Ub as P,V as dt,Va as hs,Vb as fe,W as gr,Wa as gs,Wb as _,X as fr,Xa as fs,Xb as Gs,Y as yr,Ya as ys,Yb as A,Z as br,Za as bs,Zb as Nt,_ as vr,_a as vs,_b as Ot,a as Xt,aa as $r,ab as ws,b as It,ba as wr,bc as Us,c as Eo,ca as Rr,cb as Rs,cc as Hs,d as To,da as xr,db as yt,dc as Qs,e as Ao,ea as Cr,eb as Te,ec as Ks,f as Io,fa as kr,fb as ut,fc as zs,g as ln,ga as Er,gb as et,h as Fo,ha as Tr,hb as xs,i as Lt,ia as Ar,ib as Cs,j as _o,ja as Ir,jb as ks,jc as tt,k as Wo,ka as Lr,kb as Es,kc as Dt,l as Vo,la as Pr,m as Pt,ma as jr,mb as Ue,mc as Js,na as Nr,nb as Is,oa as Or,ob as Ls,p as Go,pa as Dr,pb as Ps,pc as ti,q as Uo,qa as Mr,qb as js,r as Ho,ra as qr,rb as Ns,s as Qo,sa as Fr,sb as Os,t as Ko,ta as Br,tb as Ds,u as zo,ua as _r,ub as Ms,va as Wr,vb as qs,w as jt,wa as Vr,wb as ce,x as un,xa as Gr,y as Jo,ya as Ur,z as Ge,za as Hr,zb as Ae}from"./chunk-4UUCUASK.js";import{a as Bt,b as ri,c as da,d as ua,e as pa,f as hn,g as ma,h as ha,i as ga,j as fa,k as ya,l as ba,m as Ca}from"./chunk-F7WQ337U.js";import{$b as ie,Ab as Kn,Ac as ko,Bc as on,Bd as Do,Ca as Hn,Cd as Mo,Da as yo,Dd as qo,H as mo,Ha as bo,Ia as Qn,Ma as We,N as ot,Na as vo,O as ho,Oa as So,Oe as Bs,P as Zt,Pb as xo,Pe as _s,Q as rt,Ra as st,Ta as $o,Td as Bo,Ud as dn,V as ve,W as pe,Xc as Ve,a as po,aa as en,ab as at,ac as Co,ca as ne,da as ge,hd as rn,id as Lo,jd as Po,je as $s,kd as sn,ke as pn,ld as an,m as At,mc as nn,md as lt,n as Un,ob as ct,od as cn,pb as wo,sa as go,td as zn,ua as fo,ud as jo,wd as No,xd as Oo,xe as Ts,yb as tn,ye as As,zb as Ro}from"./chunk-OIVZ7PW6.js";import{existsSync as bn,mkdirSync as mp,symlinkSync as hp,readlinkSync as si,unlinkSync as ai,readdirSync as ka}from"fs";import{join as qe,dirname as _t,resolve as it,relative as gp,isAbsolute as fp}from"path";import{homedir as Ea,platform as yp}from"os";import{fileURLToPath as Ta}from"url";var bp=yp()==="win32",Aa=["scip-query","scip-plan","scip-setup","scip-integrity-audit"];var Ia=["scip-query","scip-plan","scip-setup","scip-integrity-audit","scip-explore","concrete-plan"];function vn(e={}){let t=e.quiet?()=>{}:console.log,n=Ta(import.meta.url),i=it(_t(n),"..","skills"),o=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??Ea(),r=[qe(o,".claude","skills"),qe(o,".codex","skills"),qe(o,".agents","skills")],s={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let a of r){let c=_t(a);if(!bn(c))continue;mp(a,{recursive:!0});let l=ja(a);vp(a,i,l,s,t);for(let d of Ia){let m=qe(i,d),h=qe(a,d);if(!bn(m)){s.skipped.push(`${l}/${d}`);continue}if(bn(h)){try{let p=si(h);if(it(p)===it(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}ai(h)}hp(m,h,bp?"junction":"dir"),s.installed.push(`${l}/${d}`),t(` done: ${d} \u2192 ${l}`)}}return s}function vp(e,t,n,i,o){let r=new Set(Ia);for(let s of ka(e)){if(r.has(s))continue;let a=qe(e,s),c;try{c=it(_t(a),si(a))}catch{continue}Pa(c,t)&&(ai(a),i.pruned.push(`${n}/${s}`),o(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function La(e={}){let t=Ta(import.meta.url),n=it(_t(t),"..","skills"),i=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??Ea(),o=[qe(i,".claude","skills"),qe(i,".codex","skills"),qe(i,".agents","skills")],r={removed:[],left:[],skipped:[]};for(let s of o){if(!bn(s))continue;let a=ja(s);for(let c of ka(s)){let l=qe(s,c),d;try{let m=si(l);d=it(_t(l),m)}catch{r.left.push(`${a}/${c} (not a symlink)`);continue}if(!Pa(d,n)){r.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(r.removed.push(`${a}/${c}`),!e.dryRun)try{ai(l)}catch(m){r.skipped.push(`${a}/${c} (${m instanceof Error?m.message:String(m)})`)}}}return r}function Pa(e,t){let n=gp(it(t),it(e));return n===""||!n.startsWith("..")&&!fp(n)}function ja(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as Gt}from"fs";import{dirname as cl,join as Ti}from"path";import{execFileSync as am}from"child_process";import{createRequire as Sp}from"module";var $p=Sp(import.meta.url);function Na(e,t=[]){let n=wp(),i=Fo(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 wp(){try{return $p.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Wt,spawnSync as Rp}from"child_process";import{existsSync as Le,mkdtempSync as xp,readdirSync as Cp,rmSync as Oa,symlinkSync as kp,writeFileSync as Ep}from"fs";import{tmpdir as Tp}from"os";import{join as ye}from"path";var Ap=3e5,Ip=12,Fa=3e4,li=1024*1024,Lp={readWorkingTreeStatus(e){return Wt("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",timeout:Fa,maxBuffer:li,killSignal:"SIGKILL"})}};function Ba(e,t,n={}){let i=_p(e,n.workingTreeRuntime),o=i.state==="known"?i.files:[],r=Bp(t,i),s=di(e);if(s.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,batches:[]};let a=Op(t,s),c=n.timeoutMs??Ap,l=[],d=new Map,m;try{m=Wa(e,"scip-cleanup-verify-")}catch(h){return{checkers:s.map(p=>p.label),uncoveredFiles:a,baselineErrors:0,workingTree:i,dirtyOverlap:r,dirtyWorkingTree:o,unavailableReason:Gp(h),batches:[]}}try{Vp(e,m.root);for(let h of s)d.set(h.label,Ma(h,m.root,c).rawErrors);for(let h of t.batches){Va(m.root,h);let p=null;for(let g of s){let f=Ma(g,m.root,c),y=Pp(f,d.get(g.label)??[],f.rawErrors);if(y.status==="failed"){let v=y.errors.length>0?y.errors:f.outputTail;p={depth:h.depth,status:"failed",reason:`${g.label}: ${y.reason}`,errors:v.slice(0,Ip)};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 Pp(e,t,n){let i=jp(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 jp(e,t){let n=Np(e),i=new Map,o=[];for(let r of t){let s=_a(r),a=(i.get(s)??0)+1;i.set(s,a),a>(n.get(s)??0)&&o.push(r)}return o}function Np(e){let t=new Map;for(let n of e){let i=_a(n);t.set(i,(t.get(i)??0)+1)}return t}function Op(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 _a(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Da=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],Dp=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function di(e){let t=[];if(Le(ye(e,"tsconfig.json"))){let n=ye(e,"node_modules",".bin","tsc");t.push(Le(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Da,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Da,strength:"reference-aware"})}if(Le(ye(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=>Le(ye(e,n)))){let n=Mp();n&&t.push(n)}if(Dp.some(n=>Le(ye(e,n)))){let n=qp(e);n&&t.push(n)}for(let n of Fp(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:ye(e,n,"..","target")}});return t}function Mp(){return Ve("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"}:Ve("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function qp(e){let t=ye(e,"node_modules",".bin","clj-kondo");return Le(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...en],strength:"reference-aware"}:Ve("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...en],strength:"reference-aware"}:Ve("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...en],strength:"reference-aware"}:null}function Fp(e){let t=[];if(Le(ye(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Cp(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||Le(ye(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function Bp(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 _p(e,t=Lp){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:Wp(n)}}}function Wp(e){let t=e&&typeof e=="object"?e:{};if(t.code==="ETIMEDOUT"||t.killed===!0)return`git status timed out after ${Fa}ms`;if(t.code==="ENOBUFS"||typeof t.message=="string"&&/maxBuffer|stdout.*buffer/i.test(t.message))return`git status exceeded its ${li}-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 Vp(e,t){for(let n of["node_modules"]){let i=ye(e,n),o=ye(t,n);if(Le(i)&&!Le(o))try{kp(i,o,"junction")}catch{}}}function Wa(e,t){let n=xp(ye(Tp(),t)),i=ye(n,"checkout");try{let o=Wt("git",["-C",e,"rev-parse","--verify","HEAD"],{encoding:"utf-8",timeout:3e4,maxBuffer:li,killSignal:"SIGKILL"}).trim();return Wt("git",["clone","--quiet","--no-checkout","--shared","--",e,i],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),Wt("git",["-C",i,"checkout","--quiet","--detach","--force",o],{stdio:"ignore",timeout:3e4,killSignal:"SIGKILL"}),{root:i,dispose(){Oa(n,{recursive:!0,force:!0})}}}catch(o){throw Oa(n,{recursive:!0,force:!0}),o}}function Gp(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 Va(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=ye(e,i);if(!Le(r))continue;let s=ve(r,{maxBytes:rt,inputKind:"cleanup verification source file"});Ep(r,Qp(s,o,{rust:i.endsWith(".rs")}))}}function Up(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 Hp(e,t,n={}){let i=Up(t,n);if(!i.dryRun)for(let o of t)Va(e,o);return i}function Ga(e,t){let n=Wa(e,"scip-cleanup-patch-");try{return Hp(n.root,t),Wt("git",["-C",n.root,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024,timeout:3e4,killSignal:"SIGKILL"})}finally{n.dispose()}}function Ua(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 Ha(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 Qp(e,t,n={}){let i=e.split(`
4
+ `),o=(n.rust===!0?Kp(e):wo(e)).split(`
5
+ `),r=new Set;for(let s of t){let a=zp(i,s.start),c=Yp(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 Kp(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 zp(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 Jp=200;function Yp(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>Jp)break}return n}function Ma(e,t,n){let i=Rp(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:qa(o)};let r=Xp(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(sm),diagnostics:s,parseBasis:r.parseBasis,outputTail:qa(o)}}function Xp(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:Zp(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:em(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=tm(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:nm(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:im(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:om(t),parseBasis:"clj-kondo-json"}:{diagnostics:rm(t),parseBasis:"heuristic"}}function Zp(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 em(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 tm(e){let t=Qa(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 nm(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 im(e){let t=[];for(let n of e.split(`
8
+ `)){if(!n.trim().startsWith("{"))continue;let i=ci(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 om(e){let t=Qa(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 rm(e){return e.split(`
9
+ `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function sm(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 Qa(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return ci(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(i=>i>=0));return Number.isFinite(n)?ci(t.slice(n)):null}function ci(e){try{return JSON.parse(e)}catch{return null}}function qa(e,t=10){return e.split(`
10
+ `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Ja={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"]},cm={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"},lm={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 Fe(e,t){let n=t.languages??pn(e),i=n.map(a=>{let c=rn(hn(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),o=$m(e,n,t),r=pi({semantics:o},"typescript"),s=di(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:i,semantics:o,semantic:r,checkers:s,gitAvailable:xm(e)}}function St(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=>bm(e,c,{hasIndexedGraph:vm(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:dm(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.`},...hm(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 dm(e,t){return va.map(n=>{let i=Jo.flatMap(r=>{let s=r.relations.filter(a=>a.family===n.family);return s.length===0?[]:[um(r,s,e,t)]}),o=ui(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 um(e,t,n,i){let o=n.map(a=>pm(e,t,a,i)),r=ui(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 pm(e,t,n,i){let o=e.requirements.filter(s=>!mm(s,n,i));if(o.length>0)return{language:n.language,status:"unsupported",reason:`Missing ${o.join(", ")}.`};let r=ui(t.map(s=>s.supportCeiling));return{language:n.language,status:r,reason:`${e.label} is available; subtype coverage is ${r}.`}}function mm(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 ui(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 hm(e){return gm(e).map(t=>{let n=pi(e,t),i=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${fm(t)} semantic provider`,status:i,evidence:"semantic",reason:ym(t,n)}})}function gm(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of Xa(e))t.add(n.language);return[...t].sort((n,i)=>Ka(n)-Ka(i))}function Ka(e){return e==="typescript"?0:1}function fm(e){return e==="typescript"?"TypeScript":"Rust"}function ym(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 bm(e,t,n){let i=e.indexers.find(d=>d.language===t),o=i?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",r=o!=="unavailable",s=Sm(t,n.runtimeProbe),a=wm(e,t),c=Rm(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 ${Ja[t].join(", ")} files.`}}}function vm(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function Sm(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)??za(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=Ya(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)??za(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 za(e){let t=cm[e];return t?tn(t):Ya(e)==="regex-only"?"regex":"unavailable"}function Ya(e){let t=lm[e],n=t?xo(t):null;return n?.imports??n?.exports??n?.reExports??null}function $m(e,t,n){let i=[];if(t.includes("typescript")&&i.push({language:"typescript",...Na(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")){let o=Io(e);i.push({language:"rust",available:o.available,dependencyAvailable:o.dependencyAvailable,resolvedBinary:o.resolvedBinary,reason:o.available?o.note:o.reason})}return i}function Xa(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function pi(e,t){return Xa(e).find(n=>n.language===t)}function wm(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=pi(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 Rm(e,t){let n=new Set(Ja[t]);return e.checkers.filter(i=>i.coversExtensions.some(o=>n.has(o)))}function xm(e){try{return am("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{existsSync as lc,lstatSync as km,statSync as Em}from"fs";import{basename as Tm,dirname as Am,isAbsolute as gi,join as Ke,relative as dc,resolve as uc}from"path";import{watch as Im}from"chokidar";import Lm from"ignore";function mi(e){let t=JSON.stringify(e);return Buffer.byteLength(t)<=65536?t:void 0}var pc=5e3,$n=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;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;preferFilesystemGitState=!0;watchGitLayout=null;localCacheWatchPath;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=et(t.config),this.outputDb=t.outputDb??Ke(vo(this.projectRoot,t.config),"index.db"),this.preferFilesystemGitState=t.gitReader===void 0,this.localCacheWatchPath=Jm(this.projectRoot,Am(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??Dm,mc.set(this,Ym(t.stopTimeoutMs??pc,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??Wm(),this.subscriptionFactory=t.subscriptionFactory??Mm,this.budgetInspector=t.budgetInspector??ga,hc.set(this,{gitReader:t.gitReader??go,languages:gc(t.languages??t.config.languages),stagedIndexEntries:null}),this.gitignoreFilter=$s(t.projectRoot),this.extraIgnore=Lm(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,Sn(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();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...Sn(this).closures],o=jm(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=nc(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||!Um(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),Nm(Sn(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(ic(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("../")||ic(i,this.localCacheWatchPath)||this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)||i.endsWith("index.db")||i.endsWith("index.scip")||i.endsWith("index.db.tmp")||Tm(i).startsWith(ma)||(i===".scipquery.json"&&sc(this,this.projectRoot),!ac(this,i)))return;let o=Vm(t);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=gi(t)?t:Ke(this.projectRoot,t);return dc(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t,n,i=!1){this.pendingTrigger=nc(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});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)return;let t=this.inspectBudget(),n=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(),this.stopped)return;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.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),this.onReindexError(l,o),this.onError(l),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===a&&(this.activeOperation=null)})}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 Pm(l,o,this.clock),m=Sn(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,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=Gm(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=dn(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 mi(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&&(pt(this).stagedIndexEntries=cc(this.projectRoot,pt(this).gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}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=pt(this),s=r.stagedIndexEntries,a=cc(this.projectRoot,r.gitReader);r.stagedIndexEntries=a;let c=Xm(this.projectRoot,r.gitReader,t,n,s,a,i,o),l=null;if(c!==null&&(c.includes(".scipquery.json")&&sc(this,this.projectRoot),l=c.filter(m=>ac(this,m)),l.length===0))return;let d=l?.map(m=>({path:m,kind:lc(Ke(this.projectRoot,m))?"change":"delete"}));i&&o?this.scheduleReindex({kind:"watch-git-state",detail:hi("HEAD and index changed",l)},d,d!==void 0):i?this.scheduleReindex({kind:"watch-git-head",detail:hi("HEAD changed",l)},d,d!==void 0):o&&this.scheduleReindex({kind:"watch-git-index",detail:hi(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??Hm(this.projectRoot);if(!t)return null;this.watchGitLayout=t;let n=Qm(t.gitDir);return n?rc(n,t.indexPath):null}readGitStateFromGit(){let t=pt(this).gitReader,n=Hn(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let i=yo(this.projectRoot,n);return rc(Hn(this.projectRoot,["rev-parse","--verify","HEAD"],t),i)}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function Pm(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 ec=new WeakMap,mc=new WeakMap,hc=new WeakMap;function Sn(e){let t=ec.get(e);if(t)return t;let n={closures:new Set,errors:[]};return ec.set(e,n),n}function jm(e){return mc.get(e)??pc}function pt(e){let t=hc.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function Nm(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 Om(e,t=an){let{projectRoot:n,config:i,languages:o,pnpmWorkspaces:r,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:c,indexerConcurrency:l,trigger:d}=e,m=Te(n),h=Object.keys(m).length>0?m:i,p=st(n,h),g=h.indexer?.typescript,f=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:g?.pnpmWorkspaces??r?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:g?.projectMode??s,projects:g?.projects??a??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:f?.configPath??c??"",SCIP_REINDEX_TRIGGER_KIND:d.kind,SCIP_REINDEX_TRIGGER_DETAIL:d.detail??"",SCIP_REINDEX_CHANGE_JOURNAL:e.changeJournal?mi(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 Dm={now:lt,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Mm=(e,t)=>Im(e,t),qm=15*6e4,Fm=1e3,Bm=64*1024;function _m(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function tc(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 Wm(e={}){let t=e.timeoutMs??qm,n=e.terminationGraceMs??Fm,i=e.maxOutputBytes??Bm,o=e.resolveLaunch??Om;return{start(r){let s=o(r),a=new AbortController,c=_m(),l=!1,d=_s({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)throw new Error(tc(new Error(`Reindex worker exited with ${m.signal?`signal ${m.signal}`:`code ${m.status}`}`),c));return m.durationMs}).catch(m=>{throw m instanceof Bs&&(c={stdoutTail:m.stdout,stderrTail:m.stderr,stdoutTruncated:m.stdoutTruncated,stderrTruncated:m.stderrTruncated}),new Error(tc(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 nc(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 Vm(e){if(e==="add")return"add";if(e==="change")return"change";if(e==="unlink")return"delete"}function Gm(e,t){return e?e==="add"?t==="delete"?null:"add":e==="delete"&&t==="add"?"change":t:t}function Um(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}var fi=/^[0-9a-f]{40,64}$/i;function ic(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 Hm(e){let t=Ke(e,".git");try{let n=km(t),i;if(n.isDirectory())i=t;else if(n.isFile()){let o=/^gitdir:\s*(.+)\s*$/m.exec(pe(t,"Git directory marker"));if(!o?.[1])return null;let r=o[1].trim();i=gi(r)?r:uc(e,r)}else return null;return lc(i)?{gitDir:i,indexPath:Ke(i,"index")}:null}catch{return null}}function Qm(e){let t;try{t=pe(Ke(e,"HEAD"),"Git HEAD").trim()}catch{return}if(fi.test(t))return t.toLowerCase();let n=/^ref:\s*(.+)$/.exec(t)?.[1]?.trim();if(!n)return;let i=Km(e);return oc(e,n)??oc(i,n)??zm(i,n)}function Km(e){try{let t=pe(Ke(e,"commondir"),"Git common-directory marker").trim();return t?gi(t)?t:uc(e,t):e}catch{return e}}function oc(e,t){try{let n=pe(Ke(e,t),"Git reference").trim();return fi.test(n)?n.toLowerCase():void 0}catch{return}}function zm(e,t){try{for(let n of pe(Ke(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&&fi.test(o))return o.toLowerCase()}}catch{return}}function rc(e,t){let n={head:e,indexPath:t};try{let i=Em(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}function Jm(e,t){let n=dc(e,t).replaceAll("\\","/");if(!(!n||n===".."||n.startsWith("../")))return n}function Ym(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function gc(e){return e&&e.length>0?[...e]:At}function sc(e,t){try{pt(e).languages=gc(Te(t).languages)}catch{pt(e).languages=At}}function ac(e,t){return po(t,pt(e).languages)!=="other"}function Xm(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 Zm(l.output))c.add(d)}if(a){if(o===null||r===null)return null;for(let l of th(o,r))c.add(l)}return[...c].sort()}function cc(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?eh(n.output):null}function Zm(e){return e.split("\0").filter(t=>t.length>0)}function eh(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 th(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(i=>e.get(i)!==t.get(i))}function hi(e,t){return t===null?`${e}; changed paths unavailable`:t.length===0?e:t.length===1?t[0]:`${t.length} compiler inputs changed`}import{execFileSync as nh}from"child_process";import{existsSync as Rn}from"fs";import{dirname as ih,join as wt}from"path";var fc=["- `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."],wn=[{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 ze="<!-- scip-query:agent-setup:begin -->",$t="<!-- scip-query:agent-setup:end -->",oh="# scip-query:agent-setup",yi=[".codex/hooks.json",".claude/settings.local.json"],yc="# scip-query:local-agent-hooks:begin",bc="# scip-query:local-agent-hooks:end",Rc="hook-architecture-stop";function xc(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 xn(e,t={}){let n={written:[],unchanged:[],skipped:[]};return rh(e,n),t.architectureHook!==!1&&ch(e,n,t.architectureHook),n}function Cc(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Sc(e,"AGENTS.md",t,n),Sc(e,"CLAUDE.md",t,n),lh(e,t,n),ah(e,t,n),n}function rh(e,t){let n=[ze,"## 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.",...fc,"- 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.",$t].join(`
13
+ `);vc(e,"AGENTS.md",n,t);let i=[ze,"@AGENTS.md",$t].join(`
14
+ `);vc(e,"CLAUDE.md",i,t,o=>o.includes("@AGENTS.md")&&!o.includes(ze))}function vc(e,t,n,i,o){let r=wt(e,t),s=!1,a=bi(r,t,i,c=>{if(o?.(c.text))return s=!0,{kind:"unchanged"};let l=sh(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 Sc(e,t,n,i){let o=wt(e,t);if(n.dryRun){if(!Rn(o)){i.unchanged.push(t);return}try{let s=pe(o,"agent instruction file");s.includes(ze)?($c(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=bi(o,t,i,s=>{if(!s.revision.exists||!s.text.includes(ze))return{kind:"unchanged"};let a=$c(s.text);return a.length===0?{kind:"delete"}:{kind:"write",text:a}});r&&(r.changed?i.removed.push(t):i.unchanged.push(t))}function sh(e,t){if(kc(e)==="present"){let i=new RegExp(`${ze}[\\s\\S]*?${$t}`);return e.replace(i,t)}return e.length>0?`${e.replace(/\n*$/,`
15
+
16
+ `)}${t}
17
+ `:`${t}
18
+ `}function $c(e){kc(e);let t=new RegExp(`${ze}[\\s\\S]*?${$t}`),n=e.replace(t,"").replace(/\n{3,}/g,`
19
+
20
+ `).trim();return n.length===0?"":`${n}
21
+ `}function kc(e){let t=e.split(ze).length-1,n=e.split($t).length-1;if(t===0&&n===0)return"absent";if(t===1&&n===1&&e.indexOf(ze)<e.indexOf($t))return"present";throw new Error("managed scip-query markers are incomplete, duplicated, or out of order")}function bi(e,t,n,i){try{return yt(e,i,{maxRetries:0})}catch(o){n.skipped.push({target:t,reason:o instanceof Error?o.message:String(o)});return}}function ah(e,t,n){let i=".git/hooks/pre-commit",o=wt(e,i);if(!Rn(o)){n.unchanged.push(i);return}if(!pe(o,"pre-commit hook").includes(oh)){n.skipped.push({target:i,reason:"pre-commit hook is not managed by scip-query"});return}if(t.dryRun){n.removed.push(i);return}bi(o,i,n,()=>({kind:"delete"}))?.changed&&n.removed.push(i)}function ch(e,t,n={}){let i=(n.inspectReadiness??dh)(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 yi){if(Lc(e,r)){t.skipped.push({target:r,reason:"tracked repository config; the checkout-local hook installer will not modify it"});continue}Ac(wt(e,r),r,t,s=>uh(s,o))}hh(e,t)}function lh(e,t={},n){for(let i of yi){let o=wt(e,i);if(Rn(o)){if(Lc(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=mh(o);JSON.stringify(wc(r))!==JSON.stringify(r)&&n.removed.push(i)}catch(r){n.skipped.push({target:i,reason:Cn(r)})}continue}Ac(o,i,n,wc,!0)}}}function dh(e){let t=Te(e);if(!t.architecture||t.architecture.boundaries.length===0)return{state:"not-configured"};let n=st(e,t),i=Ue(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=Fs(e);let r=dt(ft(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:Cn(r)}}finally{o?.close()}}function uh(e,t="scip-query"){let n=Ec(e.hooks),i=Array.isArray(n.Stop)?n.Stop:[];return{...e,hooks:{...n,Stop:[...Tc(i),{hooks:[{type:"command",command:`${t} ${Rc}`,timeout:120,statusMessage:"Checking architecture boundaries"}]}]}}}function wc(e){let t=Ec(e.hooks),n=Array.isArray(t.Stop)?t.Stop:[],i=Tc(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 Ec(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Tc(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!ph(n)):[]})).filter(t=>t.hooks.length>0)}function ph(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&new RegExp(`(?:^|\\s)${Rc}$`,"u").test(t)}function Ac(e,t,n,i,o=!1){try{yt(e,s=>{let a=s.revision.exists?Ic(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:Cn(r)})}}function mh(e){return Ic(pe(e,"agent hook settings"),e)}function Ic(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 Lc(e,t){try{return nh("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore",timeout:5e3,killSignal:"SIGKILL"}),!0}catch{return!1}}function hh(e,t){let n=wt(e,".git","info","exclude");if(!Rn(ih(n))){t.skipped.push({target:".git/info/exclude",reason:"Git metadata was not found; local hook files may appear as untracked"});return}try{yt(n,i=>{let o=new RegExp(`${yc}[\\s\\S]*?${bc}\\n?`,"gu"),r=i.text.replace(o,"").replace(/\n*$/u,""),s=[yc,...yi.map(c=>`/${c}`),bc].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:Cn(i)})}}function Cn(e){return e instanceof Error?e.message:String(e)}import{existsSync as Bh}from"fs";import{existsSync as gh,mkdirSync as fh,writeFileSync as yh}from"fs";import{homedir as bh}from"os";import{dirname as vh,isAbsolute as Sh,join as vi,relative as Pc,resolve as $h}from"path";function jc(e,t={}){let n=t.dossierDir?$h(e.projectRoot,t.dossierDir):vi(e.projectRoot,"docs","scip-query"),i={markdownPath:vi(n,"health-dossier.md"),jsonPath:vi(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},o=Ih({...e,generatedAt:new Date().toISOString(),healthDossier:i},e.projectRoot);try{return Eh(i.markdownPath,wh(o),i),Th(i.jsonPath,o,i),i}catch(r){return{...i,status:"failed",error:r instanceof Error?r.message:String(r)}}}function wh(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${$i(e.health)}`,"","## Items That Need Attention","",...Rh(e),"","## Blocked Or Unavailable Checks","",...xh(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","",...Ch(e),"","## JSON","",`Machine-readable report: \`${kh(e)}\``,""].join(`
27
+ `)}`}function Rh(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 xh(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 Ch(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 $i(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function kh(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Eh(e,t,n){Nc(e,t,n,"health dossier Markdown",i=>i===t)}function Th(e,t,n){let i=`${JSON.stringify(t,null,2)}
28
+ `;Nc(e,i,n,"health dossier JSON",o=>Ah(o,i))}function Nc(e,t,n,i,o){fh(vh(e),{recursive:!0});let r=gh(e)?pe(e,i):null;if(r!==null&&o(r)){n.unchanged.push(e);return}yh(e,t),n.written.push(e)}function Ah(e,t){try{let n=JSON.parse(e),i=JSON.parse(t);return delete n.generatedAt,delete i.generatedAt,JSON.stringify(n)===JSON.stringify(i)}catch{return e===t}}function Ih(e,t){return Si(e,t)}function Si(e,t){return typeof e=="string"?Lh(e,t):Array.isArray(e)?e.map(n=>Si(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,i])=>[n,Si(i,t)])):e}function Lh(e,t){if(e===t)return".";if(!Sh(e))return e;let n=Pc(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let i=Pc(bh(),e).replace(/\\/g,"/");return i&&!i.startsWith("..")?`~/${i}`:e}return n}import{spawnSync as Ph}from"child_process";import{dirname as Oc,join as jh,resolve as Nh}from"path";import{fileURLToPath as Oh}from"url";var kn={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 Dh(e,t){let n=new Set(["tree-sitter"]);for(let i of e)for(let o of kn[i]?.packages??[])n.add(o);return[...n].filter(i=>t[i]).sort().map(i=>`${i}@${t[i]}`)}function wi(e){return[...new Set(e.filter(t=>kn[t]!==void 0))].sort()}function Dc(e,t={}){let n=t.runtime??Fh,i=t.packageRoot??Mh(),o=wi(e),r=o.filter(m=>n.probe(kn[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=qh(i),c=Dh(s,a),l=n.install(i,c);l.ok&&n.resetProbe();let d=o.filter(m=>n.probe(kn[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 Mh(){let e=Oc(Oh(import.meta.url));for(;;){let t=jh(e,"package.json");try{if(JSON.parse(pe(t,"AST parser package manifest")).name==="scip-query")return e}catch{}let n=Oc(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function qh(e){return JSON.parse(pe(Nh(e,"package.json"),"AST parser package manifest")).optionalDependencies??{}}var Fh={probe:e=>tn(e)==="ast",resetProbe:Ro,install:(e,t)=>{let n=Ph(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 Mc(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 qc(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 Fc(e={}){let t=[],n=Ae(),{projectRoot:i,paths:o,dbPath:r}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,c=ut(n.config,{projectRoot:i}).filter(B=>B.level==="error"),l=null,d=null;if(c.length===0&&!n.config.collaborationDomainId)try{l=Cs(i,n.config)}catch(B){d=Rt(B)}let m=l?.config??n.config,h=e.languages?ks(i,m,e.languages):null,p=h?.config??m,g=ut(p,{projectRoot:i}),f=g.filter(B=>B.level==="error"),y=null,v=null;if(f.length===0&&p.watch?.enabled!==s)try{y=Es(i,p,s)}catch(B){v=Rt(B)}let R=y?.config??p,N=Bt();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":f.length>0||!s?"skipped":"ok",message:v??(f.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]}:{}}),G(t,{id:"scip-cli",label:"scip CLI",status:N?"ok":"warn",message:N?"scip CLI is available.":"scip CLI is not available; installation requires explicit --install-missing consent."});let F=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:vn({quiet:!0});G(t,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":F.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${F.installed.length} installed, ${F.alreadyLinked.length} already linked, ${F.pruned.length} pruned, ${F.skipped.length} skipped.`,details:[...F.pruned.map(B=>`Pruned ${B}`),...F.skipped.map(B=>`Skipped ${B}`)]});let H=y?ut(R,{projectRoot:i}):g,L=H.filter(B=>B.level==="error");G(t,{id:"config",label:"Project config",status:L.length>0?"failed":H.length>0?"warn":"ok",message:H.length===0?"Config OK.":`${H.length} diagnostic(s), ${L.length} error(s).`,details:H.map(B=>`${B.level.toUpperCase()} ${B.path}: ${B.message}`)});let q=Fe(i,R);G(t,{id:"readiness",label:"Indexer readiness",status:q.languages.length===0?"failed":q.indexers.some(B=>!B.runnable)?"warn":"ok",message:q.languages.length===0?"No supported project languages detected.":`Detected languages: ${q.languages.join(", ")}`,details:q.indexers.map(B=>`${B.runnable?"OK":B.installed?"WARN":"MISSING"} ${B.language}: ${B.binaryLabel}${B.note?` - ${B.note}`:""}`)});let E=e.installAstParsers!==!0?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:Dc(q.languages);G(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers!==!0?"skipped":E.unavailable.length>0?"warn":"ok",message:e.installAstParsers!==!0?"Skipped because installing missing parser packages requires explicit consent.":E.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${E.availableAfter.length}/${E.supportedLanguages.length} selected language parser(s) available${E.installed.length>0?`; installed ${E.installed.join(", ")}`:""}.`,details:[...E.unavailable.length>0?[`Unavailable: ${E.unavailable.join(", ")}`]:[],...E.error?[E.error]:[]]});let T=e.installIndexers===!0,V=T?Zh(i,q,t):[];T||G(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because installing missing indexers requires explicit consent."});let M=Fe(i,R),te=await _h({projectRoot:i,paths:o,config:R,readiness:M,configHasErrors:L.length>0,steps:t,onStatus:e.onStatus,installMissing:e.installIndexers===!0}),Gn=te.reindexResult,up=te.freshness,ao=et(R),co=Wh({projectRoot:i,cacheDir:o.cacheDir,watchConfig:ao,readiness:M,configHasErrors:L.length>0,reindexResult:Gn,postReindexFreshness:up,steps:t}),Ze=Fe(i,R),Jt=St(Ze),lo=Ue(i,R,o);G(t,{id:"capabilities",label:"Capability matrix",status:rg(Jt),message:sg(Jt)}),e.onStatus?.(e.runHealth===!0?"Running optional full health audit\u2026":"Skipping optional full health audit.");let uo=e.runHealth===!0?await tg(o.dbPath,t):ng(t),je=Ze.languages.includes("rust")?ln(i,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;G(t,{id:"rust-semantic-session",label:"Rust semantic session",status:je===null?"skipped":je.valid?"ok":"failed",message:je===null?"Skipped because Rust was not detected.":`${je.transport}/${je.state} selected from ${je.source}; ${je.fallback} fallback; opt out with ${je.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=xn(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(B=>`Skipped ${B.target}: ${B.reason}`)}))}catch(B){G(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Rt(B)})}let Yt=Vh({reindexResult:Gn,readiness:Ze,capabilities:Jt,freshness:lo,health:uo,healthSelected:e.runHealth===!0,agentResult:Ne,watchConfig:ao,watchService:co,rustSemanticSession:je,steps:t});G(t,{id:"smoke-tests",label:"Setup smoke tests",status:Gh(Yt),message:Uh(Yt),details:Yt.map(B=>`${B.command}: ${B.status} - ${B.evidence}`)});let pp={repository:[...h?.changed?[h.configPath]:[],...y?.changed?[y.configPath]:[],...Ne?.written??[]],checkout:[],user:[...F.installed,...E.installed,...V.filter(B=>B.attempted).map(B=>`${B.binaryLabel} installer`)]},_e={projectRoot:i,dbPath:r,configuredDbPath:o.dbPath,scipCliInstalled:N,languages:Ze.languages,steps:t,skills:F,astParsers:E,initialReadiness:q,indexerRemediation:V,readiness:Ze,capabilities:Jt,freshness:lo,reindex:Gn,automaticRefreshConfig:y,watchService:co,rustSemanticSession:je,health:uo,smokeTests:Yt,healthDossier:null,setupAgent:Ne,changeScopes:pp,filesWritten:Ne?.written??[],verdict:xi(t,Ze)};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."}),_e.verdict=xi(t,Ze),_e;let Oe=jc(_e,{dossierDir:e.dossierDir});return _e.healthDossier=Oe,_e.changeScopes.repository.push(...Oe.written),_e.filesWritten=[..._e.filesWritten,...Oe.written],G(t,{id:"health-dossier",label:"Health dossier",status:Oe.status==="failed"?"failed":"ok",message:Oe.status==="failed"?Oe.error:`${Oe.written.length} written, ${Oe.unchanged.length} unchanged.`,details:[Oe.markdownPath,Oe.jsonPath]}),_e.verdict=xi(t,Ze),_e}async function _h(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 ba({projectRoot:e.projectRoot,languages:e.readiness.languages,outputScip:e.paths.indexPath,outputDb:e.paths.dbPath,pnpmWorkspaces:e.config.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.config.indexer?.typescript?.projectMode,typescriptProjects:e.config.indexer?.typescript?.projects,clojureConfigPath:e.config.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,installMissing:e.installMissing,indexerConcurrency:e.config.indexerConcurrency,trigger:{kind:"setup",detail:"scip-query setup"},onStatus:a=>{t.push(a),e.onStatus?.(a)}}),o+=n.durationMs,r||=!n.reused,i=Ue(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:Rt(o),details:t})}return{reindexResult:n,freshness:i}}function Wh(e){let t=e.readiness.languages.length===0?"Skipped because no supported languages were detected.":e.configHasErrors?"Skipped because config validation has errors.":e.watchConfig.enabled?e.reindexResult===null||e.reindexResult.skipped.length>0||e.postReindexFreshness?.state!=="fresh"?"Skipped because the initial refresh did not produce a complete fresh generation.":null:"Disabled by watch.enabled=false; setup left the explicit opt-out unchanged.";if(t!==null)return G(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=gn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:We,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:Rt(n)}),null}}function Bc(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${$i(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:"),Ri("Repository records (commit)",e.changeScopes.repository),Ri("Checkout preferences (do not commit)",e.changeScopes.checkout),Ri("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 Ri(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function Vh(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:Hh(e.steps),evidence:Qh(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?Kh(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:zh(e.readiness,e.freshness),evidence:Jh(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:Yh(e.capabilities),evidence:Xh(e.capabilities)},{id:"watch-refresh",command:"scip-query status --json",status:i?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",evidence:i?.message??"Watch refresh policy was not evaluated."},{id:"rust-semantic-session",command:"scip-query status --json",status:e.rustSemanticSession===null?"unavailable":e.rustSemanticSession.valid?"pass":"fail",evidence:e.rustSemanticSession===null?"Rust was not detected.":`${e.rustSemanticSession.transport}/${e.rustSemanticSession.state}; ${e.rustSemanticSession.fallback} fallback; ${e.rustSemanticSession.optOut}.`},{id:"setup-agent",command:"scip-query setup-agent",status:e.agentResult?"pass":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 Gh(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable"&&t.optional!==!0)?"warn":"ok"}function Uh(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 Hh(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Qh(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function Kh(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 zh(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function Jh(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 Yh(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function Xh(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 Zh(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=hn(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=fa(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=eg(rn(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 eg(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function tg(e,t){if(!Bh(e)){let n="Skipped because no SQLite index database exists yet.";return G(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Ci(n)}try{let n=await Us({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).`}),ig(n)}catch(n){let i=Rt(n);return G(t,{id:"health",label:"Health audit",status:"failed",message:i}),Ci(i)}}function ng(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}),Ci(t)}function ig(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(og),warnings:e.warnings??[]}}function og(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 Ci(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function xi(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 rg(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 sg(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 Rt(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as ag}from"readline";function cg(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function lg(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 _c(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let i=cg(e);ag(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
29
+ `),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
30
+
31
+ `),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
32
+ `)}),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(`
33
+ `),s(i.selected);return}let h=m.name==="up"?"up":m.name==="down"?"down":m.name==="space"?"toggle":null;h&&(i=lg(i,h,e),r())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!o),t.pause()}}import{existsSync as dg}from"fs";import{join as ki}from"path";function Wc(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 Ei(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 Vc(e){let t=Ei(e);if(!t.ok)throw new Error(t.message);let n={dryRun:e.dryRun===!0};return t.global&&(n.global=La({dryRun:e.dryRun,homeDir:e.homeDir})),t.project&&(n.project=ug(e.projectRoot,{dryRun:e.dryRun})),n}function ug(e,t={}){return{agentSetup:Cc(e,{dryRun:t.dryRun}),left:pg(e)}}function pg(e){return[[".scipquery.json",ki(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",ki(e,".scipquery","suppressions")],["docs/scip-query/",ki(e,"docs","scip-query")]].filter(([,t])=>dg(t)).map(([t])=>t)}import{existsSync as Gc,lstatSync as mg,readdirSync as hg}from"fs";import{join as Uc}from"path";function Kc(e={}){let t=Uc(e.cacheRoot??So(),"projects"),n={projectsDirectory:t,scannedCacheDirs:0,ownedCacheDirs:0,retainedRoots:0,orphanedRoots:0,stoppedServices:0,alreadyStoppedServices:0,skipped:[],failures:[]};if(!Hc(t))return n;let i=e.rootIsCurrent??Hc,o=e.stopService??fn;for(let r of hg(t,{withFileTypes:!0}).sort((s,a)=>s.name.localeCompare(a.name))){let s=Uc(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=$o(s).record.canonicalProjectRoot,n.ownedCacheDirs+=1}catch(c){n.skipped.push({cacheDir:s,message:Qc(c)});continue}if(i(a)){n.retainedRoots+=1;continue}try{if(gg(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:Qc(c)})}}return n}function gg(e,t){let n=Mo(e),i=qo(n.statePath),o=Ra(n.lockPath);if(Gc(n.statePath)&&!i)throw new Error("watch state exists but is not a valid ownership record");if(Gc(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&&!sn(i.processIdentity,o.processIdentity))throw new Error("watch state and lock name different process identities")}function Hc(e){try{let t=mg(e);return t.isDirectory()&&!t.isSymbolicLink()}catch(t){let n=t.code;if(n==="ENOENT"||n==="ENOTDIR")return!1;throw t}}function Qc(e){return e instanceof Error?e.message:String(e)}var zc={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 Jc(e,t){let n=fg(t);return{...e,warnings:[...e.warnings??[],zc.note,...n],capabilities:t,scoreInterpretation:zc}}function fg(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 yg}from"crypto";import{basename as bg,join as vg}from"path";function el(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 Vt=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 tl(e,t,n,i,o){if(!Un.includes(t))throw new Error(`unsupported suppression reason code ${JSON.stringify(t)}; expected one of ${Un.join(", ")}`);if(n.length===0)throw new Error("automatic suppression requires at least one --evidence <kind:referent>");let r=n.map(s=>Cg(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 nl(e,t,n={}){let i=n instanceof Date?{now:n}:n,o=$g(t),r=wg(i.expectedRevision),s=vg(Ns(e),Os(o)),a=i.now??new Date,c="unchanged",l=yt(s,d=>{if(!d.revision.exists){if(r)throw new Vt(`Cannot replace ${s}: the observed suppression no longer exists.`,s);return c="created",{kind:"write",text:Zc(Yc(o,void 0,a,i.toolVersion))}}let m=Sg(d);if(Rg(m.suppression,o))return c="unchanged",{kind:"unchanged"};if(!r)throw new Vt(`A different suppression decision already exists at ${s}.`,s,d.revision.hash);if(r!==d.revision.hash)throw new Vt(`Suppression ${s} changed after the revision you reviewed.`,s,d.revision.hash);return c="replaced",{kind:"write",text:Zc(Yc(o,m.suppression,a,i.toolVersion))}},{maxRetries:0,onBeforeCommit:i.onBeforeCommit});return{path:s,disposition:c,revision:l.current.revision.hash}}function Sg(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=Ms(t,xg(e.path));if("error"in n)throw new Error(`Cannot update ${e.path}: ${n.error}.`);return n}function Yc(e,t,n,i=We){let o=n.toISOString(),{decision:r,createdAt:s,...a}=e,c={kind:Ls,suppressionIdentity:Ds(e),writer:{tool:"scip-query",version:i},...a,createdAt:t?.createdAt??s??o,...t?{updatedAt:o}:{}};return r?{...c,schemaVersion:js,decision:r}:{...c,schemaVersion:Ps}}function $g(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&&!Rs(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 wg(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 Rg(e,t){return JSON.stringify(Xc(e))===JSON.stringify(Xc(t))}function Xc(e){let{createdAt:t,...n}=e;return n}function xg(e){let t=bg(e);return t.endsWith(".json")?t.slice(0,-5):t}function Zc(e){return`${JSON.stringify(e,null,2)}
34
+ `}function Cg(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=ho(r),a=at(e,s);return{kind:o,referent:s,claim:n,contentHash:yg("sha256").update(a).digest("hex")}}import{execFileSync as kg}from"child_process";var Eg={changedPaths:Ag,indexedPaths:e=>mo(e,{includeIgnored:!1}),architectureFindings:e=>dt(ft(e))},Tg=/\.(?:[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 ol(e,t,n=Eg){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)||Tg.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):
35
+ ${s.map(a=>`- ${a}`).join(`
36
+ `)}
37
+
38
+ Inspect the boundary graph with: scip-query architecture`}}function rl(e){return e.kind==="block"?{decision:"block",reason:e.reason}:{}}function Ag(e){let t=il(e,["diff","--name-only","--diff-filter=ACMRTUXB","HEAD","--"]),n=il(e,["ls-files","--others","--exclude-standard","--"]);return[...new Set([...t,...n])].sort()}function il(e,t){try{return kg("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: ${Ig(n)}`,{cause:n})}}function Ig(e){return e instanceof Error?e.message:String(e)}var Lg=new Set(At),ll=Y(({db:e})=>{try{let t=ol(ce(),e);process.stdout.write(`${JSON.stringify(rl(t))}
39
+ `)}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})}
40
+ `)}});function Pg(e){return e.filter(t=>Lg.has(t))}async function dl(e){let t=de(e),n=ce(),i=Te(n),o=st(n,i),r=b(t,"json");try{let s=Pg(O(t,"language")),a=await Ca(n,i,o,{languages:s.length>0?s:i.languages,force:b(t,"force"),allowPartial:b(t,"allowPartial"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",installMissing:b(t,"installMissing"),trustProjectTools:b(t,"trustProjectTools"),indexerConcurrency:K(t,"indexerConcurrency")??i.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...r?{onStatus:()=>{}}:{onStatus:console.log}});if(r){I("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 ul(){let e=ce(),t=Xn(e);try{let n=da({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 pl(e){let t=de(e),n=ce(),i=Xn(n);try{let o=await ya({projectRoot:n,dbPath:i,tsconfig:$(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 ml(e){let t=de(e);Ce(n=>{let i=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),o=Fr(n,{base:$(t,"base")}),r=Br(n,i,o.changedFiles,o.changedRanges);ei(Ot,r)})}async function hl(e){let t=de(e);try{let n=await Ks({base:$(t,"base")});if(b(t,"json")){I("diff-impact",[],t,n.result,{observationReceipt:n.observationReceipt});return}zs(n.result)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function gl(e,t){let n=de(t),i=String(e).split(",").filter(o=>o.length>0);Ce(o=>{let r=[];for(let c of i)ps.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),r.push(c);let s={scope:$(n,"scope"),full:b(n,"full")},a=r.length===1?ms(o,r[0],s):hs(o,r,s);ei(Nt,a)})}async function fl(e){let t=de(e);if(b(t,"writeBaseline")||b(t,"baseline")){jg(t);return}try{let n=await Hs({scope:$(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:i,config:o,dbPath:r}=Ae(),s=St(Fe(i,o),{hasIndexedGraph:Gt(r)}),a=Jc(n.result,s);if(b(t,"json")){I("health",[],t,a,{observationReceipt:n.observationReceipt});return}Qs(a)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function jg(e){let t=$(e,"scope");Ce(n=>{if(b(e,"writeBaseline")){let o=cs(n,{scope:t});console.log(`Baseline written to ${o.path} (${o.findingCount} finding(s)).`);return}let i=ls(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 yl(){let e=vn(),t=e.installed.length+e.alreadyLinked.length;console.log(`
41
+ ${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 bl(){let e=!1;Bt()?console.log("scip CLI: installed"):(ri(),e=!0);let t=ce(),n=Te(t),i=Fe(t,n);if(i.languages.length===0){console.log(`
42
+ No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
43
+ Detected languages: ${i.languages.join(", ")}`),console.log(`
44
+ 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=jl(i);o.length>0&&console.log(`
45
+ Semantic provider readiness:`);for(let r of o){let s=r.available?" OK":r.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${r.language}: ${Hg(r)}${Nl(r)}`),r.reason&&console.log(` ${r.reason}`)}process.exitCode=e?1:0}function vl(e){Ng(e)}function Ng(e){let t=de(e),{projectRoot:n,config:i,paths:o,dbPath:r}=Ae(),s=Fe(n,i),a=Ue(n,i,o),c=St(s,{hasIndexedGraph:Gt(r)&&a.state!=="missing"});if(b(t,"json")){I("capabilities",[],t,{...c,explorationControls:wn,relationshipQuestions:yn(),unavailableRelationshipFrontiers:un});return}Yg(c,{matrix:b(t,"matrix")})}function Sl(){let e=ce(),t=pn(e),n=xs(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 $l(e){let t=de(e),n=ce(),i=Te(n),o=qs(n),r=[...ut(i,{projectRoot:n}),...o.compatibility.issues.map(s=>({level:"error",path:s.path,message:s.reason}))];if(b(t,"json"))I("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 wl(e,t){let n=de(t),i=$(n,"reason");if(!i||i.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}let o=$(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=ce(),a=(()=>{try{return Ce(()=>Vs())}catch{return}})(),c={id:String(e),check:$(n,"check"),file:$(n,"file"),reason:i,expiresAt:$(n,"expiresAt"),decision:tl(s,o,r,i,a)},l=nl(s,c,{expectedRevision:$(n,"replace")});if(b(n,"json")){I("suppress",[String(e)],n,l);return}for(let d of el(l,c))console.log(d)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exitCode=1}}function Rl(e){let t=de(e),{report:n,hasIndexerProblems:i,hasErrors:o}=xl("doctor");b(t,"json")?I("doctor",[],t,n):_g(n,i),process.exitCode=o?1:0}function xl(e){let{projectRoot:t,config:n,paths:i,dbPath:o}=Ae(),r=ut(n,{projectRoot:t}),s=Fe(t,n),a=Ue(t,n,i),c=Gt(o),l=St(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=xa(t,n,i),m=s.indexers.some(g=>!g.runnable),h=r.some(g=>g.level==="error")||m||a.state==="missing"||a.state==="stale",p=r.some(g=>g.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 Cl(e){de(e);let t=ce(),n=xn(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=xc(n);i.verdict==="ready"?console.log(`
46
+ Project agent guidance is configured for every selected target.`):i.verdict==="partial"?console.log(`
47
+ 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(`
48
+ 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 kl(e){let t=de(e);try{let n=b(t,"guided"),i=b(t,"yes"),o=b(t,"json");Mc({guided:n,yes:i,json:o,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0});let r=b(t,"installMissing"),s={dossierDir:$(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 Og(s,{json:o})),o||(s.onStatus=l=>console.log(` ${l}`));let c=await Fc(s);o?I("setup",[],t,c):Bc(c),process.exitCode=c.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Og(e,t){let{projectRoot:n,config:i}=Ae(),o=Fe(n,i),r=qc({files:Dg(n),watchEnabled:et(i).enabled,readiness:o}),s=o.languages.map(g=>({id:`language:${g}`,scope:"project",label:`Index ${g}`,reason:"Detected in this project.",selected:!0})),a=r.actions.map(g=>({id:g.id,scope:g.scope==="repository"?"project":g.scope,label:g.label,reason:g.reason,selected:g.recommended})),c=wi(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 _c([...s,...a]):new Set([...Mg(r.actions),...s.map(g=>g.id),...e.runHealth===!0?["run-health-analysis"]:[]]);l&&qg(r.actions,d);let m=d.has("create-agent-guidance")||d.has("update-agent-guidance"),h=r.actions.some(g=>g.id==="enable-automatic-refresh"),p=r.actions.some(g=>g.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(g=>d.has(`language:${g}`)),installSkills:d.has("install-agent-skills"),installAstParsers:l?d.has("install-ast-parsers"):e.installAstParsers===!0,runHealth:d.has("run-health-analysis")}}function Dg(e){return{agentsMd:Gt(Ti(e,"AGENTS.md")),claudeMd:Gt(Ti(e,"CLAUDE.md"))}}function Mg(e){return new Set([...e.filter(t=>t.recommended&&t.id!=="install-indexers").map(t=>t.id),"install-agent-skills"])}function qg(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 El(e){let t=de(e),n=Ei({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=Vc({projectRoot:ce(),global:n.global,project:n.project,dryRun:b(t,"dryRun")});if(b(t,"json")){I("uninstall",[],t,i);return}for(let o of Wc(i,{verbose:b(t,"verbose")}))console.log(o)}function Tl(e){let t=de(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(([,T])=>T!==void 0);if((a||c||l)&&p.length>0){console.error(`error: timing options (${p.map(([T])=>T).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 g=[["--debounce",n,!1],["--cooldown",i,!0],["--git-poll",o,!1],["--idle-timeout",r,!0]].find(([,T,V])=>T!==void 0&&(!Number.isInteger(T)||(V?Number(T)<0:Number(T)<=0)));if(g){console.error(`error: ${g[0]} requires ${g[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}if(l){Fg(t,d);return}let f=ce(),y=Te(f),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 R=et(y);y.watch=R;let N=st(f,y),F={projectRoot:f,cacheDir:N.cacheDir,cliVersion:We,watchOverrides:v};if(a){let T=Al(vt(F),R.enabled);d?I("watch",[],t,T):Il(T);return}if(c){try{let T=fn(F);d?I("watch",[],t,T):console.log(T.disposition==="stopped"?`Stopped watch service${T.pid?` (pid ${T.pid})`:""}.`:"Watch service is already stopped.")}catch(T){console.error(`error: ${T instanceof Error?T.message:String(T)}`),process.exitCode=1}return}if(!R.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 V=vt(F);if(V.classification.kind==="live")throw new Error(`watch service pid ${V.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 T=gn(F);d?I("watch",[],t,T):(console.log(`${T.disposition==="started"?"Started":"Reused"} watch service for ${f} (pid ${T.state.pid}).`),p.length>0&&console.log(`Process-local timing overrides: ${p.map(([V,M])=>`${V}=${M}`).join(", ")}. These were not written to .scipquery.json.`))}catch(T){console.error(`error: ${T instanceof Error?T.message:String(T)}`),process.exitCode=1}return}let H=wa(Ti(cl(N.dbPath),Do),f);if(!H.acquired){console.error(H.message),process.exitCode=1;return}let L=new $n({projectRoot:f,config:y,outputDb:N.dbPath,languages:y.languages,onStatus:T=>{process.stdout.write(`\r\x1B[K${Ws(Zn(T))}`)},onReindexComplete:(T,V,M)=>(console.log(`
49
+ Reindex complete in ${(T/1e3).toFixed(1)}s`),(M?.pendingChanges!==!1?Ue(f,y,N):Is(N)).state==="fresh"),onRefreshSuppressed:T=>{let V=ha(N.dbPath,T);V.state==="failed"&&console.error(`
50
+ Watch warning: suppressed-refresh telemetry was not recorded: ${V.reason}`),console.log(`
51
+ Skipped redundant refresh; the completed index already includes the queued changes.`)},onError:T=>{console.error(`
52
+ Watch error: ${T.message}`)}});console.log(`Watching ${f}`),console.log(`Debounce: ${R.debounceMs}ms | Cooldown: ${R.cooldownMs}ms | Git poll: ${R.gitPollMs}ms`),console.log(`Press Ctrl+C to stop.
53
+ `),L.start();let q=!1,E=()=>{q||(q=!0,L.stop().then(T=>{if(T.state==="degraded"){q=!1,console.error(`
54
+ Unable to stop safely: ${T.reasons.join("; ")}`);return}H.release(),console.log(`
55
+ Stopped.`),process.exit(0)}))};process.on("SIGINT",E),process.on("SIGTERM",E)}function Fg(e,t){try{let n=Kc();if(t)I("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 Al(e,t=!0){let{classification:n}=e,i=Sa(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 Bg(n)}}function Il(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`),sl(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: ${Zn(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, ${se(n.estimatedWriteBytes??n.estimatedLogicalOutputBytes)} estimated writes (${se(n.estimatedLogicalOutputBytes)} logical output)${n.confidence&&n.confidence!=="complete"?` [${n.confidence} evidence]`:""}`),(n.reflinkedBytes!==void 0||n.fallbackCopiedBytes!==void 0)&&console.log(`Reindex staging: ${se(n.reflinkedBytes??0)} reflinked, ${se(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), ${se(o.producedOutputBytes)} produced, ${Kg(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&&sl(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: ${se(n.heapUsedBytes)}${n.heapLimitBytes===void 0?"":` / ${se(n.heapLimitBytes)} heap`}${n.softMemoryLimitBytes===void 0?"":`; ${se(n.softMemoryLimitBytes)} retirement mark`}${n.retireRequested?"; retirement requested":""}`)}}function sl(e){console.log(`Refresh requests: ${e.pending} pending, ${e.claimed} claimed, ${e.completed} completed, ${e.expired} expired${e.invalid>0?`, ${e.invalid} invalid`:""}`)}function Bg(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function Ll(e){let t=de(e),{report:n}=xl("status"),i=et(Te(n.projectRoot)).enabled,o=Al(vt({projectRoot:n.projectRoot,cacheDir:cl(n.configuredDbPath),cliVersion:We}),i),r=ua(n.dbPath),s=As(n.dbPath,n.freshness.metaPath),a=Ts(n.dbPath),c=ln(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(b(t,"json")){I("status",[],t,{...n,affectedSetShadow:r,sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:o,stats:zg(n.exists)});return}Wg(n,{affectedSetShadow:r,capabilities:b(t,"capabilities"),sqliteGeneration:s,localGenerations:a,rustSemanticSession:c,watchService:o})}function _g(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})`:""}`),Pl(e.capabilities)}function Wg(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 jl(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}${Nl(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: ${Qg(e.freshness.lastRefresh)}`),Il(t.watchService),Vg(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"),Gg(t.sqliteGeneration),Ug(t.localGenerations),console.log(`Shadow: ${pa(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),Jg(e.exists),t.capabilities&&(console.log(""),Pl(e.capabilities),console.log("Run `scip-query capabilities` for the semantic control manual."))}function Pl(e){let t=al(e.capabilities),n=al(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 al(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 Vg(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), ${se(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${se(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), ${se(e.cleanup.deletedBytes??0)} removed`)}function Gg(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 Ug(e){e.state!=="absent"&&(console.log(`Local GC: ${e.state}, ${e.generationCount} generation(s), ${se(e.logicalBytes)}, ${e.protectedGenerations} protected (${e.activeReaderLeases} live reader lease(s)); limits ${e.limits.maxGenerations} / ${se(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 jl(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function Hg(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function Nl(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function Qg(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 Kg(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(1)} s`}function zg(e){if(e)return Ce(t=>{let n=Lt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function Jg(e){e&&Ce(t=>{let n=Lt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${se(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function Yg(e,t={}){console.log(`Exploration capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`),console.log(`
56
+ Primary controls:`);for(let n of wn)console.log(` ${n.stage.toUpperCase().padEnd(8)} scip-query ${n.command} [${n.outputCost}] \u2014 ${n.question}`);console.log(`
57
+ Relationship controls:`);for(let n of yn()){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(`
58
+ Strengths: ${Object.keys(jt).join(", ")}. Unavailable analyses: ${un.map(n=>n.id).join(", ")}.`),console.log(`
59
+ 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}Xg(e),Zg(e)}function Xg(e){console.log(`
60
+ Control contracts:`);for(let t of wn)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(`
61
+ Relationship contracts:`);for(let t of yn()){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(`
62
+ Evidence strength legend:`);for(let[t,n]of Object.entries(jt))console.log(` ${t.toUpperCase().padEnd(11)} ${n}`);console.log(`
63
+ Explicitly unavailable relationship analyses:`);for(let t of un)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 Zg(e){console.log(`
64
+ 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(`
65
+ 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(`
66
+ 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 xt(e){return{...e,options:x(e.options)}}function Je({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let d=xt(l);return{...d,renderShape:"list",handler:ta({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c})}}function En({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=xt(m);return{...h,renderShape:"table",handler:na({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 Ol({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,key:l,...d}){let m=xt(d);return{...m,renderShape:"grouped-by-file",handler:ia({commandName:m.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,key:l})}}function Ai({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let d=xt(l);return{...d,renderShape:"sectioned-report",handler:oi({commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:o,sections:i,toJson:r,coverage:s,agentResult:a,after:c})}}function Dl({query:e,precomputed:t,emptyMessage:n,heuristicLabel:i,sections:o,before:r,toJson:s,coverage:a,agentResult:c,after:l,...d}){let m=xt(d),h={commandName:m.id,emptyMessage:n,heuristicLabel:i,sections:o,before:r,toJson:s,coverage:a,agentResult:c,after:l},p=oi({...h,query:e});return{...m,renderShape:"sectioned-report",handler:oa(h,t,p)}}function mt({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:o,toJson:r,coverage:s,agentResult:a,after:c,...l}){let d=xt(l);return{...d,budget:d.budget??"semantic",renderShape:"sectioned-report",handler:ra(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 Pf,mkdirSync as jf,writeFileSync as Nf}from"fs";import{dirname as Of,relative as Df}from"path";import{existsSync as Ye,readdirSync as sf}from"fs";import{basename as af,dirname as Vl,isAbsolute as Gl,join as cf,relative as lf,resolve as Ut,sep as df}from"path";import{spawnSync as tf}from"child_process";import{dirname as nf}from"path";function ql(e){let n=(e.spawnSync??tf)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:nf(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 Fl(e){let t=rf(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=Bl(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 of=8;function rf(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=Ii(s,"uniquename"),c=Ii(s,"kind"),l=Ii(s,"filename");t.push({uid:i[1],type:i[2],uniquename:a===null?null:Ml(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:Ml(l),block:s})}return t}function Bl(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<of&&!r.has(p.uid)&&p.filename===o){let g=Bl(p.block,t,n,i,o,new Set([...r,p.uid]),s+1);for(let f of g.reads)a.add(f);for(let f of g.writes)c.add(f)}continue}d==="unchanged-run"&&(d="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function Ii(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function Ml(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var Ul=["update","insert","delete"],Hl=["select","query","findFirst","findMany"],Li=new Set([...Ul,...Hl]);function Pi(e){let t=e.methods&&e.methods.length>0?e.methods:[...Li],n=new Set(Ul),i=new Set(Hl);return{write:t.filter(o=>n.has(o)),read:t.filter(o=>i.has(o))}}var uf=/^(.*)@L(\d+)-L(\d+)$/;function ji(e){let t=e.match(uf);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 pf=new Set(["auto","sany","tlc","apalache","none"]),An=/^[A-Za-z_][A-Za-z0-9_]*$/;function Ql(e){return pf.has(e)}function In(e,t){let n=[],i=we(e,t);if(!i)return{errors:[`map path escapes project root: ${t}`]};if(!Ye(i))return{errors:[`map file not found: ${t}`]};let o;try{o=JSON.parse(ve(i,{inputKind:"TLA mapping",maxBytes:Zt}))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let r=mf(o,n);return r?{loaded:{contract:r,mapPath:i,mapDir:Vl(i)},errors:n}:{errors:n}}function we(e,t){if(!t)return null;let n=Gl(t)?Ut(t):Ut(e,t);return ot(e,n)?n:null}function Kl(e,t,n){if(!n)return null;if(Gl(n)){let s=Ut(n);return ot(e,s)?s:null}let i=Ut(e,n);if(ot(e,i)&&Ye(i))return i;let o=Ut(t,n);if(ot(e,o)&&Ye(o))return o;let r=ot(e,i)?i:o;return ot(e,r)?r:null}function zl(e,t){let n=we(e,t);if(!n||!Ye(n))return null;let i=ve(n,{inputKind:"TLA module",maxBytes:rt});return{path:n,modelParse:"regex-fallback",text:i,variables:Ef(i),operators:Tf(i),actions:[]}}function Jl(e,t,n){let i=we(e,t);if(!i||!Ye(i))return null;let o=ve(i,{inputKind:"TLA module",maxBytes:rt}),r=Fl(n);return{path:i,modelParse:"sany",text:o,variables:r.variables,operators:r.operators,actions:r.actions}}function Ni(e,t){let n=we(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!Ye(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let i=JSON.parse(ve(n,{inputKind:"TLA trace",maxBytes:rt})),o=Array.isArray(i)?i:ne(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(!ne(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}r.push({action:c.action,before:ne(c.before)?c.before:void 0,after:ne(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 Oi(e,t){let n=new Set,i=[];for(let o of t){let r=we(e,o)??o;n.has(r)||(n.add(r),i.push(o))}return i}function mf(e,t){if(!ne(e))return t.push("map file must contain a JSON object"),null;let n=vf(e.variables,t);bf(n,t);let i=Cf(e.actions,n,t),o=hf(e.init,t);ff(o,i,t);let r={module:Wl(e.module,"module",t),config:Wl(e.config,"config",t),scope:ge(e.scope)??[],variables:n,actions:i,...o?{init:o}:{},invariants:ge(e.invariants)??[],traces:ge(e.traces)??[],unmappedWriteScope:yf(e.unmappedWriteScope,t)};return If(e.scope,t),t.length===0?r:null}function hf(e,t){if(e===void 0)return;if(!ne(e)){t.push("init must be an object when present");return}let n=ge(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let i=gf(e.waive,t);return{codeRefs:n,...i?{waive:i}:{}}}function gf(e,t){if(e===void 0)return;if(!ne(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 ff(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 yf(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 bf(e,t){Tn(e,t,"alias",n=>n.aliases),Tn(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),Tn(e,t,"statement pattern",n=>n.statements?n.statements.map(i=>i.pattern):[]),Tn(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(i=>{let{write:o,read:r}=Pi(i);return[...o,...r].map(s=>`${i.table}:${s}`)}))}function Tn(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 vf(e,t){if(!ne(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(!An.test(i)){t.push(`invalid TLA+ variable name: ${i}`);continue}if(!ne(o)){t.push(`variables.${i} must be an object`);continue}let r=Xl(o.code);if(!r||r.length===0){t.push(`variables.${i}.code must name at least one TypeScript referent`);continue}let s=ge(o.aliases)??[],a=$f(o.resource,i,t),c=wf(o.statements,i,t),l=Rf(o.ormCalls,i,t),d=xf(o.waive,i,t),m=Sf(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 Sf(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 $f(e,t,n){if(e===void 0)return;if(!ne(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 wf(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(!ne(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{Xt(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 Rf(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(!ne(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=ge(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=>!Li.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${r}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...Li].join(", ")}`);return}i.push(a.length>0?{table:s,methods:a}:{table:s})}),i.length>0?i:void 0}function xf(e,t,n){if(e===void 0)return;if(!ne(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 Cf(e,t,n){if(!ne(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(!An.test(r)){n.push(`invalid TLA+ action name: ${r}`);continue}if(!ne(s)){n.push(`actions.${r} must be an object`);continue}let a=Xl(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=ji(h);"error"in p&&n.push(`actions.${r}.code: ${p.error}`)}let c=ge(s.reads)??[],l=ge(s.writes)??[],d=ge(s.calls)??[];for(let h of[...c,...l])i.has(h)||n.push(`actions.${r} references unknown variable: ${h}`);let m=kf(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 kf(e,t,n,i,o,r,s){if(ne(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=ge(e.reads)??[],l=ge(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${r}.waive must list reads or writes`),_l(r,"reads",c,o,s),_l(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 _l(e,t,n,i,o){for(let r of n)i.has(r)||o.push(`actions.${e}.waive.${t} references unknown variable: ${r}`)}function Ef(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();An.test(r)&&t.add(r)}}return[...t].sort()}function Tf(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 Af=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function Yl(e){if(!e||!Ye(e))return[];let t=ve(e,{inputKind:"TLA checker configuration",maxBytes:Zt}).replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,i=!1;for(let o of t.split(/[\s,]+/))if(o){if(Af.has(o)){i=o==="INVARIANT"||o==="INVARIANTS";continue}i&&An.test(o)&&n.add(o)}return[...n].sort()}function Wl(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function Xl(e){return typeof e=="string"?[e]:ge(e)}function If(e,t){e!==void 0&&(ge(e)||t.push("scope must be an array of strings when present"))}function Ln(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var Lf=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function Zl(e,t){if(!Ye(t))return{status:"none"};let i=ve(t,{inputKind:"TLA module",maxBytes:rt}).match(Lf)?.[1],o=lf(e,t).split(df).join("/"),r=af(t),s=new Set([i,o,r,r.replace(/\.tla$/i,"")].filter(d=>!!d)),a=Vl(t);if(!Ye(a))return{status:"none"};let c=[];for(let d of sf(a)){if(!d.endsWith(".scip-tla.json"))continue;let m=cf(a,d),h;try{h=JSON.parse(ve(m,{inputKind:"TLA mapping candidate",maxBytes:Zt}))}catch{continue}ne(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 Pn(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(` ${fe(m.startLine,m.endLine)} (${m.loc} LOC) ${m.shortName}${h}`)}}}var Di=20,ed=ee("dead",({db:e,args:t,opts:n,budget:i})=>{let o={scope:U(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=nr(e,o),s=r.symbols.filter(M=>M.kind==="dead-code"),a=r.symbols.filter(M=>M.kind==="file-internal"),c=r.symbols.filter(M=>M.kind==="implicit-usage"),l=!b(n,"onlyInternal"),d=!b(n,"onlyDead"),m=!b(n,"onlyDead")&&!b(n,"onlyInternal"),h=l?s:[],p=d?a:[],g=m?c:[],f=h.reduce((M,te)=>M+te.loc,0),y=p.reduce((M,te)=>M+te.loc,0),v=g.reduce((M,te)=>M+te.loc,0),R=b(n,"full"),N=R?h:h.slice(0,Di),F=R?p:p.slice(0,Di),H=R?g:g.slice(0,Di),L=N.reduce((M,te)=>M+te.loc,0),q=F.reduce((M,te)=>M+te.loc,0),E=H.reduce((M,te)=>M+te.loc,0),T={total:h.length+p.length+g.length,deadCode:h.length,fileInternal:p.length,implicitUsage:g.length,loc:f+y+v};if(b(n,"json")){I("dead",t,n,{...r,shown:{deadCode:h,fileInternal:p,implicitUsage:g},shownCounts:T,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&&g.length===0){A.empty("No matching dead-code symbols found.");return}h.length>0&&(Pn(N,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
67
+ Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,L,{count:h.length,loc:f}),!R&&h.length>N.length&&console.log(`
68
+ Showing top ${N.length} by LOC. Re-run with --full for the remaining ${h.length-N.length}.`)),p.length>0&&(h.length>0&&console.log(""),Pn(F,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
69
+ single-use helper, an abstraction-in-progress, or a callback registered
70
+ through a framework path that static analysis cannot trace (signal
71
+ handlers, event listeners, dependency injection). NOT necessarily dead \u2014
72
+ review case by case.`,q,{count:p.length,loc:y}),!R&&p.length>F.length&&console.log(`
73
+ Showing top ${F.length} by LOC. Re-run with --full for the remaining ${p.length-F.length}.`)),g.length>0&&((h.length>0||p.length>0)&&console.log(""),Pn(H,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
74
+ consumer that the static reference graph cannot trace. Investigation
75
+ signals only \u2014 not deletion candidates and not counted as dead code.`,E,{count:g.length,loc:v}),!R&&g.length>H.length&&console.log(`
76
+ Showing top ${H.length} by LOC. Re-run with --full for the remaining ${g.length-H.length}.`));let V=[];l&&V.push(`${h.length} dead code (${f} LOC)`),d&&V.push(`${p.length} file-internal (${y} LOC)`),m&&V.push(`${g.length} implicit usage (${v} LOC)`),console.log(`
77
+ \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+g.length} symbols \u2014 ${V.join(" + ")}`)}),td=Se("unused-imports",{query:({db:e,args:t,budget:n})=>sr(e,j(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
78
+ ${e.length} unused import(s)`)}),nd=sa("isolated",{query:({db:e,opts:t,budget:n})=>fr(e,{scope:$(t,"scope"),minLoc:k(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${fe(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
79
+ ${e.length} isolated symbol(s)`)}),id=ee("extract-candidates",({db:e,args:t,opts:n,budget:i})=>{let o=Nr(e,{scope:$(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")){I("extract-candidates",t,n,o,{analysisBudget:i.analysisBudget});return}if(o.length===0)return A.empty("No extraction candidates found.");He("extraction candidates");for(let r of o){console.log(`
80
+ ${_(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(`
81
+ ${o.length} extraction candidate(s) found.`)}),od=ee("locality-candidates",({db:e,args:t,opts:n,budget:i})=>{let o=Or(e,{target:U(t,0)||void 0,scope:$(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")){I("locality-candidates",t,n,o,{analysisBudget:i.analysisBudget});return}if(o.length===0)return A.empty("No locality candidates found.");He("locality candidates");for(let r of o){let s=r.sourceUnit.kind==="symbol"&&r.sourceUnit.startLine!==void 0&&r.sourceUnit.endLine!==void 0?_(r.sourceUnit.file,r.sourceUnit.startLine,r.sourceUnit.endLine):r.sourceUnit.file;if(console.log(`
82
+ ${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(`
83
+ ${o.length} locality candidate(s) found.`)}),rd=Se("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>as(e,{scope:$(t,"scope"),maxLoc:k(t,"maxLoc",15),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${_(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
84
+ Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
85
+ Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
86
+ ${e.length} wrapper candidate(s).`)}),sd=Se("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>Hr(e,{scope:$(t,"scope"),maxLoc:k(t,"maxLoc",15),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${_(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
87
+ Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
88
+ Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
89
+ Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
90
+ Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
91
+ ${e.length} passthrough candidate(s).`)}),ad=Se("stale-abstractions",{query:({db:e,opts:t,budget:n})=>ss(e,{scope:$(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}] ${_(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
92
+ ${e.reason}
93
+ Kind: ${e.stalenessKind}; tier: ${e.actionTier}
94
+ Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
95
+ ${e.length} stale abstraction(s).`)}),cd=mn("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>us(e,{scope:$(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]}),ld=Ie("similar",{query:({db:e,args:t,opts:n,budget:i})=>{if(b(n,"plan")){let r=U(t,0),s=U(t,1);if(!r||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:xr(e,r,s,{scanLimit:i.scanLimit,semantic:i.semantic})}}let o=U(t,0);return o?{mode:"target",rows:Rr(e,o,{minSimilarity:k(n,"minSimilarity",.4),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic})}:{mode:"all",rows:Cr(e,{minSimilarity:k(n,"minSimilarity",.4),limit:D(n,"limit",20),scope:$(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(`
96
+ ${Math.round(t.similarity*100)}% ${n}
97
+ `),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}
98
+ `),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let i of t.sharedEvidence)console.log(` ${i}`);if(t.uniqueToA.length>0){console.log(`
99
+ Unique to A (${t.uniqueToA.length}):`);for(let i of t.uniqueToA)console.log(` ${i}`)}if(t.uniqueToB.length>0){console.log(`
100
+ Unique to B (${t.uniqueToB.length}):`);for(let i of t.uniqueToB)console.log(` ${i}`)}console.log(`
101
+ 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=[`
102
+ ${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(`
103
+ `)});return}A.list(e.rows,t=>`
104
+ ${Math.round(t.similarity*100)}% similar:
105
+ A: ${t.shortNameA} (${t.fileA})
106
+ B: ${t.shortNameB} (${t.fileB})
107
+ Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})
108
+ Recommendation: ${t.recommendation}
109
+ `+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
110
+ `:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
111
+ ${e.rows.length} similar pair(s) found.`)}}),dd=nt({commandName:"similar-files",query:({db:e,args:t,opts:n})=>kr(e,{minSimilarity:k(n,"minSimilarity",.5),limit:D(n,"limit",20),scope:$(n,"scope"),minDeps:K(n,"minDeps"),filePattern:U(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=[`
112
+ ${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(`
113
+ `)}),console.log(`
114
+ ${e.length} similar pair(s) found.`)}}),ud=nt({commandName:"similar-chains",query:({db:e,opts:t})=>jr(e,{minSimilarity:k(t,"minSimilarity",.5),limit:D(t,"limit",15),scope:$(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(`
115
+ \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(`
116
+ ${e.length} similar chain pair(s) found.`)}}),pd=Ie("drift",{query:({db:e,args:t,opts:n,budget:i})=>rs(e,{scope:U(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(`
117
+ `)},t=>t.file),e.architecture){let t=e.architecture,n=t.edges.filter(i=>i.policyStatus==="undeclared").length;if(console.log(`
118
+ 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(`
119
+ ${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)`:""}`)}}),md=Ie("convergence",{query:({db:e,args:t,budget:n})=>gs(e,j(t,0),j(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(`
120
+ ${Math.round(e.similarity*100)}% callee overlap
121
+ `),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)
122
+ `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
123
+ Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
124
+ Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
125
+ Strategy: ${e.consolidationStrategy}`)}}}),hd=Se("similar-signatures",{query:({db:e,opts:t,budget:n})=>Ss(e,{scope:$(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=`
126
+ Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,i=e.functions.map(o=>` ${_(o.file,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC)`).join(`
127
+ `);return`${n}
128
+ ${i}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
129
+ ${e.length} group(s) found.`)}),gd=Se("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>Gr(e,{scope:$(t,"scope"),maxLoc:k(t,"maxLoc",15),minLoc:k(t,"minLoc",3),limit:D(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
130
+ Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((i,o)=>` ${(o===0?"canonical":"duplicate").padEnd(9)} ${_(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
131
+ `);return`${t}
132
+ ${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>console.log(`
133
+ ${e.length} group(s) found.`)}),fd=Se("twin-drift",{query:({db:e,opts:t,budget:n})=>Ur(e,{scope:$(t,"scope"),minSimilarity:k(t,"minSimilarity",.3),includeHomonyms:b(t,"includeHomonyms"),limit:D(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
134
+ ${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(o=>` ${_(o.file,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC)`).join(`
135
+ `),i=e.firstDivergentTokens?`
136
+ first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
137
+ ${n}${i}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
138
+ ${e.length} group(s) found.`)}),yd=Se("not-implemented",{query:({db:e,opts:t,budget:n})=>zr(e,{scope:$(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${_(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
139
+ ${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
140
+ ${e.length} reachable placeholder stub(s).`)}),bd=Se("decorative-checkers",{query:({db:e,opts:t,budget:n})=>Jr(e,{scope:$(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${_(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(`
141
+ ${e.length} decorative checker candidate(s).`)}),vd=ee("test-quality",({db:e,args:t,opts:n,budget:i})=>{let o=Yr(e,{scope:$(n,"scope"),limit:D(n,"limit",30),scanLimit:i.scanLimit,rotDays:K(n,"rotDays")});if(b(n,"json")){I("test-quality",t,n,o,{analysisBudget:i.analysisBudget});return}if(He("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(`
142
+ ASSERTION-FREE (${o.assertionFree.length})`),A.list(o.assertionFree,s=>` ${_(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),o.skipped.length>0&&(console.log(`
143
+ 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(`
144
+ MOCK-ECHO (${o.mockEcho.length})`),A.list(o.mockEcho,s=>` ${_(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
145
+ ${o.assertionFree.length} assertion-free, ${o.skipped.length} skipped, ${o.mockEcho.length} mock-echo.`)}),Sd=nt({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let i=j(t,0),o=j(t,1),r=$(n,"out")??Qr(i,o),s=we(e.config.projectRoot,r);if(!s)throw new Error(`twin-ab output path escapes the project root: ${r}`);let a=Kr(e,{refA:i,refB:o,outFile:s});if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=Df(e.config.projectRoot,s);if(!b(n,"force")&&Pf(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return jf(Of(s),{recursive:!0}),Nf(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
146
+ Wrote behavioral A/B scaffold: ${e.outPath}`),console.log(` A: ${e.a.shortName} (${_(e.a.file,e.a.startLine,e.a.startLine)})`),console.log(` B: ${e.b.shortName} (${_(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(`
147
+ Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),$d=ee("cleanup-plan",({db:e,args:t,opts:n,budget:i})=>{let o=qr(e,{scope:$(n,"scope"),minLoc:k(n,"minLoc",1),maxDepth:k(n,"maxDepth",5),scanLimit:i.scanLimit}),r=ce(),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){I("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=Ua(o),d=c?Ba(r,o):void 0;if(a){I("cleanup-plan",t,n,{result:o,verification:d},{analysisBudget:i.analysisBudget});return}if(s){let m=Ha(d,l);if(m.length>0){for(let p of m)console.error(`error: ${p}`);process.exitCode=1;return}let h=Ga(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.
148
+ `);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(`
149
+ 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),g=d.dirtyWorkingTree.length-p.length;console.log(` WARNING: verification ran at HEAD; ${d.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${p.join(", ")}${g>0?`, ... ${g} more`:""}`)}let m=Mf(d.checkers),h=qf(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 g of p.errors??[])console.log(` ${g}`)}}});function Mf(e){return e.join(", ")}function qf(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var wd=ee("recent-duplicates",({db:e,args:t,opts:n,budget:i})=>{let o=b(n,"full"),r=Xr(e,{windowCommits:k(n,"window",100),minSimilarity:K(n,"minSimilarity"),limit:D(n,"limit",30),scope:$(n,"scope"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:o?"full":"bounded"});if(b(n,"json")){I("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).`);He("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
150
+ `);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(`
151
+ ${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Rd=Y(({db:e,args:t,opts:n})=>{let i=b(n,"full"),o=Vr(e,{doc:t[0]===void 0?void 0:j(t,0),limit:D(n,"limit",20),minCoupling:k(n,"minCoupling",3),includeSnapshotExcluded:i,historyMode:i?"full":"bounded"});if(b(n,"json")){I("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.`);He("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${o.docsScanned} docs scanned, ${o.commitsAnalyzed} commits analyzed):
152
+ `);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: ${Gs(m)}`)}}console.log(`
153
+ Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),xd=Se("unused-params",{query:({db:e,opts:t,budget:n})=>ds(e,{scope:$(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${_(e.file,e.startLine,e.endLine)} ${e.shortName}
154
+ 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(`
155
+ ${e.length} function(s) with trailing unused parameters.`)});var Cd=Ie("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>Er(e,{minSimilarity:k(n,"minSimilarity",.62),minTokens:k(n,"minTokens",8),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:U(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=[`
156
+ ${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(`
157
+ `)}),console.log(`
158
+ ${e.length} duplicated React component pair(s) found.`)}}),kd=Ie("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:i})=>Tr(e,{minSimilarity:k(n,"minSimilarity",.45),minSharedBehaviors:k(n,"minSharedBehaviors",6),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:U(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=[`
159
+ ${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(`
160
+ `)}),console.log(`
161
+ ${e.length} React hook candidate pair(s) found.`)}}),Ed=Ie("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:i})=>Ar(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:$(n,"scope"),scanLimit:i.scanLimit,filePattern:U(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=>[`
162
+ ${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(`
163
+ `)),console.log(`
164
+ ${e.length} large React component(s) found.`)}}),Td=Ie("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>Ir(e,{minSimilarity:k(n,"minSimilarity",.62),minTokens:k(n,"minTokens",8),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:U(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=[`
165
+ ${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(`
166
+ `)}),console.log(`
167
+ ${e.length} duplicated Vue component pair(s) found.`)}}),Ad=Ie("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:i})=>Lr(e,{minSimilarity:k(n,"minSimilarity",.45),minSharedBehaviors:k(n,"minSharedBehaviors",6),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:U(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=[`
168
+ ${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(`
169
+ `)}),console.log(`
170
+ ${e.length} Vue composable candidate pair(s) found.`)}}),Id=Ie("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:i})=>Pr(e,{minTotalLines:b(n,"reviewThresholds")&&aa(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:$(n,"scope"),scanLimit:i.scanLimit,filePattern:U(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=[`
171
+ ${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(`
172
+ `)}),console.log(`
173
+ ${e.length} large Vue view pressure file(s) found.`)}});function be(e){return{docs:w("Cleanup"),...e}}function oe({heuristicLabel:e,...t}){return be({...t,heuristic:{label:e}})}var jn=[be({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:w("Cleanup",["scip-query unused-params -s src/services"]),handler:xd}),be({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:w("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:$d}),be({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",ke),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:w("Cleanup",["scip-query recent-duplicates --window 50"]),handler:wd}),be({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:w("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Rd}),be({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:w("Cleanup",["scip-query dead --min-loc 10"]),handler:ed}),be({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:td}),be({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:nd}),oe({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)",ke,.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:ld}),oe({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)",ke,.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:dd}),oe({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)",ke,.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:Cd}),oe({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)",ke,.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:kd}),oe({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:Ed}),oe({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)",ke,.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:Td}),oe({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)",ke,.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:Ad}),oe({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:Id}),oe({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)",ke,.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:ud}),oe({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:id}),oe({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:w("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:od}),oe({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",le,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:pd}),oe({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:rd}),oe({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:sd}),oe({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:ad}),oe({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:cd}),be({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:md}),Ol({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:w("Cleanup"),query:({db:e,opts:t})=>bs(e,{scope:$(t,"scope"),limit:D(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
174
+ barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
175
+ Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
176
+ Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
177
+ ${e.length} redundant re-export(s).`)}),be({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:gd}),be({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)",ke,.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:fd}),oe({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:w("Cleanup",["scip-query not-implemented -s src/services"]),handler:yd}),oe({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:w("Cleanup",["scip-query decorative-checkers -s src/services"]),handler:bd}),be({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:w("Cleanup",["scip-query test-quality -s tests/queries"]),handler:vd}),be({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:w("Cleanup",["scip-query twin-ab src/a.ts/escapeRegex src/b.ts/escapeRegExp"]),handler:Sd}),be({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:hd})];var Ff=Y(({db:e,args:t,opts:n})=>{let i=Lt(e);if(b(n,"json")){I("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: ${se(i.indexSizeBytes)}`),i.lastBuilt&&console.log(`Last built: ${i.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Ld=[{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:w("Core"),handler:Ff}];var Bf=mn("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>gr(e,{limit:D(t,"limit",20),scope:$(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."}),_f=Y(({db:e,args:t,opts:n})=>{let i=U(t,0),o=D(n,"limit",30);if(i){let c=cr(e,i);if(b(n,"json")){I("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=dr(e,{limit:o,scope:$(n,"scope")});if(b(n,"json")){I("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}]`:""}`))}),Wf=Y(({db:e,args:t,opts:n})=>{let i=U(t,0),o=D(n,"limit",30);if(i){let s=lr(e,i);if(b(n,"json")){I("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=ur(e,{limit:o,scope:$(n,"scope")});if(b(n,"json")){I("fan-out",t,n,{mode:"top",rows:r});return}A.table(["symbols","file"],r.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),Vf=Y(({db:e,args:t,opts:n})=>{let i=U(t,0),o=U(t,1),r=D(n,"limit",20);if(i&&o){let a=pr(e,i,o);if(b(n,"json")){I("coupling",t,n,{mode:"pair",result:a});return}console.log(`${a.file1} \u2194 ${a.file2}: ${a.sharedSymbols} shared symbols (${a.actionTier})`),console.log(` Risk: ${a.couplingKind}`),console.log(` Recommendation: ${a.recommendation}`);return}let s=mr(e,{limit:r,scope:$(n,"scope")});if(b(n,"json")){I("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}`))}),Gf=nt({commandName:"cycles",query:({db:e,opts:t})=>hr(e,{scope:$(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(`
178
+ 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(`
179
+ ${e.cycles.length} cyclic component(s) found; results are SCC-complete, not all simple cycles.`)}}),Uf=nt({commandName:"architecture",query:({db:e,opts:t})=>ft(e,{scope:$(t,"scope")}),emptyMessage:e=>e.configured?void 0:"No architecture boundaries configured. Add architecture.boundaries to .scipquery.json.",render:e=>{let t=dt(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(`
180
+ 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(`
181
+ No forbidden dependency edges found.`);if(e.staleAllowances.length>0){let n=e.policyCoverage.requiresMinimalPolicy?" [violates requireMinimalPolicy]":"";console.log(`
182
+ 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(`
183
+ 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(`
184
+ 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(`
185
+ 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(`
186
+ 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(`
187
+ 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(`
188
+ 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(`
189
+ 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=>{dt(e).length>0&&(process.exitCode=1)}});function Od(e){return nt({commandName:e,query:({db:t,opts:n})=>vr(t,{limit:D(n,"limit",10),scope:$(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(`
190
+ 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 Hf=Od("deep-chains"),Qf=Od("dependency-depth"),Kf=Y(({db:e,args:t,opts:n})=>{let i=U(t,0),o=$r(e,{search:i,scope:$(n,"scope")});if(b(n,"json")){I("entrypoints",t,n,o,{coverage:{complete:!0,totalKnown:!0,returned:o.length,total:o.length,omitted:0}});return}let r=$(n,"scope");if(console.log(`\u2550\u2550\u2550 REQUEST \u2550\u2550\u2550
191
+ text=${i?JSON.stringify(i):"<all>"}; scope=${r??"<repository>"}`),o.length===0){console.log(`
192
+ \u2550\u2550\u2550 OBSERVED FACTS \u2550\u2550\u2550
193
+ ${i?`No detected entry candidate matched ${JSON.stringify(i)}.`:"No entry candidates were detected."}`),console.log(`
194
+ \u2550\u2550\u2550 EVIDENCE CALIBRATION \u2550\u2550\u2550
195
+ Absence from this detector does not prove that the repository has no runtime ingress.`),console.log(`
196
+ \u2550\u2550\u2550 COVERAGE \u2550\u2550\u2550
197
+ Complete within the detector's indexed source/compiler entry evidence.`);return}console.log(`
198
+ \u2550\u2550\u2550 OBSERVED FACTS \u2550\u2550\u2550`),A.list(o,s=>` [${s.confidence}] ${s.file}:${P(s.startLine)} ${s.shortName}
199
+ evidence: ${s.evidence.join(", ")}; indexed callers: ${s.indexedCallerCount}
200
+ symbol: ${s.symbol}`),console.log(`
201
+ \u2550\u2550\u2550 EVIDENCE CALIBRATION \u2550\u2550\u2550
202
+ [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(`
203
+ \u2550\u2550\u2550 COVERAGE \u2550\u2550\u2550
204
+ ${o.length} entry candidate(s); complete within indexed detector evidence.`),console.log(`
205
+ \u2550\u2550\u2550 RECOVERY \u2550\u2550\u2550
206
+ Any printed exact symbol can be projected with scip-query evidence using the family and direction required by the material question.`)}),zf=Y(({db:e,args:t,opts:n})=>{let i=j(t,0),o=wr(e,i,{expand:O(n,"expand")});if(b(n,"json")){I("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}:${P(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(", ")}
207
+ `),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}
208
+ ${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)
209
+ ${a}`)}if(o.regionEdges.length>0){console.log(`
210
+ \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(", ")})
211
+ ${s.fromSymbols.join(", ")} \u2192 ${s.toSymbols.join(", ")}`)}let r=o.regions.filter(s=>s.expanded);if(r.length>0){console.log(`
212
+ \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}
213
+ ${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(`
214
+ Unmatched expansion id(s): ${o.unmatchedExpansions.join(", ")}`),console.log(`
215
+ 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.")}),Jf=Y(({db:e,args:t,opts:n})=>{let i=O(n,"selectionTerm"),o=Xo(e,{searches:O(n,"search"),symbols:O(n,"symbol"),behaviorFocusLocations:O(n,"focusAt").map(ey),maxDepth:k(n,"depth",5),expand:O(n,"expand"),relations:O(n,"relation"),evidenceFloor:$(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")){I("system-map",t,n,o,{coverage:{complete:!1,totalKnown:!1,returned:o.regions.length}});return}if(b(n,"gapRecoveryOnly")){Yf(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 g=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 ${g}`),(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 f of p.representativeMatches??[]){let y=f.ownerShortName?` ${re(f.ownerShortName)}`:"";console.log(` representative: ${f.file}:${P(f.line)}${y} \u2014 ${f.sourceLine.slice(0,160)}`)}for(let f of p.narrowingCommands??[])console.log(` narrow exactly: ${f}`);if(p.exhaustiveTraversalCommand&&console.log(` exhaustive recovery: ${p.exhaustiveTraversalCommand}`),p.kind==="symbol"&&p.matchedRegionIds.length>0&&console.log(` regions: ${p.matchedRegionIds.join(", ")}`),!l){let f=d?(p.symbolCandidates??[]).slice(0,3):p.symbolCandidates??[];for(let y of f)console.log(` ${y.relativePath}:${P(y.startLine)} ${re(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(L=>[L.id,L])),g=o.topology.nodes.filter(L=>L.disposition==="emitted"),f=o.topology.edges.filter(L=>L.disposition==="emitted"&&L.kind!=="structural-membership"&&L.fromNodeId!==L.toNodeId),y=o.topology.frontiers.filter(L=>L.disposition==="folded");console.log(`
216
+ \u2550\u2550\u2550 QUERY CONNECTOR GRAPH \u2550\u2550\u2550`),console.log(` ${g.length}/${o.topology.nodes.length} node(s) selected; ${f.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 L of o.topology.paths){let q=L.nodeIds.map(E=>p.get(E)?.label??E);console.log(` [${L.status}] ${q.length>0?q.join(" \u2194 "):"no proved connector"}`)}let v=o.topology.routeCatalog;if(v){let L=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 q of v.routes){let E=L.has(q.id)?"; selected":"",T=q.relatedEdgeFamilies.length>0?q.relatedEdgeFamilies.join(","):"control",V=q.nodeIds.map(M=>re(p.get(M)?.label??M)).join(" \u2192 ");console.log(` [${q.id}; ${q.endpointKind}; ${q.edgeIds.length} edge(s); families ${T}${E}] ${V} @ ${q.endpointLocation.file}:${P(q.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: ${Zf(n,[])} --route '<route-id>'`)}let R=g.filter(L=>typeof L.attributes.upstreamCausalEndpoint=="string");if(R.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 L of R){let q=L.location?` @ ${L.location.file}:${P(L.location.line)}`:"",E=Number(L.attributes.upstreamCausalDistance??0);console.log(` [${String(L.attributes.upstreamCausalEndpoint)}; ${E} edge(s) to anchor] ${re(L.label)}${q}`)}}let N=d?4:8;for(let L of f.slice(0,N)){let q=p.get(L.fromNodeId)?.label??L.fromNodeId,E=p.get(L.toNodeId)?.label??L.toNodeId,T=[...new Set(L.evidence.map(V=>V.strength))].join("/");console.log(` ${q} \u2192 ${E} \u2014 ${L.kind} [${T}]`)}f.length>N&&console.log(` +${f.length-N} selected connector edge(s).`);let F=y.slice(0,d?1:2);for(let L of F){let q=L.memberNodeIds.slice(0,2).map(E=>p.get(E)?.label??E).join(", ");console.log(` [folded ${L.id}] ${L.memberCount} node(s), ${L.edgeIds.length} edge(s)${q?` \u2014 ${q}`:""}`)}let H=F.find(L=>L.expansion)?.expansion;if(H&&!d){let L=H.replace(/ --frontier '[^']+'$/u,"");console.log(` Expand shown frontiers together: ${L} ${F.map(q=>`--frontier '${q.id}'`).join(" ")}`)}y.length>F.length&&console.log(` +${y.length-F.length} frontier group(s); all exact members and expansion commands remain in the structured result.`),ty(o.topology,o.behavior)}if(o.behavior&&o.behavior.steps.length>0){if(console.log(`
217
+ \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 g of o.behavior.coverage.unmatchedFocusLocations)console.log(` [unmatched focus] ${g.file}:${P(g.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(g=>[g.id,g.order+1]));for(let g of o.behavior.steps){let f=g.location?` @ ${g.location.file}:${P(g.location.line)}`:"";if(console.log(` ${g.order+1}. [${g.role}; ${g.kind}] ${re(g.label)}${f}`),!g.behavior)continue;let y=[` [${g.behavior.kind}; ${g.behavior.constructKind}] ${g.behavior.signature} (${g.behavior.renderedCharacters}/${g.behavior.rawCharacters} chars; ${g.behavior.coverage.representedStatements}/${g.behavior.coverage.sourceStatements} detected behavior statements selected)`];for(let v of g.behavior.lines){let R=v.signals.length>0?` [${v.signals.join(",")}]`:"";y.push(` ${P(v.line)}${R} ${" ".repeat(v.depth)}${v.text}`)}for(let v of g.behavior.supportingDeclarations??[]){let R=v.text.replace(/\s*\n\s*/gu," ");y.push(` [support; ${v.kind}] ${v.label} @ ${v.file}:${P(v.line)} \u2014 ${R}`)}for(let v of g.behavior.omittedSupportingDeclarations??[])y.push(` [support omitted; ${v.reason}] ${v.label} @ ${v.file}:${P(v.line)}-${P(v.endLine)}`);console.log(Dt({kind:"unit",identity:g.nodeId,content:y.join(`
218
+ `),label:re(g.label),indent:" "}))}if(o.behavior.transitions.length>0){console.log(" Transitions (arrows preserve repository-edge direction):");for(let g of o.behavior.transitions){let f=g.evidence.map(N=>`${N.method}/${N.strength}`).join(", "),y=g.kind==="runtime-boundary"?[...new Set(g.evidence.flatMap(N=>typeof N.identity=="string"&&N.identity.length>0?[N.identity]:[]))]:[],v=p.get(g.fromStepId)??"?",R=p.get(g.toStepId)??"?";console.log(Dt({kind:"edge",identity:g.edgeId,content:` ${v} \u2192 ${R} \u2014 ${g.kind}; path=${g.pathTraversal}; ${f}`+(y.length>0?`; key=${y.join(" | ")}`:""),label:`${v} \u2192 ${R} ${g.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(`
219
+ \u2550\u2550\u2550 ADJACENT RECOVERY INVENTORY \u2550\u2550\u2550`);let p=[...o.nextAnchors.anchors,...o.nextAnchors.withheldAnchors],g=new Map;for(let f of p){let y=`${f.direction}/${f.relationKind}/${f.causalRole}`;g.set(y,(g.get(y)??0)+1)}console.log(` ${o.nextAnchors.candidateAnchors} exact or candidate adjacent target(s) are recoverably folded.`);for(let[f,y]of[...g].sort(([v],[R])=>v.localeCompare(R)))console.log(` ${f}: ${y}`);console.log(` Select a named missing callee without relevance inference: ${Xf(n,["<callee-from-connected-behavior>"])}.`)}if(o.regions.length===0)console.log(`
220
+ No structural regions matched the supplied anchors.`);else{console.log(`
221
+ \u2550\u2550\u2550 COLLAPSED SYSTEM REGIONS \u2550\u2550\u2550`);for(let p of a){let g=p.expanded?"expanded":"collapsed",f=p.notableSymbols.slice(0,2);if(l){console.log(` d${p.minDepth} [${g}] ${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} [${g}] ${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} [${g}] ${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`:""}
222
+ anchors: ${p.anchorQueries.join(", ")||"none"}; drill: ${f.map(y=>`${re(y.shortName)} (${y.file})`).join(", ")||"none"}${p.symbolCount>f.length?`; +${p.symbolCount-f.length}`:""}`)}}if(o.presentation.complete||(console.log(`
223
+ \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: ${Nd(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(`
224
+ \u2550\u2550\u2550 NEXT ABSTRACTION LEVEL \u2550\u2550\u2550`),o.expansion.command)){let p=o.regions.length-o.expansion.regionCount,g=o.expansion.candidateRegionCount??o.expansion.regionCount,f=o.expansion.omittedRegionIds??[];console.log(` Expand ${o.expansion.regionCount}/${g} 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}`),f.length>0&&console.log(` Withheld traversal-relevant regions: ${f.join(", ")}. Add several --expand selectors to the command when they can change the decision.`)}if(c.length>0){console.log(`
225
+ \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(` ${jd(p.fromRegionId)} \u2192 ${jd(p.toRegionId)} \u2014 ${p.relationCount} rel [${p.kinds.join(",")}; ${p.evidence.map(dy).join(",")}]`)}if(o.boundaryFrontiers.length>0){console.log(`
226
+ \u2550\u2550\u2550 UNRESOLVED RUNTIME BOUNDARIES \u2550\u2550\u2550`);let p=sy(o.boundaryFrontiers),g=p.slice(0,d?3:8);for(let f of g){let y=f.frontiers.slice(0,d?1:2).map(v=>`${ay(v.address)} @ ${v.file}:${P(v.line)}`);console.log(` [${f.strength}] ${f.action} \xD7${f.frontiers.length} \u2014 ${y.join("; ")}`),d||console.log(` ${f.reason}`)}p.length>g.length&&console.log(` ${p.length-g.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(`
227
+ \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): ${Nd(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(`
228
+ \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})`),ry(p);o.drilldown?.command&&(console.log(`
229
+ \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(`
230
+ Unmatched expansion id(s): ${o.unmatchedExpansions.join(", ")}`),console.log(`
231
+ 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(`
232
+ 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 g of o.behavior?.steps??[])if(!(!g.location||!g.behavior))for(let f of g.behavior.lines){let y=`${g.location.file}:${P(f.line)}`;f.signals.includes("branch")&&p.get("branch conditions")?.set(y,null),f.signals.includes("shape")&&(f.signals.includes("call")||f.signals.includes("mutation")||f.signals.includes("return"))&&p.get("structured payloads")?.set(y,f.text.replace(/\s*\n\s*/gu," ")),(f.signals.includes("return")||f.signals.includes("throw"))&&p.get("terminal outcomes")?.set(y,null)}console.log(`
233
+ \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[g,f]of p)if(f.size!==0)if(g==="structured payloads"){console.log(` Draft audit \u2014 ${g}:`);for(let[y,v]of f)console.log(` ${y} \u2014 ${v??""}`)}else console.log(` Draft audit \u2014 ${g}: ${[...f.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 Yf(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(Pd)),i=[...e.anchors,...e.withheldAnchors].filter(r=>[r.callsite.calleeLeaf,...r.alternatives.map(s=>s.label)].some(s=>n.has(Pd(s))));if(i.length===0){console.log(` No resolved target matched ${t.map(X).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?`${re(s.label)} @ ${s.file}:${P(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 ${re(r.fromLabel)} @ ${r.callsite.file}:${P(r.callsite.line)} \u2014 `+r.callsite.text.slice(0,220)),r.alternativeCount>1)for(let d of r.alternatives)console.log(` candidate: ${re(d.label)} @ ${d.file}:${P(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 ${X(`${r.file}:${P(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 Xf(e,t=O(e,"gapCallee")){let n=["scip-query","system-map"];for(let o of O(e,"search"))n.push("--search",X(o));for(let o of O(e,"symbol"))n.push("--symbol",X(o));for(let o of O(e,"focusAt"))n.push("--focus-at",X(o));n.push("--depth",String(k(e,"depth",5)));for(let o of O(e,"relation"))n.push("--relation",X(o));let i=$(e,"evidenceFloor");i&&n.push("--evidence-floor",X(i));for(let o of O(e,"sourceScope"))n.push("--source-scope",X(o));b(e,"fullLiteralTraversal")&&n.push("--full-literal-traversal");for(let o of O(e,"expand"))n.push("--expand",X(o));for(let o of O(e,"frontier"))n.push("--frontier",X(o));for(let o of O(e,"route"))n.push("--route",X(o));for(let o of t)n.push("--gap-callee",X(o));return n.push("--gap-recovery-only"),n.join(" ")}function Zf(e,t){let n=["scip-query","system-map"];for(let o of O(e,"search"))n.push("--search",X(o));for(let o of O(e,"symbol"))n.push("--symbol",X(o));for(let o of O(e,"focusAt"))n.push("--focus-at",X(o));n.push("--depth",String(k(e,"depth",5)));for(let o of O(e,"relation"))n.push("--relation",X(o));let i=$(e,"evidenceFloor");i&&n.push("--evidence-floor",X(i));for(let o of O(e,"sourceScope"))n.push("--source-scope",X(o));b(e,"fullLiteralTraversal")&&n.push("--full-literal-traversal");for(let o of O(e,"expand"))n.push("--expand",X(o));for(let o of O(e,"frontier"))n.push("--frontier",X(o));for(let o of t)n.push("--route",X(o));return n.join(" ")}function Pd(e){let t=e.replace(/\(\)$/u,"").replace(/^#/u,"");return(t.slice(Math.max(t.lastIndexOf(":"),t.lastIndexOf("."))+1)||t).toLocaleLowerCase()}function ey(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 ty(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(g=>re(i.get(g)?.label??g)).join(", "),s=new Map,a=new Map;for(let p of t?.steps??[]){if(!p.location||!p.behavior)continue;let g=a.get(p.location.file)??[];g.push(...p.behavior.lines.map(f=>({line:f.line,endLine:f.endLine}))),a.set(p.location.file,g)}let c=p=>p?.location?(a.get(p.location.file)??[]).some(g=>p.location.line>=g.line&&p.location.line<=g.endLine):!1,l=new Map,d=new Map,m=[],h=new Map;for(let p of n.edgeIds){let g=o.get(p);if(g)for(let f of g.semantics??[])if(f.family==="identity"){let y=s.get(g.fromNodeId)??[];y.push(g.toNodeId),s.set(g.fromNodeId,y)}else if(f.family==="control"&&!Mi(f.subtype)){let y=i.get(g.fromNodeId),v=i.get(g.toNodeId),R=typeof y?.attributes.ownerNodeId=="string"?y.attributes.ownerNodeId:g.fromNodeId;if(c(y)&&c(v)){let L=l.get(R)??new Map;L.set(f.subtype,(L.get(f.subtype)??0)+1),l.set(R,L);continue}let N=d.get(R)??new Map,F=N.get(g.fromNodeId)??{controllerLabel:y?.label??re(g.fromNodeId),controllerLocation:y?.location?{file:y.location.file,line:y.location.line}:null,outcomes:new Map},H=F.outcomes.get(f.subtype)??new Set;H.add(v?.label??re(g.toNodeId)),F.outcomes.set(f.subtype,H),N.set(g.fromNodeId,F),d.set(R,N)}else if(ny(f.family,f.subtype)){let y=iy(g.fromNodeId,i),v=`${f.family}\0${f.subtype}\0${y.label}`,R=h.get(v)??{family:f.family,subtype:f.subtype,ownerLabel:y.label,ownerLocation:y.location,count:0,targetLabels:new Set,values:new Set};R.count+=1,R.targetLabels.add(re(i.get(g.toNodeId)?.label??g.toNodeId));let N=f.attributes?.value;(typeof N=="string"||typeof N=="number"||typeof N=="boolean")&&R.values.add(String(N)),h.set(v,R)}else m.push({edge:g,semantic:f})}console.log(`
234
+ \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: ${oy(n.outcomeNodeIds,e)}`);for(let[p,g]of[...s].sort(([f],[y])=>f.localeCompare(y))){let f=new Map;for(let v of new Set(g)){let R=i.get(v)?.kind??"unknown";f.set(R,(f.get(R)??0)+1)}let y=[...f].sort(([v],[R])=>v.localeCompare(R)).map(([v,R])=>`${v}\xD7${R}`).join(", ");console.log(` [owns] ${r([p])} \u2192 ${new Set(g).size} local construct(s) [${y}]`)}for(let[p,g]of[...l].sort(([f],[y])=>f.localeCompare(y))){let f=[...g].sort(([y],[v])=>y.localeCompare(v)).map(([y,v])=>`${y}\xD7${v}`).join(", ");console.log(` [local-control] ${r([p])} \u2014 ${f}; exact decisions are represented below`)}for(let[p,g]of[...d].sort(([f],[y])=>f.localeCompare(y)))for(let f of[...g.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=[...f.outcomes].sort(([R],[N])=>R.localeCompare(N)).flatMap(([R,N])=>[...N].sort().map(F=>`${R} \u2192 ${F}`)).join("; "),v=f.controllerLocation?` @ ${f.controllerLocation.file}:${P(f.controllerLocation.line)}`:"";console.log(` [local-control] ${r([p])}: ${f.controllerLabel} \u2014 ${y}${v}`)}for(let p of[...h.values()].sort((g,f)=>g.ownerLabel.localeCompare(f.ownerLabel)||g.family.localeCompare(f.family)||g.subtype.localeCompare(f.subtype))){let g=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)`:"",f=p.ownerLocation?` @ ${p.ownerLocation.file}:${P(p.ownerLocation.line)}`:"";console.log(` [${p.family}:${p.subtype}; grouped] ${p.ownerLabel} \u2014 ${p.count} proved edge(s)${g}${f}`)}for(let{edge:p,semantic:g}of m){let f={...g.context??{},...g.attributes??{}},y=Object.entries(f).map(([R,N])=>`${R}=${String(N)}`).join(", "),v=p.evidence.find(R=>R.location)?.location;console.log(` [${g.family}:${g.subtype}] ${r([p.fromNodeId])} \u2192 ${r([p.toNodeId])}${y?`; ${y}`:""}${v?` @ ${v.file}:${P(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 ny(e,t){return e==="control"&&Mi(t)||e==="data"&&["argument-to-parameter","constant-to-parameter"].includes(t)||e==="temporal"&&["await-completion-before","awaits-completion","lexical-successor"].includes(t)}function iy(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:re(o?.label??r??n?.label??e),location:o?.location??n?.location??null}}function Mi(e){return["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e)}function oy(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(re(i.get(l.toNodeId)?.label??l.toNodeId)),c.add(l.toNodeId)):d.family==="control"&&Mi(d.subtype)?(r.add(re(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 X(e){return`'${e.replaceAll("'","'\\''")}'`}function ry(e){let t=Jn(e.symbols,o=>o.file),n=Jn(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(Yo),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=>`${re(h.shortName)}@${P(h.startLine)}`).join(", ")+(r.length>c.length?`; +${r.length-c.length}`:""):"none";console.log(` d${o.depth} ${cy(o.kind)} ${o.file} | sym${r.length} hit${s.length} rel${a.length}${l.length>0?`:${l.map(ly).join("/")}`:""} x${d.length} | ${m}`);for(let h of s)console.log(` literal ${h.query}@${P(h.line)} ${h.sourceLine}`)}}function re(e){return e.split(":").at(-1)||e}function sy(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 ay(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=120?t:`${t.slice(0,117)}...`}function jd(e){return e.replace(/^region:(?:apps|packages)\//,"")}function cy(e){return{source:"S",test:"T",entry:"E",barrel:"B",worker:"W"}[e]??e}function ly(e){return{call:"C","contract-symbol":"K",import:"I",reference:"R","runtime-boundary":"B"}[e]??e}function dy(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 Nd(e,t){let n=e.slice(0,t);return`${n.join(", ")}${e.length>n.length?`; ${e.length-n.length} more`:""}`}var Dd=[En({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:w("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>ir(e,{limit:D(t,"limit",30),scope:$(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",agent:{...Qe("How many files reference this symbol, or which symbols have highest fan-in?","exact symbols with referencing-file counts",["symbol"],"bounded","repository",me,bt(["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:w("Graph"),handler:_f},{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:w("Graph"),handler:Wf},{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:w("Graph"),handler:Vf},{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:w("Graph"),handler:Gf},{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:Me(["index-generation","live-workspace"],[J("declared-policy","boundaries","repository-source"),J("dependency-observations","edges","compiler-graph"),J("policy-findings","forbiddenEdges","compiler-graph")]),renderShape:"custom",docs:w("Graph",["scip-query architecture --json"]),handler:Uf},{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:w("Graph"),handler:Bf},{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:w("Graph"),handler:Hf},{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:w("Graph"),handler:Qf},{id:"entrypoints",command:"entrypoints [text]",description:"Find callables where control may enter from outside the indexed call graph",agent:{...Qe("Which detected external roots or entry-surface candidates match this text?","entry symbols with files, confidence, evidence, and indexed caller counts",["pattern"],"complete","repository",me,bt(["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:w("Graph",["scip-query entrypoints","scip-query entrypoints work-session"]),handler:Kf},{id:"entry-map",command:"entry-map <entry>",description:"Map the complete indexed call graph from one detected entry point, collapsed by file",agent:{...Qe("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,me,Mt({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",W,[])]),renderShape:"custom",docs:w("Graph",["scip-query entry-map start","scip-query entry-map start --expand 'file:src/routes.ts' --expand 'file:src/store.ts'"]),handler:zf},{id:"system-map",command:"system-map",hidden:!0,description:"Deprecated compatibility view for collapsed regions and legacy route catalogues; use evidence",agent:Qe("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",me,Mt({rootKinds:["text","symbol","construct","runtime-key"],edgeFamilies:Ge,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",W,[]),u("--symbol <symbol>","Add a symbol anchor; repeat to include several",W,[]),u("--focus-at <file:line>","Focus connected behavior at one exact source location inside a selected construct; repeat to include several",W,[]),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",W,[]),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",W,[]),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",W,[]),u("--frontier <frontier-id>","Expand one accounted topology frontier; repeat to expand several together",W,[]),u("--route <route-id>","Select one proved upstream route; repeat to materialize several routes together",W,[]),u("--gap-callee <name>","Resolve one callee already shown in connected behavior; repeat to batch a named gap",W,[]),u("--selection-term <term>","Deprecated no-op retained for command compatibility; query vocabulary no longer changes graph selection",W,[]),u("--gap-recovery-only","Render only the --gap-callee targets and one exact batched recovery command")]),evidence:"mixed",claims:Me(["index-generation","live-workspace"],[J("matched-anchors","anchors","compiler-graph"),J("typed-relations","regionRelations","repository-source"),J("structural-grouping","regions","heuristic"),J("coverage","coverage","repository-source")]),renderShape:"custom",docs:w("Compatibility"),handler:Jf},mt({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:w("Graph"),query:({db:e,args:t,budget:n})=>Pt(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:ue(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(ae(t,String(n[0])),console.log(`Symbol: ${e.shortName}
235
+ `))},toJson:(e,{db:t,args:n})=>$e(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 uy=ee("complexity",({db:e,args:t,opts:n,budget:i})=>{let o=j(t,0),r=Zr(e,o,{semantic:i.semantic});if(b(n,"json")){I("complexity",t,n,$e(e,o,r,"complexity"),{analysisBudget:i.analysisBudget});return}if(!r)return A.empty(ue(e,o,"Symbol not found."));ae(e,o),console.log(`${_(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
236
+ `),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}`)}),py=Y(({db:e,args:t,opts:n})=>{let i=vs(e,{samples:k(n,"samples",50),scope:$(n,"scope")});if(b(n,"json")){I("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)}%.
237
+ `),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(`
238
+ 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(", ")}`)}}),Md=[{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:w("Health",["scip-query self-audit --samples 100"]),handler:py},{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:w("Health"),handler:uy}];var my=Y(({db:e,args:t,opts:n})=>{let i=j(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=Dr(e,i,{maxDepth:o?Number.MAX_SAFE_INTEGER:r,scope:$(n,"scope")}),a=s.rows;if(b(n,"json")){I("affected",t,n,{...$e(e,i,a,"affected"),coverage:s.coverage});return}if(a.length===0)return A.empty(ue(e,i,"No possible impacts found in the bounded reverse caller/reference closure."));ae(e,i);let c=-1;for(let l of a)l.depth!==c&&(console.log(`
239
+ \u2500\u2500 Depth ${l.depth} \u2500\u2500`),c=l.depth),console.log(` ${l.file} ${l.shortName}`);console.log(`
240
+ ${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(" ")}`)}),hy=ee("co-change",({db:e,args:t,opts:n,budget:i})=>{let o=t[0]===void 0?void 0:j(t,0),r=b(n,"full"),s=Wr(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")){I("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.`);He("co-change candidates"),console.log(o?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
241
+ `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
242
+ `),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.
243
+ `);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 ${gy(a.lastTogetherAt)}`),console.log(` subjects: ${fy(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
244
+ ${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function gy(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function fy(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 yy=ee("change-surface",({db:e,args:t,opts:n,budget:i})=>{let o=Mr(e,j(t,0),{semantic:i.semantic});if(b(n,"json")){I("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` ${fe(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${s}${c}`})}),by=ee("incomplete-migration",({db:e,args:t,opts:n,budget:i})=>{let o=_r(e,{base:$(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")){I("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(`
245
+ No incomplete migrations detected.`);return}He("incomplete migration candidates");for(let r of o.findings){console.log(`
246
+ ${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(`
247
+ ${o.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)}),qd=[{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:w("Impact"),handler:my},{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:w("Impact"),handler:yy},{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)",ke,.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:w("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:by},{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:Me(["index-generation","live-workspace"],[J("historical-pairs","findings[]","change-history"),J("structural-link-classification","findings[].structurallyLinked","compiler-graph")]),renderShape:"custom",docs:w("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:hy}];import{spawn as vy}from"child_process";import{createHash as _i,randomUUID as Sy}from"crypto";import{existsSync as qi,realpathSync as $y}from"fs";import{tmpdir as wy}from"os";import{join as _d,resolve as Nn}from"path";import{fileURLToPath as Ry}from"url";var ht=18,xy=1e3,Cy=2*xy,ky=6,Ey=4,Ty=5,Ay=3,Iy=3,Ly=4,Py=3,jy=3,Ny=8,Fd=3e4,Oy=5e3,Wd=5,Dy=10,My=1,qy=5,Vd=64*1024*1024,Fy={maxItems:64,maxBytes:128*1024*1024,maxItemBytes:Vd,maxBatch:1,responseRetentionMs:6e4};function Gd(e,t,n={},i={}){return By(e,o=>({kind:"source-search",expectedGeneration:o,pattern:t,options:n}),Hy,"search result",i)}function By(e,t,n,i,o){if(!zy(o.allowDefault===!0))return null;try{let r=o.allowDefault===!0&&process.env.SCIP_QUERY_QUERY_SERVICE!=="1",s=r?fo(e):void 0,a=Ae(e,s);if(!qi(a.dbPath))return null;let c=dn(a.dbPath);if(!c||r&&!_y(a,s,c))return null;let l=Vy({projectRoot:a.projectRoot,dbPath:a.dbPath,generationIdentity:c},t(c),n,i);return{result:l.result,generationIdentity:c,observationReceipt:l.observationReceipt}}catch(r){return Hd()&&console.error(`query-service fallback: ${r instanceof Error?r.message:String(r)}`),null}}function _y(e,t,n){if(e.config.watch?.enabled!==!0)return!1;try{return $a(vt({projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:We,gitContext:t}))===n}catch{return!1}}function Ud(e){return _i("sha256").update(cn({kind:"scip-query-service-mailbox",protocolVersion:ht,sessionDir:Nn(e)})).digest("hex")}function Fi(e){let t=_d(e,"server.json");try{let n=JSON.parse(ve(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:Po(i.processIdentity);return i.protocolVersion!==ht||typeof i.sessionIdentity!="string"||i.sessionIdentity!==Ud(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:ht,sessionIdentity:i.sessionIdentity,pid:i.pid,...o?{processIdentity:o}:{},generation:i.generation,heartbeatAtMs:i.heartbeatAtMs}}catch{return null}}function Bi(e,t=Date.now()){if(!Lo(e.pid))return!1;let n=t-e.heartbeatAtMs;if(n>=0&&n<=Cy||!e.processIdentity)return!0;let i=an(e.pid);return i!==null&&sn(e.processIdentity,i)}function Wy(e){let t=e<Dy;return{intervalMs:t?My:Wd,checkServerState:!t||e%qy===0}}function Vy(e,t,n,i){let o=Ky();if(!qi(o))throw new Error("Query service server executable is unavailable.");let r=Math.abs(process.pid)%Yy(t),s=Qy(e,o,r),a=jo(s),c=Date.now(),l=c+Fd,d=lt()+Fd,m=Sy(),h=Gy(m,t),p=No(h),g=Ud(s),f=Oo(a,{mailboxVersion:zn,protocolVersion:ht,id:p,operationKey:h,clientId:m,enqueuedAtMs:c,deadlineAtMs:l,sessionIdentity:g,request:t},{nowMs:c,limits:Fy,durability:"visibility"});Bd(s,e.projectRoot,o,d);let y=0;for(;lt()<=d;){if(qi(f.responsePath))return Uy(ve(f.responsePath,{maxBytes:Vd,inputKind:"query service response"}),{id:p,operationKey:h,clientId:m,deadlineAtMs:f.authoritativeDeadlineAtMs,generation:e.generationIdentity},n,i);let v=Wy(y);if(v.checkServerState){let R=Fi(s);(!R||!Bi(R))&&Bd(s,e.projectRoot,o,d)}Qd(v.intervalMs),y+=1}throw new Error("Persistent query service timed out.")}function Gy(e,t){return _i("sha256").update(cn({namespace:"query-service-v18",payload:{clientId:e,request:t}})).digest("hex")}function Bd(e,t,n,i){let o=Fi(e);if(o&&Bi(o))return;let r=Hd();vy(process.execPath,[n,e,t],{cwd:t,detached:!r,stdio:r?["ignore","ignore","inherit"]:"ignore",env:{...process.env,SCIP_QUERY_QUERY_SERVICE_SERVER:"1"}}).unref();let s=Math.min(i,lt()+Oy);for(;lt()<=s;){let a=Fi(e);if(a&&Bi(a))return;Qd(Wd)}throw new Error("Persistent query service did not become ready within 5s.")}function Uy(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!==zn||r.protocolVersion!==ht||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=ws(r.observationReceipt);if(s.kind!=="supported")throw new Error("Persistent query service returned an invalid observation receipt.");return{ok:!0,protocolVersion:ht,id:t.id,generation:t.generation,result:r.result,observationReceipt:s.receipt}}function Hy(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 Qy(e,t,n){let i=Xy(e.projectRoot),o=_i("sha256").update(cn({protocolVersion:ht,projectRoot:i,dbPath:Nn(e.dbPath),serverPath:Nn(t),lane:n})).digest("hex");return _d(wy(),"scip-query-query-service",o)}function Ky(){return process.env.SCIP_QUERY_QUERY_SERVICE_SERVER_PATH??Ry(new URL("./query-service-server.js",import.meta.url))}function zy(e){let t=process.env.SCIP_QUERY_QUERY_SERVICE;return process.env.SCIP_QUERY_QUERY_SERVICE_SERVER!=="1"&&t!=="0"&&(t==="1"||e)}function Hd(){return process.env.SCIP_QUERY_QUERY_SERVICE_DEBUG==="1"}function Jy(){let e=Number(process.env.SCIP_QUERY_QUERY_SERVICE_POOL_SIZE);return Number.isInteger(e)&&e>=1&&e<=Ny?e:ky}function Yy(e){let t=Jy();return e.kind==="value-flow"?Math.min(t,Py):e.kind==="dependence-slice"?Math.min(t,jy):e.kind==="call-graph"?Math.min(t,Ay):e.kind==="system"?Math.min(t,Ly):e.kind==="reference-reachability"||e.kind==="slice"?Math.min(t,Iy):e.kind==="refs"||e.kind==="trace"||e.kind==="reference-neighborhood"||e.kind==="dataflow"||e.kind==="imports"||e.kind==="unused-imports"?Math.min(t,Ty):e.kind==="imported-by"||e.kind==="hierarchy"||e.kind==="by-kind"||e.kind==="kind-counts"?Math.min(t,Ey):t}function Xy(e){try{return $y.native(e)}catch{return Nn(e)}}function Qd(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Zy(e){let t=b(e,"full"),n=D(e,"limit",12);return t?void 0:n}function Kd(e){return{scope:$(e,"scope"),context:k(e,"context",2),limit:D(e,"limit",6),regexp:b(e,"regexp"),ignoreCase:b(e,"ignoreCase"),ranking:"structural"}}function eb(e){let t=$(e,"view")??"source";if(t!=="source"&&t!=="behavior")throw new Error(`Unknown inspect view: ${t}. Use source or behavior.`);return t}function tb(e){let t=[];for(let o of e.definitions){let r=o.signature?` \u2014 ${o.signature}`:"";o.source?t.push(tt({relativePath:o.relativePath,startLine:o.startLine,source:o.source,sessionPolicy:"exact-unit",headerSuffix:r,ownerSymbol:o.signature??void 0})):t.push(` ${_(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=eu(e.referenceEvidence,o.relativePath,o.line);n.push(` line ${P(o.line)} in ${o.enclosingShort} [${tu(r)}]`),o.source!==void 0&&o.source!==null&&o.sourceStartLine!==void 0&&o.sourceStartLine!==null&&n.push(tt({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:nu(e.claimSupport),skipIfEmpty:!0}]}function eu(e,t,n){return e.find(i=>i.relativePath===t&&i.line===n)?.sourceKind}function tu(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 nu(e){return e?[zd("Reference-absence claims",e.referenceAbsence),zd("Callsite-argument claims",e.callsitePredicates)]:[]}function zd(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(`
248
+ `)}var Wi=["definition","references","callers","callees","dependencies","consumers"],Gi=["search","exact-source","definition","caller","callee","production-reference","test-reference","dependency","consumer"];function Vi(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...Wi];let n=t.filter(i=>!Wi.includes(i));if(n.length>0)throw new Error(`Unknown evidence part: ${n.join(", ")}. Use ${Wi.join(", ")}, or all.`);return[...new Set(t)]}function nb(e){if(e.length===0)return;let t=e.flatMap(i=>i.split(",")).map(i=>i.trim()).filter(Boolean);if(t.includes("all"))return[...Ge];let n=t.filter(i=>!Ge.includes(i));if(n.length>0)throw new Error(`Unknown graph evidence family: ${n.join(", ")}. Use ${Ge.join(", ")}, or all.`);return[...new Set(t)]}function ib(e){if(e!==void 0){if(Yn.includes(e))return e;throw new Error(`Unknown evidence view: ${e}. Use ${Yn.join(", ")}.`)}}function ob(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 rb(e){let t=[...new Set(e.flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean))];return t.length>0?t:void 0}function sb(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||!Gi.includes(o))throw new Error(`Unknown inspect evidence budget '${n}'. Use channel=n with ${Gi.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 ab(e){let t=On(e),n=iu(e,t),i=e.matches.map(h=>lb(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=hb(t),c=n.mode==="complete"?gb(e,t):[],l=e.textCoverage,d=Ui(e),m=n.mode==="bounded"?mb(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 Xe=320,cb=1200;function lb(e,t){let n=t.source.split(`
249
+ `);if(!(n.some(m=>m.length>Xe)||t.source.length>cb)){let m=t.ownerShort?` in ${t.ownerShort}`:"";return{text:tt({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>Xe?1:0,l=` >${String(P(t.focusLine)).padStart(5)} ${db(e,a)}`,d=Math.max(0,n.length-1);return{text:[` ${_(t.relativePath,t.startLine,t.endLine)}${r}`,l,...d>0?[` \u2026[${d} nonfocus context line(s) omitted]`]:[]].join(`
250
+ `),shortenedLines:c,omittedContextLines:d}}function db(e,t){if(t.length<=Xe)return t;let n=ub(e,t);if(n<0){let l=Xe/2,d=t.length-Xe;return`${t.slice(0,l)}\u2026[${d} characters omitted]\u2026${t.slice(-l)}`}let i=e.mode==="literal"?Math.min(e.pattern.length,Xe):1,o=n-Math.floor((Xe-i)/2),r=Math.max(0,Math.min(o,t.length-Xe)),s=r+Xe,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 ub(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 pb(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}:${P(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}:${P(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 Ui(e){let t=e.textCoverage;return!!(t&&t.skippedUnreadablePaths.length===0&&t.skippedOversizedPaths.length===0)}function iu(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 mb(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 ${Re(e.pattern)} --scope ${Re(c.relativePath)}`):[` ${o}: ${a} matching line(s) across ${s.length} file(s); scip-query search ${Re(e.pattern)} --scope ${Re(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 ou(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 On(e){return e.identityManifest??ou(e)}function hb(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?"":` ${P(r.ownerStartLine)}-${P(r.ownerEndLine)}`,c=o.get(s)??{label:r.ownerShort?`${r.ownerShort}${a}`:"<file scope>",lines:[]};c.lines.push(P(r.focusLine)),o.set(s,c)}return[` ${n} [${i[0].fileKind}; ${i.length} match(es)]`,...[...o.values()].flatMap(r=>ru(r.lines,24).map((s,a)=>` ${a===0?r.label:"\u21B3"} @ ${s.join(",")}`))]})}function gb(e,t){let n=new Set(e.matches.map(o=>Jd(o))),i=new Set;for(let o of t){if(n.has(Jd(o)))continue;let r=P(o.ownerStartLine??o.focusLine),s=P(o.ownerEndLine??o.focusLine);i.add(`${o.relativePath}:${r}-${s}`)}return ru([...i],24).map(o=>`scip-query code ${o.map(r=>Re(r)).join(" ")}`)}function Jd(e){return`${e.relativePath}\0${e.focusLine}`}function ru(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function Re(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function fb(e){let t=["scip-query inspect"];for(let i of O(e,"search"))t.push(`--search ${Re(i)}`);for(let i of O(e,"symbol"))t.push(`--symbol ${Re(i)}`);for(let i of O(e,"at"))t.push(`--at ${Re(i)}`);let n=$(e,"scope");return n&&t.push(`--scope ${Re(n)}`),t.push("--view behavior"),t.join(" ")}function yb(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: ${fb(t)}`,"Narrow to smaller exact selectors, or rerun with --allow-large-source only when the omitted syntax itself can change the decision."].join(`
251
+ `))}function bb(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}:${P(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(`
252
+ `))}function vb(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(g=>` ${g.scope}: ${g.returnedMatches}/${g.matchingLines} matching line(s) materialized; ${g.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(`
253
+ `)}),i=e.locations.map(h=>` ${h.matched?"matched":"missing"} ${h.target}`),o=t.map(xb),r=cu(e.bindingClosure),s=(e.omissionGroups??[]).map(Cb),a=Sb(e),c=e.evidence.flatMap(h=>{let p=su(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: ${Rb(l.channels)}.`]:[],...l.omittedUnits>0?[` Withheld materialized units by role: ${wb(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 Sb(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}:${P(r.callsite.line)}${a}`,` ${s.label} \u2014 ${s.file}:${P(s.line)}`)}let o=$b([...(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 ${Re(`${r.file}:${P(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 $b(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}`,n);return[...t.values()]}function wb(e){return Object.entries(e).map(([t,n])=>`${t}=${n}`).join(", ")}function Rb(e){return Gi.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 xb(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${P(a.line)}${a.endLine>a.line?`-${P(a.endLine)}`:""} ${" ".repeat(a.depth)}${a.text}${a.copied?" [verbatim]":""}`),...e.behavior.testCases.length>0?[` related test cases: ${e.behavior.testCases.join("; ")}`]:[],...Yd(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[` ${_(e.relativePath,e.startLine,e.endLine)}${t}`,` roles: ${e.roles.join(", ")}; selected by ${e.reasons.join(", ")}`,Dt({kind:"unit",identity:`inspect-behavior:${e.relativePath}:${e.startLine}:${e.endLine}`,content:s.join(`
254
+ `),label:e.ownerShort??`${e.relativePath}:${P(e.startLine)}`,indent:" "})].join(`
255
+ `)}let n=tt({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=Yd(e.runtimeFacts??[]);return i.length>0?`${n}
256
+ ${i.join(`
257
+ `)}`:n}case"path":return[` ${e.relationship}`,` ${e.roles.join(", ")} edge source was not located. Follow up exactly: ${e.exactFollowup}`].join(`
258
+ `);default:return kb(e)}}function Yd(e){return e.map(t=>{let n=t.keyParts.map(i=>`${i.name}=${i.value}`).join(", ")||"no resolved key";return` runtime L${P(t.line)} [${t.strength}] ${t.action} (${t.role}; ${t.resolution}) ${n}; proof=${t.derivation.rule}`})}function Cb(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}:${P(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(`
259
+ `)}function kb(e){throw new Error(`Unhandled source inspection unit: ${JSON.stringify(e)}`)}function su(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(`
260
+ `),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:
261
+ ${n}`}function Hi(e){if(e.kind!=="matched")return[];let t=e.definition?[tt({relativePath:e.definition.relativePath,startLine:e.definition.startLine,source:e.definition.source,sessionPolicy:"exact-unit",ownerSymbol:e.definition.shortName,headerSuffix:` ${e.definition.shortName}`}),...cu(e.definition.bindingClosure)]:[],n=e.referenceWindows.map(o=>{let r=o.references.map(s=>`${P(s.line)} in ${s.enclosingShort} [${tu(eu(e.referenceEvidence,o.relativePath,s.line))}]`).join(", ");return tt({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=>tt({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:nu(e.claimSupport),skipIfEmpty:!0}]}function Eb(e){if(e.kind!=="graph-packet")return Hi(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=Ge.flatMap(m=>{let h=e.graph.edges.filter(p=>p.family===m);return h.length===0?[]:[` ${m} (${h.length})`,...h.map(p=>` ${Qi(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=Tb(e.graph.folds??[]),s=Ab(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}`,...au(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}]`]}]:Hi(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 Tb(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 Ab(e){let t=au(e.map(o=>o.evidenceStrength)),n=t.length===0?[" No relationships were materialized, so no edge evidence strength is claimed."]:t.map(o=>` ${o}: ${jt[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 au(e){return[...new Set(e)]}function Qi(e){let t=e.context?Object.entries(e.context).filter(([,o])=>o!==void 0).map(([o,r])=>`${o}=${Xd(r)}`):[],n=e.attributes?Object.entries(e.attributes).map(([o,r])=>`${o}=${Xd(r)}`):[],i=[...t,...n];return`[${e.evidenceStrength}] ${Zd(e.from)} -> ${Zd(e.to)} \u2014 ${e.subtype}${i.length>0?`; ${i.join(", ")}`:""}`}function Xd(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}function Zd(e){let t=e.location?` @ ${_(e.location.file,e.location.line,e.location.endLine??e.location.line)}`:"";return`${e.label}${t}`}function cu(e){if(!e)return[];let t=[];for(let n of e.inline)t.push(` inline ${n.name} @ ${_(n.relativePath,n.startLine,n.endLine)}`,` ${n.source??""}`);return t}var Ib=Se("imports",{query:({db:e,args:t,budget:n})=>or(e,j(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)."}),Lb=ee("dataflow",({db:e,args:t,opts:n,budget:i})=>{let o=j(t,0),r=ts(e,o,{semantic:i.semantic});if(b(n,"json")){I("dataflow",t,n,$e(e,o,r,"dataflow"),{analysisBudget:i.analysisBudget});return}if(!r)return A.empty(ue(e,o,"No dataflow found."));if(ae(e,o),console.log(`${r.shortName} (${r.relativePath})
262
+ `),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of r.definitionSites)console.log(` ${s.file}:${P(s.line)}`)}if(r.usageSites.length>0){console.log(`
263
+ \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of r.usageSites)console.log(` ${s.file}:${P(s.line)} in ${s.enclosingShort}`)}if(r.producers.length>0){console.log(`
264
+ \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(`
265
+ \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of r.consumers)console.log(` ${s.file} ${s.shortName}`)}}),Pb=ee("reference-neighborhood",({db:e,args:t,opts:n,budget:i})=>{let o=j(t,0),r=es(e,o,{semantic:i.semantic});if(b(n,"json")){I("reference-neighborhood",t,n,$e(e,o,r,"reference-neighborhood"),{analysisBudget:i.analysisBudget});return}if(!r)return A.empty(ue(e,o,"No reference neighborhood found."));if(ae(e,o),console.log(`${r.shortName} (${r.relativePath})
266
+ `),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINITION \u2550\u2550\u2550");for(let s of r.definitionSites)console.log(` ${s.file}:${P(s.line)}`)}if(r.referenceSites.length>0){console.log(`
267
+ \u2550\u2550\u2550 REFERENCES \u2550\u2550\u2550`);for(let s of r.referenceSites)console.log(` ${s.file}:${P(s.line)} in ${s.enclosingShort}`)}if(r.incomingCalls.length>0){console.log(`
268
+ \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(`
269
+ \u2550\u2550\u2550 OUTGOING CALLS \u2550\u2550\u2550`);for(let s of r.outgoingCalls)console.log(` ${s.file} ${s.shortName}`)}}),jb=Y(({db:e,args:t,opts:n})=>{let i=j(t,0),o=fs(e,{symbols:[i]},{maxDepth:k(n,"depth",2),maxEdges:k(n,"maxEdges",48)});if(b(n,"json")){I("value-flow",t,n,o);return}ae(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=>` ${Qi(r)}`),console.log(`
270
+ Coverage: ${o.coverage.status}; ${o.coverage.basis}.`);for(let r of o.coverage.graph.blindSpots.slice(0,3))console.log(` Blind spot: ${r}`)}),Nb=ee("slice",({db:e,args:t,opts:n,budget:i})=>{let o=j(t,0),r=b(n,"forward")?"forward":"backward",s=is(e,o,{direction:r,maxDepth:k(n,"depth",3),semantic:i.semantic});if(b(n,"json")){I("slice",t,n,$e(e,o,s,"slice"),{analysisBudget:i.analysisBudget});return}if(!s)return A.empty(ue(e,o,"No slice found."));if(ae(e,o),console.log(`${s.direction} slice of ${s.shortName}
271
+ `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}A.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
272
+ ${a.relationship}`),console.log(`
273
+ ${s.connectedSymbols.length} connected symbol(s).`)}),Ob=ee("reference-reachability",({db:e,args:t,opts:n,budget:i})=>{let o=j(t,0),r=b(n,"forward")?"forward":"backward",s=ns(e,o,{direction:r,maxDepth:k(n,"depth",3),semantic:i.semantic});if(b(n,"json")){I("reference-reachability",t,n,$e(e,o,s,"reference-reachability"),{analysisBudget:i.analysisBudget});return}if(!s)return A.empty(ue(e,o,"No reference reachability found."));ae(e,o),console.log(`${s.direction} reference/call reachability from ${s.shortName}
274
+ `),A.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
275
+ ${a.relationship}`),console.log(`
276
+ ${s.connectedSymbols.length} connected symbol(s).`)}),Db=Y(({db:e,args:t,opts:n})=>{let i=j(t,0),o=ys(e,i,{direction:b(n,"forward")?"forward":"backward",maxDepth:k(n,"depth",3),maxEdges:k(n,"maxEdges",200)});if(b(n,"json")){I("dependence-slice",t,n,o);return}console.log(`${o.direction} dependence slice of ${i}
277
+ `),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] ":""}${Qi(r)}`),console.log(`
278
+ 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}`)}),Mb=Y(({db:e,args:t,opts:n})=>{let i=j(t,0),o=zo(e,{className:i});if(b(n,"json")){I("methods",t,n,o,{coverage:qb(o)}),o.kind!=="matched"&&(process.exitCode=1);return}if(o.kind==="matched"){A.list(o.methods,r=>` ${fe(r.startLine,r.endLine)} ${r.name}`);return}A.empty(Fb(o)),process.exitCode=1});function qb(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 Fb(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}:${P(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 lu=[...la,Je({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:w("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>_o(e,j(t,0)),format:e=>e.relativePath}),mt({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",W,[]),u("--symbol <symbol>","Add definition and use evidence for this symbol; repeat for related owners",W,[]),u("--at <file:line>","Add the smallest readable source unit around this location; repeat as needed",W,[]),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",De,6),u("-n, --limit <n>","Set matching lines materialized per search (default 12)",le),u("--max-units <n>","Set the ranked packet unit ceiling (default 48)",le),u("--max-characters <n>","Set the displayed-evidence character ceiling (default 20000)",le),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",le),u("--total-lines <n>","Deprecated compatibility option; inspect no longer has a packet line budget",le),u("--include <part>","Choose symbol evidence; defaults to definition, callers, and callees; repeat or comma-separate",W,[]),u("--evidence-budget <channel=n>","Set an independent unit ceiling for one evidence channel; repeat or comma-separate",W,[]),u("--full","Return all selector matches and materialized units, and run unbounded semantic analysis")],budget:"semantic",agent:{...Qe("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",me,ii(["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:w("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})=>{ti(e.config.projectRoot,"inspect",t.session!==!1);let i=b(t,"full"),o=Ko(e,{searches:O(t,"search"),symbols:O(t,"symbol"),locations:O(t,"at"),scope:$(t,"scope"),context:k(t,"context",6),searchLimit:Zy(t),maxUnits:K(t,"maxUnits"),maxCharacters:K(t,"maxCharacters"),view:eb(t),full:i,unitLines:K(t,"unitLines"),totalLines:K(t,"totalLines"),evidence:{parts:Vi(O(t,"include")),referenceContext:4,relatedSourceLines:60,semantic:n.semantic},evidenceBudgets:sb(O(t,"evidenceBudget"))});return bb(o,t),yb(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:vb}),Dl({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",De,2),u("-n, --limit <n>","Representative source windows to materialize; exact identity manifests remain separately accounted",le,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:{...Qe("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,me,bt(["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:w("Navigation",["scip-query search 'eventName'","scip-query search -- '--config'","scip-query search 'send.*event' --regexp --scope src"]),query:({db:e,args:t,opts:n})=>Wo(e,j(t,0),Kd(n)),precomputed:({args:e,opts:t})=>Gd(ce(),j(e,0),Kd(t)),emptyMessage:e=>e.matchingLines===0?`${Ui(e)?"No current project text line":"No scanned project text line"} matched '${e.pattern}'.`:void 0,coverage:e=>{let t=ou(e).length;return Ui(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:On(e).length,totalMatches:e.matchingLines,omittedMatches:iu(e,On(e)).omitted,materializedSourceWindows:e.matches.length,unmaterializedSourceWindows:e.omittedMatches,matchIdentities:On(e).map(t=>`${t.relativePath}:${P(t.focusLine)}`),scopeHints:e.scopeHints,omittedScopeHints:e.omittedScopeHints,textCoverage:e.textCoverage}),sections:ab}),Ai({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",le,4),u("--full","Analyze every candidate anchor group with semantic enrichment")],agent:Qe("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,me,bt(["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:w("Compatibility"),query:({db:e,args:t,opts:n})=>{let i=Vo(e,j(t,0),{scope:$(n,"scope"),limit:D(n,"limit",4),full:b(n,"full"),semantic:b(n,"full")});return Js(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:P(n.line),matchedTerms:n.matchedTerms})),keyAnchors:t.keyAnchors.map(n=>({file:n.file,line:P(n.line)})),relations:t.relations,systemMapCommand:t.systemMapCommand})),recoveryCommand:e.recoveryCommand}),sections:pb}),{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:w("Navigation"),renderShape:"list",handler:Mb},mt({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[u("--full","Run unbounded semantic analysis on large indexes"),ni()],budget:"semantic",agent:{operation:me,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:qt("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:w("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Ho(e,j(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?ue(t,j(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>ae(t,j(n,0)),toJson:(e,{db:t,args:n})=>({...Ft(t,j(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:tb}),mt({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",W,[]),u("--at <file:line>","Add the construct owning an exact source location; repeat to batch",W,[]),u("--search <literal>","Add an exact source or runtime literal; repeat to batch",W,[]),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",W,[]),u("--direction <direction>","Traverse incoming, outgoing, or both directed relationships"),u("--subtype <subtype>","Select exact relationship subtypes; repeat or comma-separate",W,[]),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",W,[]),u("--depth <n>","Required maximum graph traversal depth",De),u("--max-edges <n>","Required maximum typed relationships to render",le),{...u("--include <part>","Compatibility only: defer requested source parts to an exact inspect recovery command",W,[]),hidden:!0},u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",agent:{operation:me,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:Mt({rootKinds:["text","symbol","construct","runtime-key","state-resource"],edgeFamilies:Ge,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:w("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=ib($(t,"view")),s=nb(O(t,"edge")),a=ob($(t,"direction")),c=rb(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 g=Vi(O(t,"include")),f=[...n,...i],y=g===void 0?null:{parts:g,selectors:f.length,command:["scip-query inspect",...n.map(v=>`--symbol ${Re(v)}`),...i.map(v=>`--at ${Re(v)}`),"--view source",`--include ${Re(g.join(","))}`].join(" ")};return{kind:"graph-packet",graph:Zo(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:Eb}),mt({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",W,[]),u("-C, --context <n>","Source lines before and after each reference",De,2),u("--related-source-lines <n>","Maximum source lines for each caller or callee",le,80),u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",agent:{operation:me,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:ii(["construct","exact-source"],["This compatibility read does not establish graph reachability beyond its rendered evidence."],"deprecated")},docs:w("Compatibility"),query:({db:e,args:t,opts:n,budget:i})=>(ti(e.config.projectRoot,"evidence",n.session!==!1),Qo(e,j(t,0),{parts:Vi(O(n,"include")),referenceContext:k(n,"context",2),relatedSourceLines:k(n,"relatedSourceLines",80),semantic:i.semantic})),emptyMessage:e=>su(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:Hi}),Je({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:w("Navigation"),query:({db:e,args:t})=>Go(e,j(t,0)),format:e=>e.relativePath}),Je({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:w("Navigation"),query:({db:e,args:t})=>Uo(e,j(t,0)),format:e=>e.relativePath}),Ai({id:"system",command:"system <module>",description:"One-hop module summary: matched files, documented symbols, and file reference dependencies",options:[ni()],agent:{operation:me,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:qt("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:w("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>er(e,j(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=>` ${fe(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}`)}]}),Je({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:w("Navigation"),query:({db:e,args:t})=>tr(e,j(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:w("Navigation"),handler:Ib},Je({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:w("Navigation"),query:({db:e,args:t})=>rr(e,j(t,0)),format:e=>` ${e.fromFile}`}),Je({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:w("Navigation"),query:({db:e,args:t})=>ar(e,j(t,0)),format:e=>` ${fe(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>ae(t,j(n,0)),emptyMessage:({db:e,args:t})=>ue(e,j(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>$e(t,j(n,0),e,"members")}),Je({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:w("Navigation"),query:({db:e,args:t,opts:n})=>yr(e,j(t,0),{scope:$(n,"scope"),limit:D(n,"limit",100)}),format:e=>` ${_(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${j(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
279
+ ${e.length} symbol(s)`)}),En({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:w("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>br(e,{scope:$(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Je({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:w("Navigation"),query:({db:e,args:t})=>Sr(e,j(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>ae(t,j(n,0)),emptyMessage:({db:e,args:t})=>ue(e,j(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>$e(t,j(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:w("Navigation"),handler:Lb},{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:w("Navigation"),handler:Pb},{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:w("Navigation"),handler:jb},{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:w("Navigation"),handler:Nb},{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:w("Navigation"),handler:Ob},{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:w("Navigation"),handler:Db}];var Bb=ee("context",({db:e,args:t,opts:n,budget:i})=>{let o=D(n,"limit",20),r=Ae(e.config.projectRoot).gitContext?.headCommit,s=os(e,j(t,0),{semantic:i.semantic,impactDepth:k(n,"impactDepth",3),sliceDepth:k(n,"sliceDepth",3),scope:$(n,"scope"),...r?{gitHead:r}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(b(n,"json")){I("context",t,n,{...Ft(e,j(t,0)),...s},{analysisBudget:i.analysisBudget,coverage:du(s),agentResult:uu(s)});return}return A.empty(ue(e,j(t,0)))}if(b(n,"json")){let c=s.primaryCallable?.symbol??j(t,0);I("context",t,n,s.matched.symbol?{...Ft(e,c),...s}:s,{analysisBudget:i.analysisBudget,coverage:du(s),agentResult:uu(s)});return}s.matched.symbol&&ae(e,s.primaryCallable?.symbol??j(t,0));let a=b(n,"detail")?Wb(s,o):_b(s,j(t,0),o,k(n,"impactDepth",3),k(n,"sliceDepth",3));A.sectionedReport(a)}),pu=[{id:"context",command:"context <target>",description:"Compiler-backed context for a symbol, file, or module",options:Xs([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:Me(["index-generation","live-workspace"],[J("compiler-graph","trace","compiler-graph"),J("semantic-flow","dataflow","semantic-analysis"),J("change-history","history","change-history"),J("planning-notes","warnings[]","heuristic")]),agent:{operation:me,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:qt("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:w("Exploration",["scip-query context parseSymbol"]),handler:Bb}];function _b(e,t,n,i,o){return[{title:"TARGET",rows:hu(e)},{title:"CURRENT FLOW",rows:Vb(e,n),skipIfEmpty:!0},{title:"AFFECTED CONSUMERS",rows:Gb(e,n),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:mu(e,Math.min(n,12)),skipIfEmpty:!0},{title:"CHANGE CONSTRAINTS",rows:Ub(e,n),skipIfEmpty:!0},{title:"RELATED SOURCE IDENTITIES",rows:Hb(e,n),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:gu(e),skipIfEmpty:!0},{title:"COVERAGE AND RECOVERY",rows:Qb(e,t,i,o)}]}function Wb(e,t){return[{title:"TARGET",rows:hu(e)},{title:"DEFINITIONS",rows:fu(e,t),skipIfEmpty:!0},{title:"REFERENCES",rows:Jb(e,t),skipIfEmpty:!0},{title:"CALL GRAPH",rows:yu(e,t),skipIfEmpty:!0},{title:"DATAFLOW",rows:bu(e,t),skipIfEmpty:!0},{title:"SIMILARITY CANDIDATES",rows:mu(e,t),skipIfEmpty:!0},{title:"SOURCE PACKET",rows:gu(e),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:Yb(e,t),skipIfEmpty:!0},{title:"SURFACE",rows:Xb(e,t),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:Zb(e,t),skipIfEmpty:!0},{title:"CHANGE RISK",rows:ev(e,t),skipIfEmpty:!0},{title:"HISTORY",rows:vu(e),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:Su(e),skipIfEmpty:!0}]}function Vb(e,t){return Ee(xe([...fu(e,Math.min(t,12)),...yu(e,t),...bu(e,t)],t))}function Gb(e,t){let n=e.trace.referencedBy.map(o=>` direct ${o.relativePath}:${P(o.line)} ${o.enclosingShort}`),i=e.affected.map(o=>` depth ${o.depth} ${o.file} ${o.shortName}`);return Ee(xe(Kb([...n,...i]),t))}function Ub(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}`,...vu(e),...Su(e)];return Ee(xe(n,t))}function Hb(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)??[],...kt(e).candidates.map(({candidate:i})=>i.fileB)];return Ee(xe([...new Set(n.filter(i=>i.trim().length>0))].map(i=>` ${i}`),Math.min(t,12)))}function Qb(e,t,n,i){let o=kt(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 Kb(e){return[...new Set(e)]}function du(e){return{complete:!1,totalKnown:!1,returned:zb(e)}}function zb(e){let t=kt(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 uu(e){let t=kt(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 mu(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=kt(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 Ee(xe(a,t))}function hu(e){let t=[`Target: ${e.target}`,`Matched: symbol=${Ki(e.matched.symbol)} file=${Ki(e.matched.file)} module=${Ki(e.matched.module)}`];return e.primaryCallable&&t.push(`Primary callable: ${e.primaryCallable.shortName} ${e.primaryCallable.file}`),t}function gu(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)} ${_(n.file,n.startLine,n.endLine)} ${n.shortName}`),t.push(...n.source.split(`
280
+ `).map((i,o)=>{let r=n.startLine+o;return` ${n.focusLines?.includes(r)?">":" "}${String(P(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 fu(e,t){let n=[];for(let i of e.trace.definitions){let o=i.signature?` -- ${i.signature}`:"";n.push(` ${_(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&n.push(...i.source.split(`
281
+ `).map((r,s)=>` ${String(P(i.startLine+s)).padStart(4)} ${r}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${fe(i.startLine,i.endLine)} ${i.shortName}`)),xe(n,t).rows}function Jb(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${P(i.line)} in ${i.enclosingShort}`);return Ee(xe(n,t))}function yu(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 Ee(xe([...n,...i],t))}function bu(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}:${P(r.line)} in ${r.enclosingShort}`);return Ee(xe([...n,...i,...o],t))}function Yb(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 Ee(xe(n,t))}function Xb(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${fe(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return Ee(xe(n,t))}function Zb(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 Ee(xe(n,t))}function ev(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` ${fe(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${o}${s}`}))),e.complexity&&(n.push(` Complexity: ${_(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}`)),Ee(xe(n,t))}function vu(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 Su(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."),kt(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 kt(e){return e.affectedConsumerReuse??{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:0,perConsumerCandidateLimit:0,candidateLimit:0,returnedCandidates:0}}}function xe(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Ee(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function Ki(e){return e?"yes":"no"}import{existsSync as zt}from"fs";import{existsSync as vv,mkdtempSync as Sv,rmSync as $v}from"fs";import{tmpdir as wv}from"os";import{dirname as Yi,join as Rv}from"path";import{performance as Tu}from"perf_hooks";import{spawnSync as xv}from"child_process";import{createHash as Ru,randomUUID as tv}from"crypto";import{closeSync as Dn,createReadStream as nv,existsSync as iv,fsyncSync as ov,mkdirSync as rv,openSync as Ji,renameSync as sv,unlinkSync as av,writeSync as cv}from"fs";import{homedir as lv}from"os";import{dirname as xu,join as zi}from"path";var dv=3e5,uv=256*1024*1024;function Cu(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?zi(t.XDG_CACHE_HOME,"scip-query"):zi(lv(),".cache","scip-query"));return zi(n,e)}var Z=class extends Error{constructor(n,i,o={}){super(i,o.cause===void 0?void 0:{cause:o.cause});this.kind=n;this.name="VerifiedBinaryFetchError"}kind};async function ku(e){let{cachePath:t,url:n,expectedSha256:i}=e,o=e.timeoutMs??dv,r=e.maxBytes??uv,s=e.lockWaitMs??o;pv(o,r,s);let a=mv(n,o,e.signal);try{let c=await $u(t,i,r,a.controller.signal);if(c)return{status:"cached",path:t,sha256:c};rv(xu(t),{recursive:!0});let l=await Bo(`${t}.fetch.lock`,{waitMs:s,pollMs:25,signal:a.controller.signal});if(!l)throw new Z("lock-timeout",`timed out waiting ${s}ms for verified binary cache ownership at ${t}`);try{let d=await $u(t,i,r,a.controller.signal);return d?{status:"cached",path:t,sha256:d}:await hv(e,a.controller,r)}finally{l.release()}}catch(c){throw a.controller.signal.aborted?Et(a.controller.signal,n):c instanceof Z?c:new Z("stream",`failed to download ${n}: ${Eu(c)}`,{cause:c})}finally{clearTimeout(a.timeout),a.detachExternalAbort(),a.controller.signal.aborted||a.controller.abort()}}function pv(e,t,n){if(!Number.isFinite(e)||e<=0)throw new TypeError("timeoutMs must be a positive finite number.");if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("maxBytes must be a positive safe integer.");if(!Number.isFinite(n)||n<0)throw new TypeError("lockWaitMs must be a non-negative finite number.")}function mv(e,t,n){let i=new AbortController,o=()=>{i.abort(new Z("aborted",`download of ${e} was aborted`,{cause:n?.reason}))};n?.addEventListener("abort",o,{once:!0}),n?.aborted&&o();let r=setTimeout(()=>{i.abort(new Z("timeout",`download of ${e} timed out after ${t}ms`))},t);return r.unref(),{controller:i,timeout:r,detachExternalAbort:()=>n?.removeEventListener("abort",o)}}async function $u(e,t,n,i){if(!iv(e))return null;let o=Ru("sha256"),r=0;try{for await(let a of nv(e,{signal:i})){let c=Buffer.isBuffer(a)?a:Buffer.from(a);if(r+=c.length,r>n)return null;o.update(c)}}catch{if(i.aborted)throw Et(i,e);return null}let s=o.digest("hex");return s===t?s:null}async function hv(e,t,n){let i=e.fetchImpl??fetch,o;try{o=await wu(i(e.url,{signal:t.signal}),t.signal)}catch(l){throw t.signal.aborted?Et(t.signal,e.url):new Z("stream",`failed to download ${e.url}: ${Eu(l)}`,{cause:l})}if(!o.ok){let l=new Z("http",`failed to download ${e.url}: HTTP ${o.status}`);throw t.abort(l),l}let r=gv(o,n,e.url);if(!o.body)throw new Z("stream",`downloaded ${e.url} response has no readable body`);let s=`${e.cachePath}.tmp-${process.pid}-${tv()}`,a,c=!1;try{a=Ji(s,"wx",384),c=!0;let l=o.body.getReader(),d=Ru("sha256"),m=0;for(;;){let{done:p,value:g}=await wu(l.read(),t.signal);if(p)break;if(!(g instanceof Uint8Array))throw new Z("stream",`downloaded ${e.url} produced a non-byte stream chunk`);if(m+=g.byteLength,m>n||r!==void 0&&m>r){let y=new Z("length",`downloaded ${e.url} exceeded its ${r??n} byte limit`);throw t.abort(y),y}let f=Buffer.from(g.buffer,g.byteOffset,g.byteLength);d.update(f),bo(a,f,{writeFile:e.writeImpl??cv},"verified binary staging")}if(r!==void 0&&m!==r)throw new Z("length",`downloaded ${e.url} length mismatch: declared ${r} bytes, received ${m}`);let h=d.digest("hex");if(h!==e.expectedSha256)throw new Z("checksum",`downloaded ${e.url} checksum mismatch: expected ${e.expectedSha256}, got ${h}`);Dn(a),a=void 0;try{fv(s,e.cachePath,e.renameImpl??sv,e.syncImpl??ov)}catch(p){throw new Z("install",`failed to install verified binary at ${e.cachePath}`,{cause:p})}return c=!1,{status:"downloaded",path:e.cachePath,sha256:h}}catch(l){throw t.signal.aborted?Et(t.signal,e.url):l instanceof Z?l:new Z("install",`failed to stage verified binary at ${e.cachePath}`,{cause:l})}finally{if(a!==void 0)try{Dn(a)}catch{}if(c)try{av(s)}catch{}}}function gv(e,t,n){let i=e.headers?.get("content-length");if(i==null)return;if(!/^\d+$/.test(i))throw new Z("length",`downloaded ${n} has an invalid Content-Length header`);let o=Number(i);if(!Number.isSafeInteger(o)||o<0)throw new Z("length",`downloaded ${n} has an invalid Content-Length header`);if(o>t)throw new Z("length",`downloaded ${n} declares ${o} bytes, above the ${t} byte limit`);return o}function fv(e,t,n,i){yv(e,i),n(e,t),bv(xu(t),i)}function yv(e,t){let n=Ji(e,"r");try{t(n)}finally{Dn(n)}}function bv(e,t){let n;try{n=Ji(e,"r")}catch(i){if(Qn(i,process.platform))return;throw i}try{t(n)}catch(i){if(!Qn(i,process.platform))throw i}finally{Dn(n)}}function wu(e,t){return t.aborted?Promise.reject(Et(t,"operation")):new Promise((n,i)=>{let o=()=>{t.removeEventListener("abort",o),i(Et(t,"operation"))};t.addEventListener("abort",o,{once:!0}),e.then(r=>{t.removeEventListener("abort",o),n(r)},r=>{t.removeEventListener("abort",o),i(r)})})}function Et(e,t){return e.reason instanceof Error?e.reason:new Z("aborted",`verified binary operation for ${t} was aborted`)}function Eu(e){return e instanceof Error?e.message:String(e)}var Cv=12e4,Lu="v1.8.0",kv=`https://github.com/tlaplus/tlaplus/releases/download/${Lu}/tla2tools.jar`,Ev="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function qn(e){let t=e.spawn??xv,n=Tv(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??Cv,o=Tu.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??[])$v(l,{recursive:!0,force:!0})}let s=Math.round(Tu.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:Av(c,r.stdout??"",r.stderr??""),stdout:r.stdout??"",stderr:r.stderr??""}}function Tv(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"&&Ve(Au(e),t)){let r=Au(e);return Ve(r,t)?{checker:"apalache",command:[r,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:Yi(e.specPath)}:Mn("apalache",`Apalache binary is not available: ${r}`)}let i=Xi(e),o=Ve("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!i)return Mn(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!o)return Mn(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:Yi(e.specPath)};let s=e.metaDir??Sv(Rv(wv(),"scip-tla-tlc-"));return{checker:r,command:["java","-cp",i,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:Yi(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Mn("none",`unknown checker mode: ${n}`)}function Au(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function Xi(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Pu(t)].filter(i=>typeof i=="string"&&i.length>0).find(i=>vv(i))??null}function Pu(e=process.env){return Cu("tla2tools.jar",e)}async function ju(e={}){let t=e.cachePath??Pu(e.env),n=e.expectedSha256??Ev,i=e.version??Lu,o=e.url??kv;return{...await ku({cachePath:t,url:o,expectedSha256:n,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,maxBytes:e.maxBytes,signal:e.signal}),version:i,url:o}}function Av(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=[...Iu(n),...Iu(t)].slice(0,20);return i.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:i.map(o=>({severity:"error",message:o}))}function Iu(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Mn(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as Iv}from"crypto";var Ou=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),Du=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),Mu=new Set(["readFileSync","existsSync","statSync"]),Lv=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,Pv=/^\s*SELECT\b/i;function qu(e){return Lv.test(e)?"write":Pv.test(e)?"read":null}var jv=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function Nv(e,t){let n=e.match(jv);if(!n)return!1;let i=e.slice(n[0].length);return new RegExp(`^${ct(t)}\\b`).test(i)}function Fu(e,t,n,i=[],o=[]){let r=[],s=Mv(e,t,r),a=s.aliases,c=qv(t),l=Fv(t),d=Bv(t),m=Vv(e,t,r),h=Uv(e,t,r);n&&Hv(t,n,o,r);let p=new Map((n?.actions??[]).map(R=>[R.name,R])),g=new Set(m.flatMap(R=>R.referents.map(N=>N.match?.symbol).filter(Boolean))),f=new Set((h?.referents??[]).map(R=>R.match?.symbol).filter(Boolean)),y=Qv(e,t,m,a,c,l,d,g,f,r,p),v=Jv(e,m,a,c,l,d,r,p);return Xv(e,m,r),Zv(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:eo(m.flatMap(R=>R.referents))+eo(s.referents)+eo(h?.referents??[]),staticWrites:y,staticReads:v,waivers:vS(t),checkedInvariants:[...o],traceStepsChecked:i.length,findings:r,findingGroups:Ov(r)}}function Ov(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=Dv(o.severity,n.severity)}return[...t.values()].sort((n,i)=>i.count-n.count||Fn(i.severity)-Fn(n.severity)||n.groupKey.localeCompare(i.groupKey))}function Dv(e,t){return Fn(t)>Fn(e)?t:e}function Fn(e){return e==="error"?2:e==="warning"?1:0}function Mv(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=Wn(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}mS(e,r,l,m,n,c),s.aliases.length===0&&a.add(Co(m.symbol))}for(let l of a)i.push({variable:r,alias:l})}return{aliases:bS(i),referents:o}}function qv(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 Fv(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:Xt(o.pattern,`variables.${n}.statements pattern`)});return t}function Bv(e){let t=[];for(let[n,i]of Object.entries(e.variables))for(let o of i.ormCalls??[]){let{write:r,read:s}=Pi(o);t.push({variable:n,table:o.table,writeMethods:new Set(r),readMethods:new Set(s)})}return t}function _v(e,t,n,i,o,r){return Bu(e,t,(s,a,c)=>gt(e,s,a,c,n,i,o,r))}function Wv(e,t,n,i,o,r){return Bu(e,t,(s,a,c)=>_n(e,s,a,c,n,i,o,r))}function Bu(e,t,n){let i=Pt(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=on(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 Vv(e,t,n){return Object.entries(t.actions).map(([i,o])=>{let r=o.code.map(s=>{let a=ji(s),c="error"in a?s:a.ref,d=Wn(e,c,n,i).match;return d?(hS(e,i,s,d,n),"error"in a||!a.window?{ref:s,match:d}:Gv(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 ${ie(d.symbol)}'s actual span L${d.startLine+1}-L${d.endLine+1} in ${d.relativePath}.`,why:[`${s} resolves to ${ie(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 Gv(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function Uv(e,t,n){let i=t.init;if(!i)return;let o=!!i.waive,r=i.codeRefs.map(s=>{let a=Wn(e,s,n,"Init"),c=a.match;return c?gS(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 Hv(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&&(Nu({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)}),Nu({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 Nu(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 Qv(e,t,n,i,o,r,s,a,c,l,d){let m=[];for(let p of n){let g=[];for(let f of p.referents){if(!f.match)continue;let y=f.window??{startLine:f.match.startLine,endLine:f.match.endLine},v=gt(e,f.match.relativePath,y.startLine,y.endLine,i,o,r,s);g.push(...v),m.push(...v);let R=new Set(p.mapping.writes),N=_v(e,f.match.symbol,i,o,r,s).filter(F=>R.has(F.variable));g.push(...N),m.push(...N)}zv(p,g,l,d.get(p.name))}let h=t.unmappedWriteScope==="actions"?[]:dS(e,t);for(let p of h)for(let g of gt(e,p,0,Number.POSITIVE_INFINITY,i,o,r,s))m.push(g),Kv(g)&&(g.enclosingSymbol&&(a.has(g.enclosingSymbol)||c.has(g.enclosingSymbol))||l.push(Q("unmapped-write","error","static-action",{modelElement:g.variable,codeRef:g.enclosingSymbol??`${g.file}:${g.line+1}`,file:g.file,startLine:g.line,endLine:g.line,message:`Modeled variable ${g.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${g.target} at ${g.file}:${g.line+1}.`,g.enclosingShort?`The write is inside ${g.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 ${g.variable} from the modeled slice if it is intentionally out of scope.`})));return io(m)}function Kv(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function zv(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)&&!Qt(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}${Bn(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)&&!Qt(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}${Bn(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)&&!Qt(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 Jv(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=_n(e,m.match.relativePath,h.startLine,h.endLine,n,i,o,r);d.push(...p),c.push(...p);let g=new Set(l.mapping.reads),f=Wv(e,m.match.symbol,n,i,o,r).filter(y=>g.has(y.variable));d.push(...f),c.push(...f)}Yv(l,d,s,a.get(l.name))}return oo(c)}function Yv(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}${Bn(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)&&!Qt(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}${Bn(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)&&!Qt(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 Xv(e,t,n){for(let i of t){if(i.mapping.calls.length===0)continue;let o=i.mapping.calls.map(s=>Wn(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=Pt(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 ${ie(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 Zv(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=yS(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 gt(e,t,n,i,o,r=[],s=[],a=[]){let c=eS(e,t,n,i,o,r,s,a);return c||cS(e,t,n,i,o,r,s,a)}function _n(e,t,n,i,o,r=[],s=[],a=[]){let c=tS(e,t,n,i,o,r,s,a);return c||lS(e,t,n,i,o,r,s,a)}function eS(e,t,n,i,o,r=[],s=[],a=[]){let c=Kn(e,t);if(!c)return null;let l=[],d=m=>{if(!(m.startPosition.row>i||m.endPosition.row<n)){nS(e,t,m,o,l),_u(e,t,m,r,"write",l),Wu(e,t,m,s,"write",l),Vu(e,t,m,a,"write",l);for(let h of m.children)d(h)}};return d(c.rootNode),io(l)}function tS(e,t,n,i,o,r=[],s=[],a=[]){let c=Kn(e,t);if(!c)return null;let l=[],d=m=>{if(!(m.startPosition.row>i||m.endPosition.row<n)){rS(e,t,m,o,l),_u(e,t,m,r,"read",l),Wu(e,t,m,s,"read",l),Vu(e,t,m,a,"read",l);for(let h of m.children)d(h)}};return d(c.rootNode),oo(l)}function nS(e,t,n,i,o){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let r=n.childForFieldName("left")??n.namedChild(0);r&&Ht(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&&Ht(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&&Ht(e,t,r,"update",i,o);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let r=n.namedChild(0);r&&Ht(e,t,r,"delete",i,o);return}if(n.type==="call_expression"){let r=n.childForFieldName("function")??n.namedChild(0);if(!r||!Uu(r))return;Ht(e,t,r,"mutation-call",i,o)}}}function _u(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?to(s):null;if(!a||!(o==="write"?Du:Mu).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=Be(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?ie(p.symbol):void 0})}}function to(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 Wu(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=iS(a);if(c!==null&&qu(c)===o)for(let l of i){if(!l.regex.test(c))continue;let d=Be(e,t,n.startPosition.row),m=n.childForFieldName("function")??n.namedChild(0),h=(m&&to(m))??"call";r.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${h}(${oS(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?ie(d.symbol):void 0})}}}function iS(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function oS(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function Vu(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?to(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(!Gu(m,a,d,o))continue;let h=Be(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?ie(h.symbol):void 0})}}function Gu(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 rS(e,t,n,i,o){if(!(!sS(n)||aS(n)))for(let r of i){if(n.text!==r.alias)continue;let s=Be(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?ie(s.symbol):void 0})}}function sS(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function aS(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&&Zi(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&&Zi(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&Uu(n)&&Zi(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 Zi(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function Uu(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&Ou.has(t.text))}function Ht(e,t,n,i,o,r){for(let s of o){if(!fS(s.alias,n.text))continue;let a=Be(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?ie(a.symbol):void 0})}}function cS(e,t,n,i,o,r=[],s=[],a=[]){let l=at(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 g of o){if(Nv(p,g.alias))continue;let f=ct(g.alias);if(!new RegExp(`(?:\\b${f}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${f}\\b\\s*\\.\\s*(?:${[...Ou].join("|")})\\s*\\(|\\b${f}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(p))continue;let v=Be(e,t,h);d.push({variable:g.variable,alias:g.alias,file:t,line:h,target:p.trim(),kind:"source-scan",enclosingSymbol:v?.symbol,enclosingShort:v?ie(v.symbol):void 0})}Hu(e,t,h,p,r,Du,d),Qu(e,t,h,p,s,"write",d),Ku(e,t,h,p,a,"write",d)}return io(d)}function lS(e,t,n,i,o,r=[],s=[],a=[]){let l=at(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 g of o){let f=ct(g.alias);if(!new RegExp(`\\b${f}\\b`).test(p)||new RegExp(`\\b${f}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(p))continue;let y=Be(e,t,h);d.push({variable:g.variable,alias:g.alias,file:t,line:h,target:p.trim(),kind:"source-scan",enclosingSymbol:y?.symbol,enclosingShort:y?ie(y.symbol):void 0})}Hu(e,t,h,p,r,Mu,d),Qu(e,t,h,p,s,"read",d),Ku(e,t,h,p,a,"read",d)}return oo(d)}function Hu(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=Be(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?ie(m.symbol):void 0})}}}function Qu(e,t,n,i,o,r,s){if(o.length!==0&&qu(i)===r)for(let a of o){if(!a.regex.test(i))continue;let c=Be(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?ie(c.symbol):void 0})}}function Ku(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(!Gu(d,c,l,r))continue;let m=Be(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?ie(m.symbol):void 0})}}}function dS(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 Wn(e,t,n,i){let o=on(e,t),r=o.match??(t.includes("#")?on(e,t.replace("#","/")).match:null);return o.match&&o.total>1&&!uS(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 ${ie(o.match.symbol)}.`,why:[`${o.total} indexed definitions share this lookup shape.`,pS(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 uS(e){return/[/#:]/.test(e)}function pS(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function mS(e,t,n,i,o,r=!1){let s=no(e,i);if(s===null||SS.has(s)||r)return;let a=ro.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 ${It(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${ie(i.symbol)} with SCIP kind ${It(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function hS(e,t,n,i,o){let r=no(e,i);r===null||zu.has(r)||ro.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 ${ie(i.symbol)} with SCIP kind ${It(r)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function gS(e,t,n,i,o){let r=no(e,n);r===null||zu.has(r)||o||ro.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 ${ie(n.symbol)} with SCIP kind ${It(r)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function no(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function Be(e,t,n){return nn(e,t).filter(o=>o.startLine<=n&&o.endLine>=n).sort((o,r)=>o.endLine-o.startLine-(r.endLine-r.startLine))[0]??null}function fS(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${ct(e)}([^A-Za-z0-9_$]|$)`).test(t)}function yS(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 io(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 oo(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 bS(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 eo(e){return e.filter(t=>t.match).length}function Bn(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function Qt(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function vS(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 ro=new Set(To()),zu=new Set(Eo()),SS=new Set(Ao());function Q(e,t,n,i){let o=JSON.stringify({category:e,evidence:n,...i});return{id:`TLA${Iv("sha1").update(o).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...i}}import{basename as $S,join as wS}from"path";var so=/^[A-Za-z_][A-Za-z0-9_]*$/;function Ju(e,t,n={}){let i=[],o=nn(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=at(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&&so.test(E.leaf)),l=c.map(E=>({variable:E.leaf,alias:E.leaf})),d=l.length>0?gt(e,t,0,Number.POSITIVE_INFINITY,l):[],m=new Set(d.map(E=>E.variable)),h=c.filter(E=>m.has(E.leaf)?!0:CS(s,E)),p=null,g;if(h.length>0)g=o.filter(E=>a(E)&&E.parentTypeName===null);else{if(p=RS(e,t,o,a),!p){let E=o.some(T=>!a(T)&&!T.isTypeLike&&T.parentTypeName!==null&&so.test(T.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,g=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 f=h.map(E=>kS(E,s,t,i,p?.className)),y=f.map(E=>({variable:E.name,alias:E.leaf})),v=[],R=new Set;for(let E of g){let T=gt(e,t,E.startLine,E.endLine,y);if(T.length===0)continue;let V=_n(e,t,E.startLine,E.endLine,y),M=IS(Yu(E.leaf),R);v.push({name:M,leaf:E.leaf,codeRef:xS(t,E,p?.className),startLine:E.startLine,writes:[...new Set(T.map(te=>te.variable))].sort(),reads:[...new Set(V.map(te=>te.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 N=n.moduleName??LS(t),F=n.specDir??wS("specs",N),H=PS(N,f,v,t),L=jS(),q=NS(N,F,t,f,v);return{moduleName:N,file:t,variables:f,actions:v,warnings:i,spec:H,cfg:L,map:q}}function RS(e,t,n,i){let o=new Map;for(let s of n){if(i(s)||s.isTypeLike||s.parentTypeName===null||!so.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 gt(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 xS(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function CS(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function kS(e,t,n,i,o){let r=ES(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=TS(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 ES(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function TS(e,t){let i=t.match(new RegExp(`\\b${ct(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,r=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(i){let l=AS(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 AS(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 Yu(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function IS(e,t){let n=e,i=2;for(;t.has(n);)n=`${e}${i++}`;return t.add(n),n}function LS(e){let n=$S(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return Yu(n||"Model")}function PS(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(`
282
+ `)}function jS(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
283
+ `)}function NS(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)}
284
+ `}function Xu(e,t){let n=Object.keys(t.variables),i=Object.entries(t.actions).map(([o,r])=>{let s=r.code[0]??"",a=s?ko(e,s):null;return{action:o,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:r.writes}});return{recorderSource:OS(n),wiring:i,variables:n}}function OS(e){return`/**
285
+ * Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
286
+ *
287
+ * Usage inside a mapped action (record the model-visible slice around the
288
+ * mutation):
289
+ *
290
+ * import { tlaRecord } from './scip-tla-recorder.js';
291
+ * export function enqueue(job: string) {
292
+ * const before = snapshot();
293
+ * queue.push(job);
294
+ * tlaRecord('Enqueue', before, snapshot());
295
+ * }
296
+ *
297
+ * where snapshot() projects the mapped variables to JSON scalars \u2014 fill in
298
+ * each field with the real runtime value, e.g.
299
+ * const snapshot = () => ({ ${e.map(t=>`${t}: undefined`).join(", ")} }); // fill in each field
300
+ *
301
+ * Recording is enabled only when SCIP_TLA_TRACE names an output path, so the
302
+ * wiring is safe to leave in place. The output is a JSON array compatible
303
+ * with 'scip-query tla trace-check --trace <path>'.
304
+ */
305
+ import { readFileSync, statSync, writeFileSync } from 'node:fs';
306
+
307
+ interface TlaTraceStep {
308
+ action: string;
309
+ before: Record<string, unknown>;
310
+ after: Record<string, unknown>;
311
+ }
312
+
313
+ const tracePath = process.env['SCIP_TLA_TRACE'];
314
+ const TRACE_MAX_BYTES = 16 * 1024 * 1024;
315
+ const TRACE_MAX_STEPS = 100_000;
316
+
317
+ export function tlaRecord(action: string, before: Record<string, unknown>, after: Record<string, unknown>): void {
318
+ if (!tracePath) return;
319
+ let steps: TlaTraceStep[] = [];
320
+ try {
321
+ const size = statSync(tracePath).size;
322
+ if (size > TRACE_MAX_BYTES) throw new Error(\`TLA trace exceeds \${TRACE_MAX_BYTES} bytes\`);
323
+ steps = JSON.parse(readFileSync(tracePath, 'utf8')) as TlaTraceStep[];
324
+ if (!Array.isArray(steps)) steps = [];
325
+ } catch (error) {
326
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
327
+ }
328
+ if (steps.length >= TRACE_MAX_STEPS) throw new Error(\`TLA trace exceeds \${TRACE_MAX_STEPS} steps\`);
329
+ steps.push({ action, before, after });
330
+ const payload = JSON.stringify(steps, null, 2);
331
+ const payloadBytes = Buffer.byteLength(payload);
332
+ if (payloadBytes > TRACE_MAX_BYTES) throw new Error(\`TLA trace would exceed \${TRACE_MAX_BYTES} bytes\`);
333
+ writeFileSync(tracePath, payload);
334
+ }
335
+ `}import{copyFileSync as DS,mkdtempSync as MS,readdirSync as qS,rmSync as FS,writeFileSync as Zu}from"fs";import{tmpdir as BS}from"os";import{basename as _S,dirname as WS,join as Kt}from"path";function Vn(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 VS(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=f=>{let y={};for(let[v,R]of Object.entries(f)){if(!t.includes(v))continue;let N=US(R);N!==void 0&&(y[v]=N)}return y};s.push(c(a));for(let f of n){if(f.before)for(let[y,v]of Object.entries(f.before))y in a||(a[y]=v);Object.assign(a,f.after??{}),s.push(c(a))}let l=t.filter(f=>s.every(y=>f in y)),d=t.filter(f=>!l.includes(f));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(f=>` [${l.map(y=>`${y} |-> ${tp(f[y])}`).join(", ")}]`).join(`,
336
+ `),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(f=>` /\\ ${f} = TraceStates[1].${f}`),"","TraceStep =="," /\\ traceIdx < Len(TraceStates)"," /\\ traceIdx' = traceIdx + 1",` /\\ ${i}`,...l.map(f=>` /\\ ${f}' = TraceStates[traceIdx + 1].${f}`),"","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(`
337
+ `),g=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
338
+ `);return{moduleName:m,moduleText:p,cfgText:g,variables:l,skippedVariables:d,states:s.length,warnings:o}}function ep(e){let t=e.mappedActions??[],n=VS(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:Vn(t,[])};let i=MS(Kt(BS(),"scip-tla-trace-"));try{let o=WS(e.specPath);for(let d of qS(o))d.endsWith(".tla")&&DS(Kt(o,d),Kt(i,d));let r=Kt(i,`${n.moduleName}.tla`),s=Kt(i,`${n.moduleName}.cfg`);Zu(r,n.moduleText),Zu(s,n.cfgText);let a=qn({...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:Vn(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:Vn(t,e.steps)};let c=GS(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:Vn(t,l)}}finally{FS(i,{recursive:!0,force:!0})}}function GS(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 US(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 tp(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>tp(t)).join(", ")}>>`}function np(e){return _S(e).replace(/\.tla$/i,"")}import{mkdirSync as op,writeFileSync as rp}from"fs";import{dirname as HS,join as Tt}from"path";var QS=async(...e)=>{let{args:t,opts:n}=ca(e),i=j(t,0);if(i==="fetch-tools"){let r=await ju();if(b(n,"json")){I("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=U(t,1);if(!r)throw new Error("tla scaffold requires a target source file");Ce(s=>KS(s,t,n,r));return}if(i==="instrument"){let r=U(t,1);Ce(s=>zS(s,t,n,r));return}if(i==="trace-check"){let r=U(t,1);if(!r)throw new Error("tla trace-check requires a spec path");Ce(s=>JS(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=U(t,1);if(!o)throw new Error("tla verify requires a spec path");Ce(r=>ZS(r,t,n,o))};function KS(e,t,n,i){let o=e.config.projectRoot,r=Ju(e,i,{moduleName:$(n,"moduleName"),specDir:$(n,"out")}),s=$(n,"out")??Tt("specs",r.moduleName),a=we(o,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=b(n,"force"),l=[{path:Tt(a,`${r.moduleName}.tla`),body:r.spec},{path:Tt(a,`${r.moduleName}.cfg`),body:r.cfg},{path:Tt(a,`${r.moduleName}.scip-tla.json`),body:r.map}];for(let d of l)if(!c&&zt(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);op(a,{recursive:!0});for(let d of l)rp(d.path,d.body);if(b(n,"json")){I("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 ${Tt(s,`${r.moduleName}.tla`)}'.`)}function zS(e,t,n,i){let o=e.config.projectRoot,r=$(n,"map")??(i?Ln(i):void 0);if(!r)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=In(o,r);if(!s.loaded)throw new Error(s.errors.join(`
339
+ `));let{contract:a,mapDir:c}=s.loaded,l=Xu(e,a),d=$(n,"out")??Tt(c,"scip-tla-recorder.ts"),m=we(o,d);if(!m)throw new Error(`instrument output escapes the project root: ${d}`);if(!b(n,"force")&&zt(m))throw new Error(`refusing to overwrite ${m} (pass --force to replace the recorder)`);if(op(HS(m),{recursive:!0}),rp(m,l.recorderSource),b(n,"json")){I("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 JS(e,t,n,i){let o=e.config.projectRoot,r=we(o,i);if(!r||!zt(r))throw new Error(`TLA+ spec not found: ${i}`);let s=$(n,"map")??Ln(i),a=In(o,s);if(!a.loaded)throw new Error(a.errors.join(`
340
+ `));let{contract:c}=a.loaded,l=O(n,"trace"),m=Oi(o,[...c.traces,...l]).flatMap(g=>Ni(o,g).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=ep({specPath:r,baseModuleName:np(r),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:m,nextOperator:$(n,"next"),toolOptions:{projectRoot:o,tlaToolsJar:$(n,"tlaTools"),timeoutMs:K(n,"timeoutMs")}}),p=h.status==="accepted"||h.status==="unavailable"&&b(n,"allowUnknown")?0:1;if(b(n,"json")){I("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 g of h.generation.warnings)console.log(`WARNING: ${g}`)}console.log(`${h.status.toUpperCase()}: ${h.detail}`),b(n,"coverage")&&YS(h.actionCoverage),process.exitCode=p}function YS(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 XS(e,t,n,i){let o=$(i,"map");if(o)return{mapArg:o};let r=Ln(t),s=we(e,r);if(s&&zt(s))return{mapArg:r};let a=Zl(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 ZS(e,t,n,i){let o=e.config.projectRoot,r=we(o,i);if(!r||!zt(r))throw new Error(`TLA+ spec not found: ${i}`);let{mapArg:s,mappingDiscoveredBy:a}=XS(o,i,r,n),c=In(o,s);if(!c.loaded)throw new Error(c.errors.join(`
341
+ `));let{contract:l,mapPath:d,mapDir:m}=c.loaded,h=$(n,"config")??l.config,p=Kl(o,m,h),g=t$($(n,"checker")??"auto"),f=$(n,"tlaTools"),y=e$(o,i,r,f)??zl(o,i),v=Yl(p),R=O(n,"trace"),F=Oi(o,[...l.traces,...R]).map(M=>({tracePath:M,...Ni(o,M)})),H=F.flatMap(M=>M.steps),L=new Set(R),q=F.filter(M=>L.has(M.tracePath)).flatMap(M=>M.errors),E=Fu(e,l,y,H,v);for(let M of[...c.errors,...q])E.findings.push({id:`TLA-CONTRACT-${E.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:M,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 T=qn({projectRoot:o,specPath:r,configPath:p??void 0,checker:g,tlaToolsJar:f,apalacheBin:$(n,"apalache"),length:k(n,"length",10),timeoutMs:K(n,"timeoutMs")});T.status==="skipped"&&g!=="none"&&E.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:T.diagnostics.map(M=>M.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 V={operation:"verify",specPath:r,mapPath:d,...a?{mappingDiscoveredBy:a}:{},...p?{configPath:p}:{},checker:T,conformance:E,exitCode:n$(T,E,b(n,"allowUnknown"))};if(b(n,"json")){I("tla",t,n,V),process.exitCode=V.exitCode;return}i$(V,b(n,"full")),process.exitCode=V.exitCode}function e$(e,t,n,i){let o=Xi({projectRoot:e,specPath:n,tlaToolsJar:i,checker:"sany"});if(!o)return null;let r=ql({specPath:n,jarPath:o});return r?Jl(e,t,r):null}var sp=[{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:he("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)",le),u("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",W,[]),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:w("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:QS}];function t$(e){if(!Ql(e))throw new Error(`unknown checker mode: ${e}`);return e}function n$(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 ip=3;function i$(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=r$(e);console.log(`
342
+ 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 s$(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)ap(r);return}o$(e.conformance)}function o$(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
343
+ Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
344
+ [${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let o of n.findingIds.slice(0,ip)){let r=t.get(o);r&&ap(r)}let i=n.count-ip;i>0&&console.log(` ... and ${i} more in this group (use --full to show all)`)}}function r$(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 s$(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 ap(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${_(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
345
+ [${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 cp=["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"],a$=[Ld,lu,Dd,jn,qd,pu,sp,Md],lp=a$.flat(),c$=new Map(lp.map(e=>[e.id,e]));for(let e of lp)if(!cp.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var dp=cp.map(e=>l$(e));function l$(e){let t=c$.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var wE=[Ys,{id:"hook-architecture-stop",command:"hook-architecture-stop",hidden:!0,agent:he("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:ll},{id:"reindex",command:"reindex",agent:he("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)",W,[]),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("--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",le)]),renderShape:"custom",docs:w("Indexing",["scip-query reindex"]),handler:dl},{id:"augment-sources",command:"augment-sources",agent:he("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:w("Indexing"),handler:ul},{id:"augment-vue",command:"augment-vue",agent:he("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:w("Indexing"),handler:pl},...dp,{id:Ot,command:Ot,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:ml},{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:Me(["index-generation","live-workspace"],[J("changed-files","changedFiles[]","repository-source"),J("changed-symbols","changedSymbols[]","compiler-graph"),J("downstream-consumers","affected[]","compiler-graph")]),renderShape:"custom",docs:w("Impact"),handler:hl},{id:Nt,command:Nt,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:gl},{id:"health",command:"health",agent:he("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:Me(["index-generation","live-workspace","process"],[ea("actions","actions[]","evidence",{"graph-fact":"compiler-graph",heuristic:"heuristic","change-graph":"change-history"}),J("coverage-notes","coverage","repository-source")]),renderShape:"custom",docs:w("Health",["scip-query health --json","scip-query health --baseline"]),handler:fl},{id:"install-skills",command:"install-skills",agent:he("Which scip-query skills were installed, updated, skipped, or conflicted?","skill target paths and install outcomes",[],"complete","repository",z("mutation")),description:`Install skills (${Aa.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:w("Maintenance"),handler:yl},{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:w("Maintenance"),handler:bl},{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:w("Maintenance"),handler:vl},{id:"init",command:"init",agent:he("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:w("Maintenance"),handler:Sl},{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:Zs("repository-source",["live-workspace"]),renderShape:"custom",docs:w("Maintenance",["scip-query config-validate"]),handler:$l},{id:"suppress",command:"suppress <id>",agent:he("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",W,[]),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:w("Maintenance"),handler:wl},{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:w("Maintenance"),handler:Rl},{id:"setup",command:"setup",agent:he("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:w("Maintenance",["scip-query setup","scip-query setup --health","scip-query setup --install-missing","scip-query setup --json"]),handler:kl},{id:"setup-agent",command:"setup-agent",agent:he("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:w("Maintenance",["scip-query setup-agent"]),handler:Cl},{id:"uninstall",command:"uninstall",agent:he("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:w("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:El},{id:"watch",command:"watch",agent:he("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",De),u("--cooldown <ms>","Minimum milliseconds between indexes",De),u("--git-poll <ms>","Milliseconds between Git state checks",De),u("--idle-timeout <ms>","Milliseconds before a clean idle daemon exits",De)]),renderShape:"custom",docs:w("Maintenance"),handler:Tl},{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:w("Maintenance"),handler:Ll}];export{wE as commandDescriptors};
346
+ //# sourceMappingURL=command-descriptors-QH3G2OVD.js.map