codebaseiq 0.1.0 → 0.2.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 (422) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/dist/augment-vue-worker.js +1 -1
  3. package/dist/{chunk-DQMDCD24.js → chunk-27PHVDKL.js} +2 -2
  4. package/dist/{chunk-ZMI2JSX2.js → chunk-2DMVFAY7.js} +2 -2
  5. package/dist/{chunk-5PUWMSDU.js → chunk-2E6BTWER.js} +2 -2
  6. package/dist/{chunk-YESXMKX3.js → chunk-2F5ERMNI.js} +2 -2
  7. package/dist/chunk-2VKB5CMA.js +60 -0
  8. package/dist/{chunk-NNJ2KZZG.js → chunk-327YK6TB.js} +4 -4
  9. package/dist/chunk-347TXATM.js +2 -0
  10. package/dist/{chunk-VEXUL62T.js → chunk-35YYZD3D.js} +2 -2
  11. package/dist/chunk-36WRYYTE.js +3 -0
  12. package/dist/chunk-37TKC6MB.js +2 -0
  13. package/dist/{chunk-FAJQ7LWY.js → chunk-3AC56WAR.js} +2 -2
  14. package/dist/{chunk-JE3WZ6II.js → chunk-3NUZVLR7.js} +2 -2
  15. package/dist/{chunk-UZGZB3VB.js → chunk-3XFJUWJE.js} +2 -2
  16. package/dist/{chunk-OVTS4DKB.js → chunk-4AOOSCZ7.js} +2 -2
  17. package/dist/{chunk-LU3BMVH2.js → chunk-4IFISPQW.js} +2 -2
  18. package/dist/chunk-4NHWNAWQ.js +11 -0
  19. package/dist/chunk-4O52YNKL.js +5 -0
  20. package/dist/{chunk-HPJRBHVT.js → chunk-54K6556S.js} +2 -2
  21. package/dist/{chunk-HRWGYWRJ.js → chunk-57GCCPLS.js} +2 -2
  22. package/dist/{chunk-J77SU6VA.js → chunk-57KEZDPT.js} +2 -2
  23. package/dist/{chunk-OFBE4NGP.js → chunk-57KFVPVZ.js} +2 -2
  24. package/dist/{chunk-WOQBZPIF.js → chunk-5BDK6QC3.js} +2 -2
  25. package/dist/{chunk-7MGU3HPH.js → chunk-5IO2APSS.js} +2 -2
  26. package/dist/chunk-5NJPH3QZ.js +61 -0
  27. package/dist/{chunk-GW6Z3WGY.js → chunk-5WXOEJ4G.js} +2 -2
  28. package/dist/chunk-5XEVXVTK.js +3 -0
  29. package/dist/{chunk-RR7SX44N.js → chunk-6OVNYYY4.js} +2 -2
  30. package/dist/{chunk-ZV3JV5G5.js → chunk-6SDEQTVY.js} +2 -2
  31. package/dist/{chunk-EF2R3WNQ.js → chunk-6URCE5QY.js} +2 -2
  32. package/dist/{chunk-UCD3H3UZ.js → chunk-6ZV5EDUT.js} +2 -2
  33. package/dist/{chunk-C6SBF2WH.js → chunk-77GHPR2R.js} +2 -2
  34. package/dist/{chunk-YVCIMIOC.js → chunk-7R64XY4Y.js} +2 -2
  35. package/dist/{chunk-VXYS3FZD.js → chunk-7Z7HCZ7J.js} +2 -2
  36. package/dist/{chunk-CO5R3UNA.js → chunk-A67HT5FR.js} +2 -2
  37. package/dist/{chunk-UDS562V4.js → chunk-A7XQT7MH.js} +2 -2
  38. package/dist/{chunk-RDBI2RXU.js → chunk-ACZDU5GK.js} +2 -2
  39. package/dist/{chunk-FETNQCFO.js → chunk-AM5SUGHF.js} +2 -2
  40. package/dist/{chunk-NNOKTMZT.js → chunk-B2E3HZ2A.js} +2 -2
  41. package/dist/{chunk-CVYSU6BX.js → chunk-BH5CE4LN.js} +2 -2
  42. package/dist/chunk-BLKYYQ7C.js +543 -0
  43. package/dist/{chunk-4WKDMDEW.js → chunk-BX2U3QQV.js} +2 -2
  44. package/dist/{chunk-ZKX2FRS6.js → chunk-CANBLFVQ.js} +2 -2
  45. package/dist/{chunk-SMRBZ6EC.js → chunk-CCRZLRWJ.js} +2 -2
  46. package/dist/chunk-CDWSLAPN.js +21 -0
  47. package/dist/chunk-CIVYHK7U.js +22 -0
  48. package/dist/{chunk-L57ZKWVG.js → chunk-CMXW7MFV.js} +2 -2
  49. package/dist/{chunk-T3DGWPXM.js → chunk-CSZOQ7YO.js} +2 -2
  50. package/dist/{chunk-ZZXSWSN6.js → chunk-CWMHWD56.js} +2 -2
  51. package/dist/{chunk-6NW7MU72.js → chunk-CZEIHYMP.js} +2 -2
  52. package/dist/{chunk-DO6WQD2T.js → chunk-D62CTZX6.js} +2 -2
  53. package/dist/{chunk-XWUOUWYI.js → chunk-DFPAZXLU.js} +2 -2
  54. package/dist/{chunk-MOVBWNIP.js → chunk-DKJXK3HA.js} +2 -2
  55. package/dist/{chunk-XMQ23E27.js → chunk-DLC6JDN7.js} +2 -2
  56. package/dist/chunk-DUKHVPU5.js +4 -0
  57. package/dist/{chunk-ID63777H.js → chunk-DVYG3JTA.js} +2 -2
  58. package/dist/{chunk-NE6IU5ZD.js → chunk-EFFMFK7C.js} +2 -2
  59. package/dist/{chunk-I2T2LLK2.js → chunk-EM5UHLAM.js} +2 -2
  60. package/dist/chunk-EN4AHLL3.js +3 -0
  61. package/dist/chunk-EXMVF3JR.js +3 -0
  62. package/dist/{chunk-SWHMHUKF.js → chunk-FEBLLMTL.js} +2 -2
  63. package/dist/chunk-FIXYHQ3W.js +3 -0
  64. package/dist/{chunk-RKEJ6VTF.js → chunk-FLLXYUOL.js} +2 -2
  65. package/dist/{chunk-KWVHSKHK.js → chunk-FPDL2TUB.js} +2 -2
  66. package/dist/chunk-FQA3KIFX.js +17 -0
  67. package/dist/chunk-FWY2PRIF.js +3 -0
  68. package/dist/chunk-FY5V4V4F.js +2 -0
  69. package/dist/chunk-G2XUZCF2.js +88 -0
  70. package/dist/{chunk-QHRNXP3C.js → chunk-GXVDTHFC.js} +2 -2
  71. package/dist/{chunk-6MUIJMVL.js → chunk-H3CKAL6P.js} +2 -2
  72. package/dist/chunk-H5QXP63L.js +2 -0
  73. package/dist/{chunk-VUIYB2V3.js → chunk-HBQGKMM3.js} +2 -2
  74. package/dist/{chunk-PYAB5SM6.js → chunk-HBXZAGY6.js} +2 -2
  75. package/dist/{chunk-NNO6A2PO.js → chunk-HCMQZPEO.js} +2 -2
  76. package/dist/{chunk-Q65CQ4XL.js → chunk-HHBBGWES.js} +2 -2
  77. package/dist/{chunk-GTXSJDCO.js → chunk-HIEXRDJF.js} +2 -2
  78. package/dist/{chunk-4FC325IF.js → chunk-HYKSLTAR.js} +2 -2
  79. package/dist/{chunk-XLQ3GLWZ.js → chunk-I2KP4AGR.js} +2 -2
  80. package/dist/chunk-I5FCDTK2.js +2 -0
  81. package/dist/{chunk-QKPLA6IC.js → chunk-I645ZF75.js} +2 -2
  82. package/dist/{chunk-FDGD5AB5.js → chunk-IBM3F2BJ.js} +2 -2
  83. package/dist/{chunk-Q72QSKXC.js → chunk-IEL6Q5W3.js} +38 -38
  84. package/dist/{chunk-NCZUNH3E.js → chunk-IGQQUENU.js} +12 -12
  85. package/dist/chunk-IGYAZPRX.js +4 -0
  86. package/dist/chunk-IOVPAZWP.js +3 -0
  87. package/dist/{chunk-OL6KJP3N.js → chunk-IVJJNVSX.js} +2 -2
  88. package/dist/{chunk-AKB7V7TV.js → chunk-IWAMYGPN.js} +2 -2
  89. package/dist/chunk-IYBIBMPF.js +90 -0
  90. package/dist/{chunk-IOP6FWIM.js → chunk-J24VICI5.js} +2 -2
  91. package/dist/{chunk-C7QOQX32.js → chunk-JN5LIBT3.js} +2 -2
  92. package/dist/{chunk-O6QTXQPJ.js → chunk-JOALNFY3.js} +2 -2
  93. package/dist/{chunk-GCHRX4YW.js → chunk-JUO3Z644.js} +2 -2
  94. package/dist/{chunk-BJ6SQAEN.js → chunk-JXHLB7TP.js} +2 -2
  95. package/dist/{chunk-IJ4HMYBE.js → chunk-JYX5UZSZ.js} +2 -2
  96. package/dist/chunk-K2O7SBAU.js +2 -0
  97. package/dist/{chunk-OLF4MA5W.js → chunk-K5G7SPAG.js} +2 -2
  98. package/dist/{chunk-YSNONTJ2.js → chunk-KDYQQJ6X.js} +2 -2
  99. package/dist/{chunk-7NVGT435.js → chunk-KM4QRWI5.js} +2 -2
  100. package/dist/{chunk-HKQUXIFO.js → chunk-KNV5VFDV.js} +2 -2
  101. package/dist/chunk-L3YSDLNB.js +2 -0
  102. package/dist/{chunk-EZNMUY67.js → chunk-LAGDJXFY.js} +2 -2
  103. package/dist/{chunk-ENCCHKM6.js → chunk-LY2NB5XR.js} +4 -4
  104. package/dist/chunk-M4EVGA5S.js +14 -0
  105. package/dist/chunk-M7LAIM77.js +127 -0
  106. package/dist/{chunk-BVAJLC5A.js → chunk-MRGTCMDK.js} +2 -2
  107. package/dist/{chunk-OZYRSMSH.js → chunk-MT5W4DUG.js} +2 -2
  108. package/dist/{chunk-VE5AVNMP.js → chunk-MTMF4N7F.js} +2 -2
  109. package/dist/chunk-N3Q3AWGW.js +545 -0
  110. package/dist/{chunk-TXXOEMZJ.js → chunk-NDGTJHQN.js} +2 -2
  111. package/dist/chunk-NIO346UL.js +2 -0
  112. package/dist/chunk-NJA4MMBD.js +2 -0
  113. package/dist/{chunk-7FND7D7N.js → chunk-NK76RSB6.js} +2 -2
  114. package/dist/{chunk-H3LGFZVK.js → chunk-NTRW52UR.js} +2 -2
  115. package/dist/{chunk-JOIRNPPY.js → chunk-OJFLPVBP.js} +2 -2
  116. package/dist/{chunk-KMITESMT.js → chunk-OMBRP7BB.js} +2 -2
  117. package/dist/{chunk-UP3BUZR5.js → chunk-OVKZM2XI.js} +2 -2
  118. package/dist/{chunk-MVB3DAEY.js → chunk-PARCKE3Q.js} +2 -2
  119. package/dist/{chunk-CAUCPUOF.js → chunk-PFPHS4NO.js} +2 -2
  120. package/dist/chunk-PHPQ24UG.js +22 -0
  121. package/dist/chunk-PLZXWZHY.js +77 -0
  122. package/dist/{chunk-34WBMAYK.js → chunk-PNVZIJ57.js} +2 -2
  123. package/dist/{chunk-SYDJMPES.js → chunk-QKVTWODE.js} +2 -2
  124. package/dist/{chunk-FW53T7EB.js → chunk-QLTFXVUI.js} +2 -2
  125. package/dist/{chunk-PBI2LFKH.js → chunk-QMGWSEPL.js} +2 -2
  126. package/dist/{chunk-CQP3THUZ.js → chunk-QVHZB75Z.js} +2 -2
  127. package/dist/{chunk-6BQ3DSPK.js → chunk-QVWDQTMG.js} +2 -2
  128. package/dist/{chunk-ST7V3SKN.js → chunk-RCPZOPV6.js} +2 -2
  129. package/dist/chunk-RJWAB4VR.js +345 -0
  130. package/dist/chunk-RRPK327J.js +20 -0
  131. package/dist/chunk-RVYLJDXC.js +21 -0
  132. package/dist/chunk-RWKEXCHU.js +3 -0
  133. package/dist/{chunk-L4NRUAGJ.js → chunk-S5SKXCND.js} +2 -2
  134. package/dist/{chunk-RBAS5ZHI.js → chunk-S64NCE2Z.js} +2 -2
  135. package/dist/{chunk-WMPRTGH2.js → chunk-SF34QLK2.js} +2 -2
  136. package/dist/{chunk-ANFVSJWQ.js → chunk-SJZQ2PTZ.js} +2 -2
  137. package/dist/{chunk-4XTAUQFD.js → chunk-SRY26ITJ.js} +2 -2
  138. package/dist/chunk-SV2LEFVM.js +2 -0
  139. package/dist/{chunk-7XAN6GKB.js → chunk-T3YFIJ5P.js} +2 -2
  140. package/dist/chunk-T55YPJGB.js +3 -0
  141. package/dist/chunk-TAJ6UGCO.js +21 -0
  142. package/dist/{chunk-PIOMTC27.js → chunk-TUTSO7UZ.js} +2 -2
  143. package/dist/{chunk-FQKZWM4L.js → chunk-U24M5RQM.js} +5 -5
  144. package/dist/{chunk-XME3HPXZ.js → chunk-U2XX3BT4.js} +2 -2
  145. package/dist/{chunk-SZD2KF7Q.js → chunk-UWB5WMC2.js} +2 -2
  146. package/dist/{chunk-6CS3UQTN.js → chunk-VCL7FK3E.js} +2 -2
  147. package/dist/{chunk-N3IQCBCF.js → chunk-VCWAJPXQ.js} +2 -2
  148. package/dist/{chunk-LZYFLFEH.js → chunk-VG55NFXF.js} +2 -2
  149. package/dist/{chunk-PTAWHLVJ.js → chunk-VLTUX4IF.js} +2 -2
  150. package/dist/{chunk-JEJLSICM.js → chunk-VVCBMH5O.js} +2 -2
  151. package/dist/{chunk-JSOYNVWH.js → chunk-VYZQZ4ZN.js} +2 -2
  152. package/dist/chunk-W3FK73MD.js +8 -0
  153. package/dist/{chunk-UNBY47BC.js → chunk-W6C6QTXJ.js} +2 -2
  154. package/dist/chunk-WH5SYOMD.js +2 -0
  155. package/dist/chunk-WJOQC4P7.js +7 -0
  156. package/dist/chunk-WO47BIPY.js +3 -0
  157. package/dist/chunk-WOOTEWQT.js +239 -0
  158. package/dist/{chunk-UBGWN7I4.js → chunk-X5I2BQGX.js} +2 -2
  159. package/dist/{chunk-PX4RYAAK.js → chunk-XNUWRTYM.js} +2 -2
  160. package/dist/{chunk-ICFDQHAM.js → chunk-XUJM6474.js} +2 -2
  161. package/dist/chunk-XYLV727H.js +21 -0
  162. package/dist/{chunk-TRRC4ZJ7.js → chunk-YFQPWKHR.js} +2 -2
  163. package/dist/{chunk-NEDP5RFQ.js → chunk-YIOQJ45A.js} +2 -2
  164. package/dist/{chunk-Y6KHROC3.js → chunk-YXJ4IAHH.js} +2 -2
  165. package/dist/chunk-YYFV32WR.js +3 -0
  166. package/dist/{chunk-BH5F2Q4O.js → chunk-ZB3V5QM7.js} +2 -2
  167. package/dist/chunk-ZJZQ7Q2Q.js +3 -0
  168. package/dist/{chunk-EMNIHCRB.js → chunk-ZNQCR656.js} +2 -2
  169. package/dist/{chunk-TIIC3ZE7.js → chunk-ZOEDRCR4.js} +2 -2
  170. package/dist/cli-context-TSADTXLB.js +2 -0
  171. package/dist/cli-context-XEPPF4RX.js +3 -0
  172. package/dist/cli-program-KJGQEM72.js +7 -0
  173. package/dist/cli.js +1 -1
  174. package/dist/{code-DlqpBDd0.d.ts → code-CDe-mIjx.d.ts} +1 -1
  175. package/dist/code-viewer-YGDON6SY.js +12 -0
  176. package/dist/code-viewer-ZCTHXQ5C.js +11 -0
  177. package/dist/command-descriptors-5VAB2MZX.js +335 -0
  178. package/dist/command-descriptors-EAHKIRAG.js +337 -0
  179. package/dist/{config-types-BNoC96J3.d.ts → config-types-D6X5S68_.d.ts} +50 -0
  180. package/dist/{db-D7sauVFH.d.ts → db-DmRNdCtm.d.ts} +1 -1
  181. package/dist/direct-navigation-B3SGOOBW.js +2 -0
  182. package/dist/direct-navigation-ZL362KXF.js +3 -0
  183. package/dist/{graph-evidence-BIFqyisO.d.ts → graph-evidence-Bs54NWws.d.ts} +1 -1
  184. package/dist/{health-DJaZXg8I.d.ts → health-BnzbSLCE.d.ts} +1 -1
  185. package/dist/index.d.ts +2 -2
  186. package/dist/index.js +1 -1
  187. package/dist/invocation-command-descriptors-CSUGUHTT.js +2 -0
  188. package/dist/invocation-command-descriptors-PPVZOIE5.js +3 -0
  189. package/dist/output-continuation-command-FTVVBVSN.js +2 -0
  190. package/dist/output-continuation-command-ITPRC3YV.js +3 -0
  191. package/dist/project-reindex-7HZSLLLY.js +3 -0
  192. package/dist/project-reindex-NGM3DYBN.js +2 -0
  193. package/dist/queries/affected.d.ts +2 -2
  194. package/dist/queries/affected.js +1 -1
  195. package/dist/queries/anchors.d.ts +2 -2
  196. package/dist/queries/anchors.js +1 -1
  197. package/dist/queries/architecture.d.ts +2 -2
  198. package/dist/queries/architecture.js +1 -1
  199. package/dist/queries/bottlenecks.d.ts +2 -2
  200. package/dist/queries/bottlenecks.js +1 -1
  201. package/dist/queries/by-kind.d.ts +2 -2
  202. package/dist/queries/by-kind.js +1 -1
  203. package/dist/queries/call-graph.d.ts +2 -2
  204. package/dist/queries/call-graph.js +1 -1
  205. package/dist/queries/change-surface.d.ts +2 -2
  206. package/dist/queries/change-surface.js +1 -1
  207. package/dist/queries/cleanup-plan.d.ts +2 -2
  208. package/dist/queries/cleanup-plan.js +1 -1
  209. package/dist/queries/co-change.d.ts +2 -2
  210. package/dist/queries/co-change.js +1 -1
  211. package/dist/queries/code.d.ts +3 -3
  212. package/dist/queries/code.js +1 -1
  213. package/dist/queries/complexity-hotspots.d.ts +2 -2
  214. package/dist/queries/complexity-hotspots.js +1 -1
  215. package/dist/queries/complexity.d.ts +2 -2
  216. package/dist/queries/complexity.js +1 -1
  217. package/dist/queries/context.d.ts +2 -2
  218. package/dist/queries/context.js +1 -1
  219. package/dist/queries/convergence.d.ts +2 -2
  220. package/dist/queries/convergence.js +1 -1
  221. package/dist/queries/coupling.d.ts +2 -2
  222. package/dist/queries/coupling.js +1 -1
  223. package/dist/queries/cycles.d.ts +2 -2
  224. package/dist/queries/cycles.js +1 -1
  225. package/dist/queries/dataflow.d.ts +2 -2
  226. package/dist/queries/dataflow.js +1 -1
  227. package/dist/queries/dead.d.ts +2 -2
  228. package/dist/queries/dead.js +1 -1
  229. package/dist/queries/decorative-checkers.d.ts +2 -2
  230. package/dist/queries/decorative-checkers.js +1 -1
  231. package/dist/queries/deep-chains.d.ts +2 -2
  232. package/dist/queries/deep-chains.js +1 -1
  233. package/dist/queries/dependence-slice.d.ts +3 -3
  234. package/dist/queries/dependence-slice.js +1 -1
  235. package/dist/queries/dependency-depth.d.ts +2 -2
  236. package/dist/queries/dependency-depth.js +1 -1
  237. package/dist/queries/deps.d.ts +2 -2
  238. package/dist/queries/deps.js +1 -1
  239. package/dist/queries/diff-impact.d.ts +2 -2
  240. package/dist/queries/diff-impact.js +1 -1
  241. package/dist/queries/doc-drift.d.ts +2 -2
  242. package/dist/queries/doc-drift.js +1 -1
  243. package/dist/queries/drift.d.ts +2 -2
  244. package/dist/queries/drift.js +1 -1
  245. package/dist/queries/duplicate-bodies.d.ts +2 -2
  246. package/dist/queries/duplicate-bodies.js +1 -1
  247. package/dist/queries/entry-map.d.ts +2 -2
  248. package/dist/queries/entry-map.js +1 -1
  249. package/dist/queries/evidence.d.ts +3 -3
  250. package/dist/queries/evidence.js +1 -1
  251. package/dist/queries/extract-candidates.d.ts +2 -2
  252. package/dist/queries/extract-candidates.js +1 -1
  253. package/dist/queries/fan.d.ts +2 -2
  254. package/dist/queries/fan.js +1 -1
  255. package/dist/queries/files.d.ts +2 -2
  256. package/dist/queries/files.js +1 -1
  257. package/dist/queries/health.d.ts +3 -3
  258. package/dist/queries/health.js +1 -1
  259. package/dist/queries/hierarchy.d.ts +2 -2
  260. package/dist/queries/hierarchy.js +1 -1
  261. package/dist/queries/hotspots.d.ts +2 -2
  262. package/dist/queries/hotspots.js +1 -1
  263. package/dist/queries/imports.d.ts +2 -2
  264. package/dist/queries/imports.js +1 -1
  265. package/dist/queries/incomplete-migration.d.ts +2 -2
  266. package/dist/queries/incomplete-migration.js +1 -1
  267. package/dist/queries/index.d.ts +5 -5
  268. package/dist/queries/index.js +1 -1
  269. package/dist/queries/isolated.d.ts +2 -2
  270. package/dist/queries/isolated.js +1 -1
  271. package/dist/queries/locality-candidates.d.ts +2 -2
  272. package/dist/queries/locality-candidates.js +1 -1
  273. package/dist/queries/members.d.ts +2 -2
  274. package/dist/queries/members.js +1 -1
  275. package/dist/queries/methods.d.ts +2 -2
  276. package/dist/queries/methods.js +1 -1
  277. package/dist/queries/not-implemented.d.ts +2 -2
  278. package/dist/queries/not-implemented.js +1 -1
  279. package/dist/queries/outline.d.ts +2 -2
  280. package/dist/queries/outline.js +1 -1
  281. package/dist/queries/passthrough-candidates.d.ts +2 -2
  282. package/dist/queries/passthrough-candidates.js +1 -1
  283. package/dist/queries/plan-context.d.ts +2 -2
  284. package/dist/queries/plan-context.js +1 -1
  285. package/dist/queries/react-component-duplicates.d.ts +2 -2
  286. package/dist/queries/react-component-duplicates.js +1 -1
  287. package/dist/queries/react-hook-candidates.d.ts +2 -2
  288. package/dist/queries/react-hook-candidates.js +1 -1
  289. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  290. package/dist/queries/react-large-component-pressure.js +1 -1
  291. package/dist/queries/recent-duplicates.d.ts +2 -2
  292. package/dist/queries/recent-duplicates.js +1 -1
  293. package/dist/queries/redundant-reexports.d.ts +2 -2
  294. package/dist/queries/redundant-reexports.js +1 -1
  295. package/dist/queries/reference-neighborhood.d.ts +2 -2
  296. package/dist/queries/reference-neighborhood.js +1 -1
  297. package/dist/queries/reference-reachability.d.ts +2 -2
  298. package/dist/queries/reference-reachability.js +1 -1
  299. package/dist/queries/refs.d.ts +2 -2
  300. package/dist/queries/refs.js +1 -1
  301. package/dist/queries/self-audit.d.ts +2 -2
  302. package/dist/queries/self-audit.js +1 -1
  303. package/dist/queries/similar-chains.d.ts +2 -2
  304. package/dist/queries/similar-chains.js +1 -1
  305. package/dist/queries/similar-files.d.ts +2 -2
  306. package/dist/queries/similar-files.js +1 -1
  307. package/dist/queries/similar-signatures.d.ts +2 -2
  308. package/dist/queries/similar-signatures.js +1 -1
  309. package/dist/queries/similar.d.ts +2 -2
  310. package/dist/queries/similar.js +1 -1
  311. package/dist/queries/slice.d.ts +2 -2
  312. package/dist/queries/slice.js +1 -1
  313. package/dist/queries/source-inspection.d.ts +4 -4
  314. package/dist/queries/source-inspection.js +1 -1
  315. package/dist/queries/source-search.d.ts +2 -2
  316. package/dist/queries/source-search.js +1 -1
  317. package/dist/queries/stale-abstractions.d.ts +2 -2
  318. package/dist/queries/stale-abstractions.js +1 -1
  319. package/dist/queries/stats.d.ts +2 -2
  320. package/dist/queries/surface.d.ts +2 -2
  321. package/dist/queries/surface.js +1 -1
  322. package/dist/queries/symbols.d.ts +2 -2
  323. package/dist/queries/symbols.js +1 -1
  324. package/dist/queries/system-map.d.ts +2 -2
  325. package/dist/queries/system-map.js +1 -1
  326. package/dist/queries/system.d.ts +2 -2
  327. package/dist/queries/system.js +1 -1
  328. package/dist/queries/test-quality.d.ts +2 -2
  329. package/dist/queries/test-quality.js +1 -1
  330. package/dist/queries/trace.d.ts +2 -2
  331. package/dist/queries/trace.js +1 -1
  332. package/dist/queries/twin-ab.d.ts +2 -2
  333. package/dist/queries/twin-ab.js +1 -1
  334. package/dist/queries/twin-drift.d.ts +2 -2
  335. package/dist/queries/twin-drift.js +1 -1
  336. package/dist/queries/unused-imports.d.ts +2 -2
  337. package/dist/queries/unused-imports.js +1 -1
  338. package/dist/queries/unused-params.d.ts +2 -2
  339. package/dist/queries/unused-params.js +1 -1
  340. package/dist/queries/value-flow.d.ts +3 -3
  341. package/dist/queries/value-flow.js +1 -1
  342. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  343. package/dist/queries/vue-component-duplicates.js +1 -1
  344. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  345. package/dist/queries/vue-composable-candidates.js +1 -1
  346. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  347. package/dist/queries/vue-large-view-pressure.js +1 -1
  348. package/dist/queries/wrapper-candidates.d.ts +2 -2
  349. package/dist/queries/wrapper-candidates.js +1 -1
  350. package/dist/reindex-worker.js +1 -1
  351. package/dist/reindex.d.ts +3 -3
  352. package/dist/reindex.js +31 -31
  353. package/dist/runtime.d.ts +24 -4
  354. package/dist/runtime.js +3 -3
  355. package/dist/rust-semantic-session-server.js +1 -1
  356. package/dist/rust-semantic-session-worker.js +1 -1
  357. package/dist/rust-semantic-worker.js +1 -1
  358. package/dist/{scip-cli-B7N3haxa.d.ts → scip-cli-BRFKkHQn.d.ts} +1 -1
  359. package/dist/sentinel-ensure-command-KYYULCFU.js +2 -0
  360. package/dist/sentinel-ensure-command-RIZA3RY7.js +3 -0
  361. package/dist/sentinel-hook.js +39 -0
  362. package/dist/sentinel-worker.js +16 -0
  363. package/dist/typescript-mailbox-worker.js +1 -1
  364. package/dist/watch-server.js +6 -6
  365. package/docs/COMMAND_REFERENCE.md +5 -3
  366. package/docs/schemas/project-config.schema.json +159 -0
  367. package/package.json +9 -5
  368. package/skills/codebaseiq/SKILL.md +1 -1
  369. package/skills/concrete-plan/SKILL.md +1 -1
  370. package/ui/view/api.js +450 -0
  371. package/ui/view/app.js +394 -0
  372. package/ui/view/builder.js +323 -0
  373. package/ui/view/file-panel.js +170 -0
  374. package/ui/view/focus.js +379 -0
  375. package/ui/view/index.html +54 -0
  376. package/ui/view/map.js +424 -0
  377. package/ui/view/styles.css +1125 -0
  378. package/dist/chunk-2X7V4HS4.js +0 -88
  379. package/dist/chunk-3IER7Q6H.js +0 -12
  380. package/dist/chunk-3JSXXYTZ.js +0 -345
  381. package/dist/chunk-476NR5B7.js +0 -2
  382. package/dist/chunk-5VKBFZZU.js +0 -3
  383. package/dist/chunk-ADTBPVUZ.js +0 -21
  384. package/dist/chunk-BFFZDZQV.js +0 -2
  385. package/dist/chunk-BMYOV5GP.js +0 -77
  386. package/dist/chunk-C74PPYLA.js +0 -3
  387. package/dist/chunk-CWONGW6P.js +0 -3
  388. package/dist/chunk-DDZ7VHWV.js +0 -20
  389. package/dist/chunk-DR2LURYU.js +0 -3
  390. package/dist/chunk-ECQBG7PW.js +0 -564
  391. package/dist/chunk-FM5BPL4V.js +0 -60
  392. package/dist/chunk-G6XFR4ZL.js +0 -4
  393. package/dist/chunk-GTIYTDRE.js +0 -562
  394. package/dist/chunk-HOA5YGOH.js +0 -3
  395. package/dist/chunk-KUW32IRO.js +0 -2
  396. package/dist/chunk-LTA3BRZX.js +0 -2
  397. package/dist/chunk-NAUD7LCA.js +0 -2
  398. package/dist/chunk-OGTFJ3XD.js +0 -2
  399. package/dist/chunk-Q5ELPRKQ.js +0 -2
  400. package/dist/chunk-QCN62RTF.js +0 -3
  401. package/dist/chunk-QW7EP6WI.js +0 -21
  402. package/dist/chunk-RU65DDUP.js +0 -215
  403. package/dist/chunk-SELM5MER.js +0 -2
  404. package/dist/chunk-SNNWPCN7.js +0 -4
  405. package/dist/chunk-TFZB6XTM.js +0 -239
  406. package/dist/chunk-UXM43C7T.js +0 -3
  407. package/dist/chunk-VFY6Y2H6.js +0 -61
  408. package/dist/chunk-WE5RZHZ7.js +0 -5
  409. package/dist/chunk-Z54RD7VL.js +0 -3
  410. package/dist/cli-context-3SNLDYBM.js +0 -3
  411. package/dist/cli-context-T3B7W6GG.js +0 -2
  412. package/dist/cli-program-YNOXO72B.js +0 -7
  413. package/dist/command-descriptors-6AOUKWW7.js +0 -346
  414. package/dist/command-descriptors-ZFKJSRUP.js +0 -344
  415. package/dist/direct-navigation-DP4LVMRX.js +0 -3
  416. package/dist/direct-navigation-FLUS3BT6.js +0 -2
  417. package/dist/invocation-command-descriptors-QT2JMY5J.js +0 -3
  418. package/dist/invocation-command-descriptors-YN4QJEAX.js +0 -2
  419. package/dist/output-continuation-command-2V2SL4TD.js +0 -2
  420. package/dist/output-continuation-command-65J5IP3O.js +0 -3
  421. package/dist/project-reindex-5JOKXAXT.js +0 -2
  422. package/dist/project-reindex-UQBIKO4M.js +0 -3
@@ -0,0 +1,16 @@
1
+ import{a as G}from"./chunk-IGYAZPRX.js";import{a as he,b as ge,d as et,e as tt,f as nt,g as it,i as st,j as rt,l as me,m as ot}from"./chunk-5XEVXVTK.js";import{a as at}from"./chunk-SV2LEFVM.js";import{B as Xe,ca as Ze,l as Je,m as Ye,ma as Qe,o as Ve,p as A,q as fe,r as C,s as pe}from"./chunk-WJOQC4P7.js";import{C as We,K as Ke,L as Ge,n as He,s as ze,y as K}from"./chunk-IYBIBMPF.js";import{a as Ue}from"./chunk-XYLV727H.js";import{e as W}from"./chunk-4NHWNAWQ.js";import{g as qe}from"./chunk-2VKB5CMA.js";import{p as Be,r as je}from"./chunk-ACZDU5GK.js";import"./chunk-R2NOK63J.js";import"./chunk-6URCE5QY.js";import{Q as z,R as k,a as le,b as de,f as ce,g as ue,h as P,n as Le}from"./chunk-4O52YNKL.js";import{randomBytes as Gs}from"crypto";import{chmodSync as qs,existsSync as kn,mkdirSync as Js,realpathSync as Ys,renameSync as Vs,rmSync as Te,statSync as Xs}from"fs";import{createServer as Zs}from"net";import{dirname as Qs,join as _n,posix as xn}from"path";import{isMainThread as er,parentPort as En,workerData as Rn}from"worker_threads";import{createHash as Is}from"crypto";import{setImmediate as gn}from"timers/promises";function R(t){return`${t.container.join(".")}#${t.name}#${t.ordinal}`}function ye(t){let e={files:new Map,byExactHash:new Map};for(let[n,i]of t)I(e,n,i);return e}function I(t,e,n){let i=t.files.get(e);if(i)for(let s of i){let r=t.byExactHash.get(s.exactHash);if(!r)continue;let o=r.filter(a=>a.file!==e);o.length>0?t.byExactHash.set(s.exactHash,o):t.byExactHash.delete(s.exactHash)}if(!n){t.files.delete(e);return}t.files.set(e,[...n]);for(let s of n){let r=t.byExactHash.get(s.exactHash)??[];r.push({file:e,unit:s}),t.byExactHash.set(s.exactHash,r)}}function O(t,e){if(!t)return[...e];let n=new Map;for(let s of t){let r=`${s.name}\0${s.exactHash}`;n.set(r,(n.get(r)??0)+1)}let i=[];for(let s of e){let r=`${s.name}\0${s.exactHash}`,o=n.get(r)??0;o>0?n.set(r,o-1):i.push(s)}return i}function lt(t,e,n){let i=[];for(let s of e){if(s.unit.tokenCount<8)continue;let r=R(s.unit);for(let o of t.byExactHash.get(s.unit.exactHash)??[]){if(o.file===s.file&&R(o.unit)===r)continue;let a=o.unit.name===s.unit.name;s.unit.bodyLines<3&&!a||i.push({subject:s,counterpart:o,basis:s.unit.bodyLines<3?"exact-body-same-name":"exact-body",inFlight:n.isInFlight(o),crossBoundary:!n.allowsDependency(s.file,o.file)})}}return i.sort(Cn)}function Cn(t,e){return t.subject.file.localeCompare(e.subject.file)||t.subject.unit.startLine-e.subject.unit.startLine||Number(t.inFlight)-Number(e.inFlight)||t.counterpart.file.localeCompare(e.counterpart.file)||t.counterpart.unit.startLine-e.counterpart.unit.startLine}function dt(t,e){return`${t}#${R(e)}`}function ct(t,e,n){return e==="unknown"?new Set:new Set(O(e,n).map(i=>dt(t,i)))}var q=class{options;corpus=ye([]);constructor(e){this.options=e}buildCorpus(e){this.corpus=ye([]);for(let n of e)this.updateFile(n)}updateFile(e){I(this.corpus,e,this.currentUnits(e))}removeFile(e){I(this.corpus,e,null)}corpusSize(){return this.corpus.files.size}currentUnits(e){if(!this.options.isInputPath(e))return null;let n=this.options.readText(e);return n===null?null:G(this.options.db,e,n)?.units??null}analyzeEdit(e){let n=new Map,i=new Set,s=[],r=[];for(let d of e.files){let u=this.currentUnits(d.path);if(n.set(d.path,u),I(this.corpus,d.path,u),!!u){if(d.baselineUnits==="unknown"||d.baselineUnits===null&&!d.createdInSession){r.push(d.path);continue}d.createdInSession&&i.add(d.path);for(let c of O(d.baselineUnits,u))s.push({file:d.path,unit:c})}}let o=lt(this.corpus,s,{isInFlight:d=>e.inFlight.has(dt(d.file,d.unit)),allowsDependency:this.options.allowsDependency}),a=[],l=[];for(let d of o){let u=this.verify(d,n);u&&(i.has(u.subject.file)?l:a).push(u)}return{matches:a,held:l,skipped:r}}recheckHeld(e){let n=new Map;return e.flatMap(i=>this.verify(i,n)??[])}verify(e,n){let i=this.freshUnit(e.subject,n),s=this.freshUnit(e.counterpart,n);return i&&s?{...e,subject:i,counterpart:s}:null}freshUnit(e,n){n.has(e.file)||n.set(e.file,this.currentUnits(e.file));let i=R(e.unit),s=n.get(e.file)?.find(r=>R(r)===i&&r.exactHash===e.unit.exactHash);return s?{file:e.file,unit:s}:null}};var $n="codebaseiq sentinel (exact-body evidence):",ut="If a match is intended, ignore it or mark the copy with `// codebaseiq: ignore-similar`.",An="codebaseiq sentinel (unwired code):",In="Wire them in, remove them, or tell the user why they are intentionally unreferenced.",On="codebaseiq sentinel (earlier evidence, still unresolved):";function T(t){let e=s=>t.settings.delivery[s.family]==="shadow",n=t.findings.filter(e),i=jn(t.findings.filter(s=>!e(s)));return{...Tn(i,t),shadowed:n}}function Tn(t,e){switch(e.event){case"edit":case"prompt":return Mn(t,e);case"stop":return Ln(t,e);case"session-start":return Bn(t,e);case"session-end":return{delivered:[],blocked:[]}}}function Mn(t,e){let n=ft(t,e).slice(0,e.settings.maxPerDelivery);return n.length===0?{delivered:[],blocked:[]}:{modelText:[$n,...n.map(J),ut].join(`
2
+ `),delivered:n.map(i=>i.id),blocked:[]}}function Ln(t,e){let n=e.unverifiedReason||Un(e);if(n)return{userText:`codebaseiq sentinel unverified: ${n}`,delivered:[],blocked:[]};let i=t.filter(o=>o.family==="unwired"),s=i.filter(o=>(o.evidence==="exact"||o.evidence==="syntactic")&&!e.alreadyBlocked.has(o.id));if(e.settings.blockOnUnwired&&!e.stopHookActive&&s.length>0)return{block:!0,modelText:[An,...s.map(J),In].join(`
3
+ `),delivered:[],blocked:s.map(o=>o.id)};let r=[...i,...ft(t,e)];return r.length===0?{delivered:[],blocked:[]}:{userText:Hn(r,e.settings.maxPerDelivery),delivered:[],blocked:[]}}function Un({serviceStatus:t,settings:e}){return t.corpus==="ready"||!Object.values(e.delivery).includes("live")?null:`corpus ${t.corpus}`}function Bn(t,e){let n=t.slice(0,e.settings.maxPerDelivery);if(n.length===0)return{delivered:[],blocked:[]};let i=[On,...n.map(J)];return n.some(s=>s.family==="reuse-match")&&i.push(ut),{modelText:i.join(`
4
+ `),delivered:n.map(s=>s.id),blocked:[]}}function ft(t,e){return t.filter(n=>n.family==="reuse-match"&&!e.alreadyDelivered.has(n.id))}function jn(t){let e=new Set;return t.filter(n=>e.has(n.id)?!1:(e.add(n.id),!0))}function pt(t){if(t.family==="reuse-match")return t.summary;let{name:e,file:n,line:i}=t.subject;return`\`${e}\` (${n}:${i}) has no import or call outside tests`}function J(t){return`- ${pt(t)}`}function Hn(t,e){let n=t.slice(0,e),i=n.map(r=>r.family==="unwired"&&r.evidence!=="exact"?`- ${pt(r)} (${r.evidence} evidence)`:J(r)),s=t.length-n.length;return["codebaseiq sentinel:",...i,...s>0?[`- and ${s} more`]:[]].join(`
5
+ `)}import{createHash as zn}from"crypto";var Wn=new Map([["echo","reuse-match"],["new-dead","unwired"]]),gt="similar",Kn=/(?:\/\/|#|\/\*)\s*codebaseiq/i;function M(t,e,n,i){return`SN${zn("sha256").update([t,e,n.join("."),i].join("\0")).digest("hex").slice(0,14)}`}function Se(t){return{file:t.file,line:t.unit.startLine+1,name:t.unit.name,signature:t.unit.signature}}function Y(t,e){let n=Se(t.subject),i=Se(t.counterpart),s=[t.basis];t.inFlight&&s.push("in-flight"),t.crossBoundary&&s.push("cross-boundary");let r=t.basis==="exact-body-same-name"?"the same name and body as":"the same body as",o=t.inFlight?`in-flight \`${i.name}\``:`\`${i.name}\``,a=`\`${n.name}\` (${n.file}:${n.line}) has ${r} ${o} (${i.file}:${i.line}, ${i.signature})`;return a+=t.inFlight?" from this or another live session.":".",t.crossBoundary&&(a+=` The architecture policy does not allow \`${n.file}\` to import \`${i.file}\`.`),{id:M("reuse-match",t.subject.file,t.subject.unit.container,t.subject.unit.name),family:"reuse-match",evidence:"exact",subject:n,counterpart:i,labels:s,summary:a,timesSeen:e}}function mt(t,e){if(t.status!=="unwired")throw new Error(`cannot build an unwired finding for a callable classified ${t.status}`);let n=Se(t);return{id:M("unwired",t.file,t.unit.container,t.unit.name),family:"unwired",evidence:t.evidence,subject:n,labels:["unwired"],summary:`\`${n.name}\` (${n.file}:${n.line}) has no import or call outside tests.`,timesSeen:e}}function yt(t,e,n){for(let i of e){if(i.id!==void 0&&i.id===t.id)return`suppressed by id ${t.id}`;if(i.check!==void 0&&i.file!==void 0&&(Wn.get(i.check)??i.check)===t.family&&i.file===t.subject.file&&(i.name===void 0||i.name===t.subject.name)){let s=i.name===void 0?"":`${t.subject.name} in `;return`suppressed by ${t.family} rule for ${s}${t.subject.file}`}}return Gn(n(t.subject.file),t.subject.line)?`marked \`codebaseiq: ignore-${gt}\` in source`:null}function Gn(t,e){if(!t)return!1;let n=t[e-2];if(n!==void 0&&ht(n))return!0;let i=t[e-1];if(i===void 0)return!1;let s=i.search(Kn);return s>=0&&ht(i.slice(s))}function ht(t){return He(t)?.toLowerCase()===gt}import{spawn as qn}from"child_process";var Jn=/^[0-9a-f]{40,64} (\S+) (\d+)$/,Yn=/ (?:missing|ambiguous)$/,St=1,V=class{constructor(e){this.projectRoot=e}projectRoot;child;buffered=Buffer.alloc(0);header;pending=[];restartsLeft=St;read(e){return e.includes(`
6
+ `)?Promise.resolve(null):new Promise((n,i)=>{this.pending.push({revPath:e,resolve:n,reject:i}),this.ensureChild().stdin.write(`${e}
7
+ `)})}close(){let e=this.child;return this.child=void 0,this.failPending(new Error("GitBlobReader closed before answering")),e?new Promise(n=>{e.once("close",()=>n()),e.once("error",()=>n()),e.stdin.end(),e.kill()}):Promise.resolve()}ensureChild(){if(this.child)return this.child;let e=qn("git",["-C",this.projectRoot,"cat-file","--batch"],{env:z(),stdio:["pipe","pipe","ignore"],windowsHide:!0});return this.child=e,this.buffered=Buffer.alloc(0),this.header=void 0,e.stdout.on("data",n=>{this.child===e&&this.consume(e,n)}),e.stdin.on("error",()=>{}),e.on("error",()=>this.onStopped(e)),e.on("close",()=>this.onStopped(e)),e}onStopped(e){if(this.child===e&&(this.child=void 0,this.pending.length!==0)){if(this.restartsLeft===0){this.failPending(new Error("git cat-file exited before answering"));return}this.restartsLeft-=1,this.ensureChild().stdin.write(this.pending.map(n=>`${n.revPath}
8
+ `).join(""))}}consume(e,n){for(this.buffered=this.buffered.length===0?n:Buffer.concat([this.buffered,n]);;)if(this.header){let{type:i,size:s}=this.header;if(this.buffered.length<s+1)return;let r=Buffer.from(this.buffered.subarray(0,s));this.buffered=this.buffered.subarray(s+1),this.header=void 0,this.settle(i==="blob"?r:null)}else{let i=this.buffered.indexOf(10);if(i<0)return;let s=this.buffered.subarray(0,i).toString("utf8");this.buffered=this.buffered.subarray(i+1);let r=Jn.exec(s);if(r)this.header={type:r[1],size:Number(r[2])};else if(Yn.test(s))this.settle(null);else{e.kill(),this.onStopped(e);return}}}settle(e){let n=this.pending.shift();n&&(this.restartsLeft=St,n.resolve(e))}failPending(e){for(let n of this.pending.splice(0))n.reject(e)}};import{spawnSync as Vn}from"child_process";var Xn=64*1024*1024;function bt(t,e,n){let i=[...new Set(e.filter(a=>a.length>0))],s=new Map(i.map(a=>[a,new Set]));if(i.length===0)return s;let r=Vn("git",["grep","-n","-z","-w","-F","-I","--untracked",...i.flatMap(a=>["-e",a]),"--",...n.pathspecs],{cwd:t,env:z(),encoding:"utf8",windowsHide:!0,timeout:n.timeoutMs,maxBuffer:Xn});if(r.error)throw new Error(`git grep failed: ${r.error.message}`);if(r.status===1)return s;if(r.status!==0)throw new Error(`git grep exited with ${r.status??r.signal}: ${r.stderr.trim()}`);let o=new RegExp(`(?<![A-Za-z0-9_])(${i.map(Zn).join("|")})(?![A-Za-z0-9_])`,"g");for(let a of r.stdout.split(`
9
+ `)){let l=a.indexOf("\0"),d=l<0?-1:a.indexOf("\0",l+1);if(d<0)continue;let u=a.slice(0,l);for(let c of a.slice(d+1).matchAll(o))s.get(c[1])?.add(u)}return s}function Zn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{appendFileSync as Qn,existsSync as be,mkdirSync as ei,renameSync as ti,rmSync as ni,statSync as ii}from"fs";import{join as si}from"path";var ri=["shadowed","shown","acted-on","dismissed","blocked"],oi=1024*1024,ve=5;function wt(t){let e=i=>si(t,i===0?"outcomes.jsonl":`outcomes.${i}.jsonl`),n=()=>{ni(e(ve),{force:!0});for(let i=ve-1;i>=0;i--)be(e(i))&&ti(e(i),e(i+1))};return{append(i){let s=`${JSON.stringify(i)}
10
+ `;ei(t,{recursive:!0});let r=e(0);if(be(r)){let o=ii(r).size;o>0&&o+Buffer.byteLength(s)>oi&&n()}Qn(r,s)},readRecent(i,s){let r=[];for(let o=0;o<=ve&&r.length<s;o++){if(!be(e(o)))continue;let a=P(e(o),"sentinel outcome log").split(`
11
+ `);for(let l=a.length-1;l>=0&&r.length<s;l--){let d=ai(a[l]);d?.family===i&&r.push(d)}}return r.reverse()}}}function ai(t){if(t.length===0)return null;try{let e=JSON.parse(t);return typeof e.at=="string"&&typeof e.session=="string"&&typeof e.findingId=="string"&&A.includes(e.family)&&ri.includes(e.kind)?e:null}catch{return null}}function xt(t,e,n){let{counterpart:i,subject:s}=t;if(t.family!=="reuse-match"||!i||n===null)return!1;let r=n.filter(c=>c.name===i.name);if(r.length===0)return!1;if(e===null)return!0;let o=vt(n,i),a=o?[o]:r,l=s.file===i.file,d=new Set(a.map(c=>c.exactHash)),u=new Set(a.map(R));return e.some(c=>d.has(c.exactHash)&&!(l&&u.has(R(c))))?!1:e.some(c=>c.name===s.name)?vt(e,s)?.calleeLeaves.includes(i.name)??!1:!0}function vt(t,e){let n=t.filter(i=>i.name===e.name);return n.find(i=>i.signature===e.signature)??n.find(i=>i.startLine+1===e.line)??(n.length===1?n[0]:void 0)}function li(t,e,n=C.window){let i=new Map;for(let r of t)r.family===e&&((r.kind==="shown"||r.kind==="blocked")&&!i.has(r.findingId)?i.set(r.findingId,!1):r.kind==="acted-on"&&i.has(r.findingId)&&i.set(r.findingId,!0));let s=[...i.values()].slice(-n);return s.length<n?null:s.filter(Boolean).length/n}function Et(t,e,n=C.window){let i=li(t,e,n);return i!==null&&i<C.minActedOnRate}import{isAbsolute as di,relative as ci,resolve as ui,sep as Rt}from"path";var fi=["tsup.config.ts","tsup.config.js","tsup.config.mjs"],pi=/(?<!\.d)\.[cm]?[jt]sx?$/,hi=/(?:^|\/)(?:tests?|__tests__|test-fixtures)\//,gi=/\.(?:test|spec)\.[^/]+$/,mi=/\bentry\s*:\s*/g,yi=/(['"`])((?:(?!\1)[^\\\n]|\\.)*)\1/g,Ft={"{":"}","[":"]"};function _t(t,e,n){let{architecture:i}=t;if(!i)return!0;let s=kt(i,e),r=kt(i,n);if(s===null||r===null||s===r)return!0;let o=i.allowedDependencies;return!o||!Object.hasOwn(o,s)?!0:o[s].includes(r)}function kt(t,e){let n=t.boundaries.filter(i=>i.paths.some(s=>at(s,e)));return n.length===1?n[0].name:null}function Dt(t,e){let n=new Set,i=r=>{let o=vi(t,r);o!==null&&pi.test(o)&&e(o)!==null&&n.add(o)};for(let r of fi){let o=e(r);o!==null&&Si(o).forEach(i)}let s=wi(e("package.json"));return Pt(s)&&(X(s.bin).forEach(i),X(s.exports).forEach(i)),n}function Nt(t){let e=t.replace(/\\/g,"/");return hi.test(e)||gi.test(e)}function Si(t){let e=ze(t),n=[];for(let i of e.matchAll(mi)){let s=i.index+i[0].length,r=bi(e,s);for(let o of r.matchAll(yi))!o[2].includes("${")&&!/[*?]/.test(o[2])&&n.push(o[2])}return n}function bi(t,e){let n=t[e];if(n===void 0)return"";if(n==="'"||n==='"'||n==="`"){let r=t.indexOf(n,e+1);return r<0?"":t.slice(e,r+1)}if(!(n in Ft))return"";let i=0,s=null;for(let r=e;r<t.length;r+=1){let o=t[r];if(s)o==="\\"?r+=1:o===s&&(s=null);else if(o==="'"||o==='"'||o==="`")s=o;else if(o in Ft)i+=1;else if((o==="}"||o==="]")&&(i-=1,i===0))return t.slice(e,r+1)}return""}function X(t){return typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(X):Pt(t)?Object.values(t).flatMap(X):[]}function vi(t,e){let n=ci(t,ui(t,e));return n===""||n===".."||n.startsWith(`..${Rt}`)||di(n)?null:n.split(Rt).join("/")}function wi(t){if(t!==null)try{return JSON.parse(t)}catch{return}}function Pt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}import{createHash as xi}from"crypto";import{utimesSync as Ei}from"fs";import{join as Ee}from"path";var Ct=/^[0-9a-f]{40,64}$/,Ri=["status","--porcelain=v1","-z","--untracked-files=all","--no-renames"];function Re(t){return Ee(t,"blobs")}function At(t,e){return Ee(Re(t),e)}function It(t){let e=Mt(t.projectRoot);if(e.kind==="not-repository")return{kind:"not-a-repository"};let n=e.kind==="success"?e.output:void 0,i=$t(t,n);return i.exact||(i=$t(t,n)),{kind:"captured",baseline:{head:i.head,tree:i.tree,capturedAt:Date.now(),dirty:i.dirty,...i.exact?{}:{approximated:!0}}}}function $t({projectRoot:t,stateDir:e,isTrackedInput:n},i){let s=we(t),r=i===void 0?void 0:xe(t,i);if(i===void 0||!r)return{...s,dirty:[],exact:!1};let o=new Map,a=!0;for(let{code:u,path:c}of r.entries){if(!n(c))continue;let f=Fe(t,c);if(f.kind==="file"){let p=Ut(f.content);Di(e,p,f.content),o.set(c,{path:c,sha256:p})}else f.kind==="absent"&&u.includes("D")?o.set(c,{path:c,sha256:null}):a=!1}let l=xe(t,i),d=we(t);return a=a&&l?.raw===r.raw&&d.head===s.head&&d.tree===s.tree,{...s,dirty:[...o.values()],exact:a}}async function Ot(t,e,n,i){let s=t.dirty.find(o=>o.path===e);if(s)return s.sha256===null?null:ce(At(i,s.sha256),{inputKind:"session baseline overlay",maxBytes:de}).toString("utf8");if(t.head===null)return null;let r=await n.read(`${t.head}:./${e}`);return r===null?null:r.toString("utf8")}function Tt(t){let{projectRoot:e,baseline:n,ledgerPaths:i}=t,s=Mt(e),r=s.kind==="success"?xe(e,s.output):void 0;if(s.kind!=="success"||!r)throw new Error(`git status failed in ${e}; the session delta is unknown.`);let o=we(e).head,a=ki(e,n.head,o),l=new Set(r.entries.map(c=>c.path));if(a==="descendant")for(let c of _i(e,n.head,o,s.output))l.add(c);for(let c of n.dirty){let f=Fe(e,c.path),p=f.kind==="file"?Ut(f.content):f.kind==="absent"?null:void 0;p!==void 0&&p===c.sha256?l.delete(c.path):l.add(c.path)}let d=new Set(n.dirty.map(c=>c.path)),u=[];for(let c of new Set(i))l.has(c)||(d.has(c)||Fi(e,n.head,c)?u.push(c):l.add(c));return{changed:[...l].sort(),revertedOrStashed:u,head:a}}function Fi(t,e,n){let i=Fe(t,n);if(i.kind==="absent")return!0;if(i.kind==="unreadable"||e===null)return!1;let s=k.run(t,["rev-parse","--verify","--quiet",`${e}:./${n}`]);return s?k.run(t,["hash-object","--",n])===s:!1}function ki(t,e,n){return e===n?"unchanged":e===null?"descendant":n===null?"unrelated":k.runResult(t,["merge-base","--is-ancestor",e,n]).kind==="success"?"descendant":"unrelated"}function _i(t,e,n,i){let s=e===null?["ls-tree","-r","-z","--name-only","--full-tree",n]:["diff-tree","-r","-z","--name-only","--no-renames","--first-parent",e,n],r=k.run(t,s);if(r===void 0)throw new Error(`git ${s[0]} failed in ${t}; the session delta is unknown.`);return r.split("\0").flatMap(o=>{let a=o?Lt(o,i):void 0;return a===void 0?[]:[a]})}function we(t){let[e,n]=(k.run(t,["rev-parse","HEAD","HEAD^{tree}"])??"").split(`
12
+ `).map(i=>i.trim());return e&&n&&Ct.test(e)&&Ct.test(n)?{head:e,tree:n}:{head:null,tree:null}}function Mt(t){return k.runResult(t,["rev-parse","--show-prefix"])}function Lt(t,e){return e===""?t:t.startsWith(e)?t.slice(e.length):void 0}function xe(t,e){let n=k.run(t,Ri);if(n===void 0)return;let i=n.split("\0").filter(s=>s.length>=4&&s[2]===" ").flatMap(s=>{let r=Lt(s.slice(3),e);return r===void 0?[]:[{code:s.slice(0,2),path:r}]});return{raw:i.map(s=>`${s.code} ${s.path}`).join("\0"),entries:i}}function Fe(t,e){try{return{kind:"file",content:ce(Ee(t,e),{inputKind:"session baseline file",maxBytes:de})}}catch(n){let i=n.code;return i==="ENOENT"||i==="ENOTDIR"?{kind:"absent"}:{kind:"unreadable"}}}function Di(t,e,n){let i=At(t,e),s=new Date;try{Ei(i,s,s);return}catch(r){if(r.code!=="ENOENT")throw r}Be(i,n)}function Ut(t){return xi("sha256").update(t).digest("hex")}import{existsSync as jt,readdirSync as Ht,rmSync as Bt,statSync as Ni}from"fs";import{join as Z}from"path";var zt=()=>{};function Wt(t){let{stateDir:e,session:n,host:i,source:s,capture:r,now:o=Date.now()}=t,a=w(e,n);if(a){let c={...a,lastSeenAt:o};return delete c.endedAt,L(e,c),c}let l=r(),u={session:n,host:i,createdAt:o,lastSeenAt:o,baseline:s==="resume"||s==="compact"?{...l,approximated:!0}:l,touched:{},delivered:[],blocked:[],timesSeen:{}};return L(e,u),u}function w(t,e){return sn(en(t,e))}function Kt(t,e,n,i=Date.now()){return U(t,e,i,s=>{s.touched[n.path]={sha256:n.sha256,at:i,change:n.change}})}function Gt(t,e,n,i=Date.now()){let s=w(t,e);if(!s)return;let r=!1;for(let{path:o,sha256:a,change:l}of n){let d=Object.hasOwn(s.touched,o)?s.touched[o]:void 0;!d||d.sha256===a&&d.change===l||(s.touched[o]={sha256:a,at:i,change:l},r=!0)}return r&&L(t,s),s}function qt(t,e,n,i=Date.now(),s={}){return U(t,e,i,r=>{for(let o of n)r.delivered.includes(o)||r.delivered.push(o),r.timesSeen[o]=(r.timesSeen[o]??0)+1;Object.keys(s).length>0&&(r.deliveredFindings={...r.deliveredFindings,...s})})}function Jt(t,e,n,i=Date.now()){let s=w(t,e),r=s?.deliveredFindings;if(!s||!r||!n.some(o=>Object.hasOwn(r,o)))return s;for(let o of n)delete r[o];return s.lastSeenAt=i,L(t,s),s}function Yt(t,e,n,i=Date.now()){return U(t,e,i,s=>{for(let r of n)s.blocked.includes(r)||s.blocked.push(r)})}function Vt(t,e,n=Date.now()){return U(t,e,n,i=>{i.endedAt=n})}function Xt(t,e,n,i=Date.now()){return U(t,e,i,s=>{s.baseline=n,s.touched={},delete s.endedAt})}function Zt(t,e,n,i=zt){return nn(t,i).ledgers.map(({ledger:s})=>s).filter(s=>s.endedAt===void 0&&e-s.lastSeenAt<=n)}function Qt(t,e,n=Date.now(),i=zt){let s=new Set,r=0,{ledgers:o,unreadable:a}=nn(t,i);for(let{path:u,ledger:c}of o){if(n-c.lastSeenAt>e){Bt(u,{force:!0}),r+=1;continue}for(let f of c.baseline.dirty)f.sha256!==null&&s.add(f.sha256)}let l=0,d=Re(t);if(a===0&&jt(d))for(let u of Ht(d)){let c=Z(d,u);s.has(u)||Ni(c).mtimeMs>=n-e||(Bt(c,{force:!0}),l+=1)}return{removedSessions:r,removedBlobs:l}}function U(t,e,n,i){let s=w(t,e);if(s)return i(s),s.lastSeenAt=n,L(t,s),s}function L(t,e){je(en(t,e.session),e)}function en(t,e){if(!Ve.test(e))throw new Error(`Invalid sentinel session id ${JSON.stringify(e)}.`);return Z(tn(t),`${e.replaceAll(":","%3A")}.json`)}function tn(t){return Z(t,"sessions")}function nn(t,e){let n=tn(t),i=[],s=0;if(!jt(n))return{ledgers:i,unreadable:s};for(let r of Ht(n)){if(!r.endsWith(".json"))continue;let o=Z(n,r);try{let a=sn(o);a&&i.push({path:o,ledger:a})}catch(a){s+=1,e(`sentinel skipped the unreadable session ledger ${o}: ${a instanceof Error?a.message:String(a)}`)}}return{ledgers:i,unreadable:s}}function sn(t){let e;try{e=JSON.parse(P(t,"sentinel session ledger"))}catch(n){if(n instanceof SyntaxError||n.code==="ENOENT")return;throw n}return Pi(e)?e:void 0}function Pi(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.session=="string"&&(e.host==="claude"||e.host==="codex")&&typeof e.createdAt=="number"&&typeof e.lastSeenAt=="number"&&typeof e.baseline=="object"&&e.baseline!==null&&Array.isArray(e.baseline.dirty)&&typeof e.touched=="object"&&e.touched!==null&&Array.isArray(e.delivered)&&Array.isArray(e.blocked)&&typeof e.timesSeen=="object"&&e.timesSeen!==null&&(e.deliveredFindings===void 0||typeof e.deliveredFindings=="object"&&e.deliveredFindings!==null&&!Array.isArray(e.deliveredFindings))}import{join as Ci}from"path";function ln(t,e=()=>{}){let n=Ci(t,Ye),i=$i(),s;try{s=P(n,"sentinel settings")}catch(a){return a.code!=="ENOENT"&&e(`sentinel settings ${n} are unreadable: ${an(a)}; using defaults`),i}let r;try{r=JSON.parse(s)}catch(a){return e(`sentinel settings ${n} are not valid JSON: ${an(a)}; using defaults`),i}if(!on(r))return e(`sentinel settings ${n} must be a JSON object; using defaults`),i;let o=(a,l)=>e(`sentinel settings ${n}: ${a} must be ${l}; using the default`);return r.delivery!==void 0&&(on(r.delivery)?Ai(i.delivery,r.delivery,o):o("delivery","an object")),r.blockOnUnwired!==void 0&&(typeof r.blockOnUnwired=="boolean"?i.blockOnUnwired=r.blockOnUnwired:o("blockOnUnwired","true or false")),r.leaseIdleMs!==void 0&&(rn(r.leaseIdleMs)?i.leaseIdleMs=r.leaseIdleMs:o("leaseIdleMs","a positive number of milliseconds")),r.maxPerDelivery!==void 0&&(rn(r.maxPerDelivery)&&Number.isInteger(r.maxPerDelivery)?i.maxPerDelivery=r.maxPerDelivery:o("maxPerDelivery","a positive integer")),i}function $i(){return{...fe,delivery:{...fe.delivery}}}function Ai(t,e,n){for(let[i,s]of Object.entries(e))Ii(i)?s==="shadow"||s==="live"?t[i]=s:n(`delivery.${i}`,'"shadow" or "live"'):n(`delivery.${i}`,`one of ${A.join(", ")}`)}function Ii(t){return A.includes(t)}function rn(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function on(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function an(t){return t instanceof Error?t.message:String(t)}import{posix as y}from"path";var Oi=new Set([".vue",".svelte",".astro"]),dn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ti={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]},Mi=new Set(["class_declaration","abstract_class_declaration","class"]),Li=new Set(["identifier","shorthand_property_identifier"]),Ui=new Set(["identifier","property_identifier","shorthand_property_identifier"]),Bi=new Set(["identifier","property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),ji=new Set(["identifier","field_identifier"]),Hi=new Set(["identifier"]),zi=new Set(["import_specifier","export_specifier"]),Wi=/^#\[\s*(?:allow|warn|deny|inline|must_use|deprecated|doc|rustfmt|track_caller)\b/,Ki=/cfg\s*\(\s*test\s*\)|^#\[\s*(?:\w+::)*test\b/,Gi=3,qi=100,Ji="a default export can be imported under any name",Yi=new RegExp(["(?:^|/)app/(?:.*/)?(?:route|page|layout|loading|error|global-error|not-found|template|default|sitemap|robots|manifest|opengraph-image|twitter-image|icon|apple-icon)\\.[cm]?[jt]sx?$","(?:^|/)pages/","(?:^|/)middleware\\.[cm]?[jt]sx?$","\\.config\\.[cm]?[jt]sx?$","(?:^|/)\\+[a-z-]+(?:\\.server)?\\.[jt]s$"].join("|")),Vi=new Set(["handler","up","down","middleware","loader","action","GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","getServerSideProps","getStaticProps","getStaticPaths","generateMetadata","generateStaticParams"]),Xi=new Set(["lib.rs","mod.rs","main.rs"]);function un(t){let e=ss(t.readText),n=new Map,i=[];for(let o of t.candidates){let a=Zi(t,o);a?n.set(o,a):i.push(o)}let s=null,r="";if(i.length>0)try{s=t.grep([...new Set(i.map(({unit:o})=>o.name))])}catch(o){r=o instanceof Error?o.message:String(o)}for(let o of i){if(!s){n.set(o,F("unverified",`the repository search failed: ${r}`));continue}n.set(o,Qi(t,o,s.get(o.unit.name)??new Set,e))}return t.candidates.map(o=>({...o,...n.get(o)}))}function Zi(t,{file:e,unit:n}){if(n.exported&&t.entryModules.has(e))return{status:"wired-by-entry",evidence:"syntactic",detail:`exported from entry module ${e}`};if(t.isTestPath(e))return F("unverified","defined in a test file");if(!N(K(e)))return F("unverified",`no analyzer for ${y.extname(e)||e}`);let i=t.exactReferences?.(e,n)??null;return i!==null&&i>0?{status:"wired",evidence:"exact",detail:`${i} indexed reference(s)`}:null}function Qi(t,{file:e,unit:n},i,s){let r=s(e);if(r.kind!=="ok")return F("unverified",`${e} could not be read or parsed`);let{language:o}=r.parsed,a=ls(r.parsed,n);if(!a)return F("unverified",`the definition of ${n.name} is not at line ${n.startLine+1} of ${e}`);if(a.testScoped)return F("unverified","defined inside a test-only module");let l=N(o),d={file:e,unit:n,family:l,def:a,shared:t.definitionCountByName.get(n.name)??1,mentions:i,parse:s,isTestPath:t.isTestPath,entryModules:t.entryModules,trace:Ds(e,s),defaultExport:a.defaultExport,exposedByList:!1};return es(d,ts(d,r.parsed))}function es(t,e){let{unit:n}=t;if(e.entry)return{status:"wired-by-entry",evidence:"syntactic",detail:e.entry};let i=t.shared>1,s=e.crossFile??(i?null:e.sameFile??e.member);if(s)return{status:"wired",evidence:s.evidence,detail:s.detail};if(i){let a=e.sameFile??e.member,l=a?`; ${a.detail} cannot be tied to this definition`:"; no import of this definition found";return F("ambiguous",`${t.shared} definitions are named ${n.name}${l}`)}if(e.incomplete)return F("unverified",e.incomplete);let r=t.def.implicit??(t.defaultExport?Ji:null)??ps(t);if(r)return F("unverified",`${r}; a caller may not be visible in source`);let o=e.testOnly>0?`, ignoring ${e.testOnly} test file(s)`:"";return{status:"unwired",evidence:"syntactic",detail:`no use of ${n.name} outside tests (searched ${e.searched} file(s)${o})`}}function F(t,e){return{status:t,evidence:"heuristic",detail:e}}function ts(t,e){let n={entry:null,sameFile:null,crossFile:null,member:null,incomplete:null,searched:0,testOnly:0};if(t.family==="js"&&t.def.exported&&(t.exposedByList=!0,t.entryModules.has(t.file))){let o=t.def.method?`a method of ${t.def.exposedName}`:t.unit.name;return n.entry=`${o} is exported from entry module ${t.file}`,n}let i=[...t.mentions].filter(o=>o!==t.file).sort(),s=[t.file,...i.filter(o=>!t.isTestPath(o))];n.testOnly=i.length-(s.length-1);let r=s.slice(0,qi);r.length<s.length&&(n.incomplete=`${t.unit.name} is mentioned in ${s.length} files; only ${r.length} were searched`);for(let o of r){if(o!==t.file&&ns(t,n))break;let a=o===t.file?{kind:"ok",parsed:e}:t.parse(o);if(a.kind==="unreadable"){n.incomplete??=`${o} mentions ${t.unit.name} but could not be read`;continue}if(a.kind==="unparsed"){(N(K(o))===t.family||t.family==="js"&&Oi.has(y.extname(o)))&&(n.incomplete??=`${o} mentions ${t.unit.name} but could not be parsed`);continue}N(a.parsed.language)===t.family&&(n.searched+=1,is(t,o,a.parsed,n),o===t.file&&t.family==="js"&&Fs(t,n))}return n}function ns(t,e){return!!(e.entry||e.crossFile||t.shared<=1&&(e.sameFile||e.member))}function is(t,e,n,i){t.def.method?Ss(t,e,n,i):t.family==="js"?vs(t,e,n,i):t.family==="rust"?Cs(t,e,n,i):As(t,e,n,i)}function ss(t){let e=new Map;return n=>{let i=e.get(n);return i||(i=rs(n,t(n)),e.set(n,i)),i}}function rs(t,e){if(e===null)return{kind:"unreadable"};let n=K(t),i=n?We(n,e):null;return n&&i&&!os(i)?{kind:"ok",parsed:{language:n,tree:i}}:{kind:"unparsed"}}function os(t){let e=!1;return _(t.rootNode,n=>(e=n.type==="ERROR",e)),e}function N(t){switch(t){case"typescript":case"tsx":case"javascript":return"js";case"rust":return"rust";case"python":return"python";default:return null}}function _(t,e){let n=[t];for(;n.length>0;){let i=n.pop();if(e(i))return;let s=i.children;for(let r=s.length-1;r>=0;r--)n.push(s[r])}}function j(t,e){return t.childCount===0&&t.text===e}function ee(t,e){return t.startIndex>=e.startIndex&&t.endIndex<=e.endIndex}function B(t,e){return t!==null&&t.startIndex===e.startIndex&&t.endIndex===e.endIndex}function _e(t){return t.parent!==null&&B(t.parent.childForFieldName("name"),t)}function fn(t,e){for(let n=t.parent;n;n=n.parent)if(e.has(n.type))return n;return null}function De(t,e){return fn(t,e)!==null}function pn(t,e){let n=t.parent?.children??[],i=n.findIndex(r=>r.type===t.type&&B(r,t)),s=[];for(let r=i-1;r>=0;r--){let o=n[r];if(!Ke(o)){if(o.type!==e)break;s.push(o)}}return s}function as(t){let e=t;for(let n=0;e&&n<3;n++,e=e.parent)if(e.type==="export_statement")return!0;return!1}function Ne(t){return t?.type==="string"?t.text.slice(1,-1):null}function te(t){return Ne(t.childForFieldName("source"))}function ls(t,e){let n=[];_(t.tree.rootNode,r=>{if(r.startPosition.row!==e.startLine||r.endPosition.row!==e.endLine)return;let o=Ge(r,t.language);if(!(o?.name!==e.name||o.definitionNode!==r))return n.push(r),!0});let i=n[0];if(!i)return null;let s=N(t.language);return s==="js"?ds(i,e):s==="rust"?us(i,e):fs(i,e)}function ds(t,e){let n=["method_definition","method_signature","public_field_definition"].includes(t.type),i=n?fn(t,Mi):null,s=null;return n&&e.name==="constructor"?s="a constructor runs when its class is instantiated":n&&pn(t,"decorator").length>0?s="a decorator registers this method":n&&!i?s="a method of an object literal":i?.children.some(r=>r.type==="class_heritage")&&(s="the class extends or implements another type"),{node:t,method:n,exported:i?as(i):e.exported,exposedName:i?.childForFieldName("name")?.text??e.name,defaultExport:!n&&cs(t),implicit:s,testScoped:!1}}function cs(t){let e=t;for(let n=0;e&&n<3;n++,e=e.parent)if(e.type==="export_statement")return e.children.some(i=>i.type==="default");return!1}function us(t,e){let n=t.parent?.type==="declaration_list"?t.parent.parent:null,i=n?.type==="impl_item"||n?.type==="trait_item",s=null;return n?.type==="trait_item"?s="a default method of a trait":n?.type==="impl_item"&&n.childForFieldName("trait")?s="a method of a trait impl":hn(t).some(r=>!Wi.test(r))?s="an attribute registers this function":e.name==="main"&&(s="main is the program entry point"),{node:t,method:i,exported:!1,exposedName:e.name,defaultExport:!1,implicit:s,testScoped:Pe(t)}}function hn(t){return pn(t,"attribute_item").map(e=>e.text)}function Pe(t){for(let e=t;e;e=e.parent)if(!(e.type!=="mod_item"&&e.type!=="function_item")&&hn(e).some(n=>Ki.test(n)))return!0;return!1}function fs(t,e){let n=t.parent?.type==="decorated_definition",i=(n?t.parent.parent:t.parent)??null,s=i?.type==="block"&&i.parent?.type==="class_definition"?i.parent:null,r=null;return n?r="a decorator registers this function":/^__.+__$/.test(e.name)?r="a dunder method is called by the interpreter":s?.childForFieldName("superclasses")&&(r="the class has base classes"),{node:t,method:s!==null,exported:!1,exposedName:e.name,defaultExport:!1,implicit:r,testScoped:!1}}function ps(t){return t.family==="js"?hs(t):t.family==="rust"?gs(t):ys(t)}function hs({file:t,unit:e,def:n,exposedByList:i}){return n.method||!i?null:Yi.test(t)?`${t} is a framework entry file whose exports are called by convention`:Vi.has(e.name)?`${e.name} is an export name that frameworks and tools call by convention`:null}function gs({file:t,def:e}){let n=y.basename(t);return!Xi.has(n)||!ms(e.node)?null:`a public item of ${n} is part of the crate API`}function ms(t){for(let e=t;e&&e.type!=="source_file";e=e.parent){if(e.type==="block")return!1;if(e.type!=="function_item"&&e.type!=="mod_item")continue;if(e.children.find(i=>i.type==="visibility_modifier")?.text!=="pub")return!1}return!0}function ys({file:t,unit:e,def:n,parse:i}){if(n.node.parent?.type!=="module")return null;if(y.basename(t)==="__init__.py")return"a function of __init__.py is part of the package API";if(e.name.startsWith("_"))return null;let s=y.dirname(t);return i(y.join(s,"__init__.py")).kind==="unreadable"?null:`${e.name} is a public function of the package ${s}`}var Ce=new Set(["import_statement","import_from_statement","use_declaration"]);function Ss(t,e,n,i){let{name:s}=t.unit,r=t.family==="js"?Ui:t.family==="rust"?ji:Hi;_(n.tree.rootNode,o=>{if(!(!j(o,s)||!r.has(o.type))&&!(e===t.file&&ee(o,t.def.node))&&!(o.parent&&zi.has(o.parent.type))&&!De(o,Ce)&&!(t.family==="rust"&&Pe(o)))return i.member??={detail:`${s} is used in ${e}`,evidence:"heuristic"},!0})}function bs(t){if(!Li.has(t.type))return"skip";let e=t.parent;return e?e.type==="export_specifier"?e.parent?.parent?.childForFieldName("source")?"skip":"export-list":e.type==="import_specifier"?"skip":e.type==="export_statement"?"export-default":_e(t)&&!e.type.startsWith("jsx_")?"skip":"use":"use"}function vs(t,e,n,i){e===t.file?ws(t,n,i):xs(t,e,n,i)}function ws(t,e,n){let{name:i}=t.unit;_(e.tree.rootNode,s=>{if(!j(s,i)||ee(s,t.def.node))return;let r=bs(s);r==="use"&&(n.sameFile??={detail:`${i} is referenced in its own file`,evidence:"syntactic"}),(r==="export-list"||r==="export-default")&&(t.exposedByList=!0,r==="export-default"&&(t.defaultExport=!0),t.entryModules.has(t.file)&&(n.entry??=`exported from entry module ${t.file}`))})}function xs(t,e,n,i){let{name:s}=t.unit,r=new Set,o=[],a=!1;if(_(n.tree.rootNode,l=>{if(l.type==="import_statement")Es(t,e,l,r,i);else if(l.type==="export_statement")Rs(t,e,l,i);else if(l.type==="call_expression"){let d=l.childForFieldName("function"),u=d?.type==="import"||d?.type==="identifier"&&d.text==="require",c=l.childForFieldName("arguments")?.namedChildren[0];if(!u||!c)return;let f=Ne(c);if(f===null){i.incomplete??=`${e} loads a module by a computed specifier and mentions ${s}`;return}let p=t.trace(e,f,s);p==="defining"?a=!0:p==="opaque"&&D(t,e,f,i)}else l.type==="member_expression"&&l.childForFieldName("property")?.text===s&&o.push(l)}),o.some(l=>r.has(l.childForFieldName("object")?.text??""))&&(i.crossFile??={detail:`${s} is used through a namespace import in ${e}`,evidence:"syntactic"}),a){let l=!1;_(n.tree.rootNode,d=>(l=j(d,s)&&Bi.has(d.type),l)),l&&(i.crossFile??={detail:`${s} is loaded with require or import() in ${e}`,evidence:"syntactic"})}}function Es(t,e,n,i,s){let{name:r}=t.unit,o=n.namedChildren.find(d=>d.type==="import_require_clause");if(o){let d=Ne(o.childForFieldName("source"));if(d===null)return;let u=t.trace(e,d,r),c=o.namedChildren.find(f=>f.type==="identifier");u==="defining"&&c?i.add(c.text):u==="opaque"&&D(t,e,d,s);return}let a=te(n),l=n.namedChildren.find(d=>d.type==="import_clause");if(!(a===null||!l)){for(let d of l.namedChildren)if(d.type==="identifier"){let u=t.trace(e,a,"default");u==="defining"&&t.defaultExport?s.crossFile??={detail:`${r} is imported as a default export in ${e}`,evidence:"syntactic"}:u==="opaque"&&D(t,e,a,s)}else if(d.type==="namespace_import"){let u=t.trace(e,a,r),c=d.namedChildren.find(f=>f.type==="identifier");u==="defining"&&c?i.add(c.text):u==="opaque"&&D(t,e,a,s)}else if(d.type==="named_imports")for(let u of d.namedChildren){if(u.type!=="import_specifier"||u.childForFieldName("name")?.text!==r)continue;let c=t.trace(e,a,r);c==="defining"?s.crossFile??={detail:`${r} is imported in ${e}`,evidence:"syntactic"}:c==="opaque"&&D(t,e,a,s)}}}function D(t,e,n,i){i.incomplete??=`${e} may reach ${t.unit.name} through '${n}', which does not resolve to a project file (path aliases, packages)`}function Rs(t,e,n,i){let{name:s}=t.unit,r=te(n);if(r===null)return;let o=n.namedChildren.find(a=>a.type==="export_clause");if(!o){t.trace(e,r,s)==="opaque"&&D(t,e,r,i);return}for(let a of o.namedChildren){if(a.type!=="export_specifier"||a.childForFieldName("name")?.text!==s)continue;let l=t.trace(e,r,s);l==="opaque"?D(t,e,r,i):l==="defining"&&(t.entryModules.has(e)?i.entry??=`re-exported by entry module ${e}`:a.childForFieldName("alias")&&(i.incomplete??=`${e} re-exports ${s} under another name`))}}function Fs(t,e){if(e.entry||!t.exposedByList)return;let n=t.def.exposedName;for(let i of[...t.entryModules].sort()){if(i===t.file||t.isTestPath(i))continue;let s=t.parse(i);if(!(s.kind!=="ok"||N(s.parsed.language)!=="js"))for(let r of s.parsed.tree.rootNode.namedChildren){let o=r.type==="export_statement"?te(r):null;if(o===null)continue;let a=r.namedChildren.find(d=>d.type==="export_clause");if(t.trace(i,o,n)==="defining"&&(!a||a.namedChildren.some(d=>d.childForFieldName("name")?.text===n))){e.entry=`re-exported by entry module ${i}`;return}}}}function ks(t,e){if(!e.startsWith("."))return[];let n=y.join(y.dirname(t),e),i=y.extname(n),s=Ti[i];return s?[n,...s.map(r=>n.slice(0,-i.length)+r)]:[n,...dn.map(r=>n+r),...dn.map(r=>`${n}/index${r}`)]}function _s(t){return!t.startsWith(".")&&!t.startsWith("node:")}function Ds(t,e){let n=(i,s,r,o)=>{if(_s(s))return"opaque";let a=ks(i,s);if(a.includes(t))return"defining";if(o===0)return"none";let l="none";for(let d of a){let u=e(d);if(!(u.kind!=="ok"||N(u.parsed.language)!=="js"))for(let c of u.parsed.tree.rootNode.namedChildren){let f=c.type==="export_statement"?te(c):null;if(f===null)continue;let p=c.namedChildren.find(g=>g.type==="export_clause"),m=p?p.namedChildren.flatMap(g=>{let S=g.childForFieldName("name")?.text,$=g.childForFieldName("alias")?.text??S;return S&&$===r?[S]:[]}):[r];for(let g of m){let S=n(d,f,g,o-1);if(S==="defining")return"defining";S==="opaque"&&(l="opaque")}}}return l};return(i,s,r)=>n(i,s,r,Gi)}function Ns(t){let e=y.basename(t,".rs");return e==="lib"||e==="main"?new Set(["crate"]):new Set([e==="mod"?y.basename(y.dirname(t)):e])}function ke(t){return t?t.type==="scoped_identifier"?t.childForFieldName("name")?.text??null:t.text:null}function Ps(t,e){let n=y.basename(e)==="mod.rs"?y.dirname(e):e.slice(0,-3);return t.startsWith(`${n}/`)}function Cs(t,e,n,i){let{name:s}=t.unit,r=e===t.file,o=Ns(t.file),a=u=>u!==null&&(o.has(u)||r&&u==="self"||u==="super"&&!r&&Ps(e,t.file)),l=!1,d=!1;_(n.tree.rootNode,u=>{if(u.type==="use_wildcard"){let m=u.namedChildren[0]??null;!r&&a(ke(m))&&(l=!0);return}if(!j(u,s)||u.type!=="identifier"||r&&ee(u,t.def.node))return;let c=u.parent,f=!1;if(c?.type==="scoped_identifier"&&B(c.childForFieldName("name"),u))f=a(ke(c.childForFieldName("path")));else if(c?.type==="use_list"||c?.type==="use_as_clause"){let g=(c.type==="use_list"?c:c.parent)?.parent;f=!!((c.type==="use_as_clause"?B(c.childForFieldName("path"),u):!0)&&g?.type==="scoped_use_list"&&a(ke(g.childForFieldName("path"))))}else!De(u,Ce)&&!_e(u)&&(r?f=!0:d=!0);if(!f||Pe(u))return;let p={detail:r?`${s} is referenced in its own file`:`${s} is reached through a module path in ${e}`,evidence:"syntactic"};r?i.sameFile??=p:i.crossFile??=p}),l&&d&&(i.crossFile??={detail:`${s} is used after a glob import of its module in ${e}`,evidence:"syntactic"})}function $s(t){let e=t.replace(/\.pyi?$/,"");return y.basename(e)==="__init__"?y.dirname(e):e}function Q(t,e,n){let i=$s(e),s=/^\.*/.exec(n)[0].length,r=n.slice(s).replace(/\./g,"/");if(s===0)return i===r||i.endsWith(`/${r}`);let o=y.dirname(t);for(let a=1;a<s;a++)o=y.dirname(o);return i===(r?y.join(o,r):o)}function cn(t){if(t.type!=="aliased_import")return{name:t.text,local:t.text};let e=t.childForFieldName("name")?.text??t.text;return{name:e,local:t.childForFieldName("alias")?.text??e}}function As(t,e,n,i){let{name:s}=t.unit,r=e===t.file,o=new Set,a=[],l=!1,d=!1;_(n.tree.rootNode,u=>{if(u.type==="import_from_statement"&&!r){let[c,...f]=u.namedChildren,p=c?.text??"";for(let m of f){if(m.type==="wildcard_import"){Q(e,t.file,p)&&(l=!0);continue}let{name:g,local:S}=cn(m);g===s&&Q(e,t.file,p)?i.crossFile??={detail:`${s} is imported in ${e}`,evidence:"syntactic"}:Q(e,t.file,`${p}${p.endsWith(".")?"":"."}${g}`)&&o.add(S)}}else if(u.type==="import_statement"&&!r)for(let c of u.namedChildren){let{name:f,local:p}=cn(c);Q(e,t.file,f)&&o.add(p)}else if(u.type==="attribute"&&u.childForFieldName("attribute")?.text===s)a.push(u);else if(j(u,s)&&u.type==="identifier"){if(De(u,Ce)||_e(u)||u.parent?.type==="attribute"&&B(u.parent.childForFieldName("attribute"),u)||r&&ee(u,t.def.node))return;r?i.sameFile??={detail:`${s} is referenced in its own file`,evidence:"syntactic"}:d=!0}}),a.some(u=>o.has(u.childForFieldName("object")?.text??""))&&(i.crossFile??={detail:`${s} is used through a module import in ${e}`,evidence:"syntactic"}),l&&d&&(i.crossFile??={detail:`${s} is used after a wildcard import of its module in ${e}`,evidence:"syntactic"})}var x=class extends Error{constructor(){super("the index database is unavailable")}},se=class extends Error{constructor(){super("not a git repository")}},mn=25,Os=5e3,Ts=24*36e5,Ms=168*36e5,Ls=4,Us=200,Bs=500,js=["reuse-match"],Hs=["*.ts","*.tsx","*.mts","*.cts","*.js","*.jsx","*.mjs","*.cjs","*.vue","*.svelte","*.astro","*.rs","*.py"];function wn(t){return new Oe(t)}var Oe=class{constructor(e){this.deps=e;this.outcomes=wt(e.stateDir),this.pruneIfDue(),this.indexLiveSessions()}deps;analyzer=null;corpusState="idle";rebuildOnNextGeneration=!1;corpusDone=Promise.resolve();db=null;dbMissing=!1;blobReader=null;closed=!1;closing;draining=!1;analysisCounter=0;lastPruneAt;runtimes=new Map;sessions=new Map;changed=new Set;requests=new Set;muted=new Set;logged=new Set;outcomes;async handle(e){if(this.closed)return this.failure("sentinel service is closed");this.pruneIfDue();let n=this.dispatch(e).catch(i=>(this.deps.log(`sentinel ${e.event} failed: ${b(i)}`),this.failure(b(i))));this.requests.add(n);try{return await n}finally{this.requests.delete(n)}}filesChanged(e){if(!this.closed){if(e.length===0){this.pathSetUnknown();return}for(let n of this.sessions.values())for(let i of e)n.changedKeys.delete(i);this.refreshTouched(e);for(let n of e)this.changed.add(n);this.drainChanges()}}pathSetUnknown(){this.rebuildOnNextGeneration=!0,this.analyzer=null,this.corpusState="idle",this.changed.clear();for(let e of this.sessions.values())e.changedKeys.clear();this.refreshTouched(null)}generationPublished(){this.releaseDb(),this.rebuildOnNextGeneration&&(this.rebuildOnNextGeneration=!1,this.analyzer=null,this.corpusState="idle")}releaseDb(){this.db=null,this.dbMissing=!1}liveSessionCount(){try{let e=this.deps.now(),{leaseIdleMs:n}=this.loadSettings();return[...this.sessions.values()].filter(i=>$e(i,e,n)).length}catch(e){return this.deps.log(`sentinel could not count live sessions: ${b(e)}`),0}}close(){return this.closing??=this.shutdown(),this.closing}async shutdown(){this.closed=!0;let e=[...this.runtimes.values()].flatMap(n=>[...n.analyses.values()]);await Promise.allSettled([...this.requests,this.corpusDone,...e]),await this.blobReader?.close(),this.blobReader=null,this.db=null}async dispatch(e){switch(e.event){case"session-start":return this.sessionStart(e);case"edit":return this.edit(e);case"prompt":return this.prompt(e);case"stop":return this.stop(e);case"session-end":return this.sessionEnd(e);default:return this.failure(`unknown sentinel event ${String(e.event)}`)}}async sessionStart(e){let n=e.source??"startup";return this.openLedger(e,n)?(this.startCorpusBuild(),n!=="resume"&&n!=="compact"?this.respond([],{},this.status()):this.relist(this.runtimeFor(e.session),e.session)):this.unsupported(e)}async edit(e){let n=this.activeSession(e);if(!n)return this.unsupported(e);let i=e.files??[],s=this.deps.now();for(let o of i){let a={path:o.path,sha256:o.sha256??null,change:o.change};this.track(Kt(this.deps.stateDir,e.session,a,s))}this.startCorpusBuild(),this.checkActedOn(n,e.session),this.promoteHeld(n,e.session);let r=this.startAnalysis(n,e.session,i);return e.wait&&await r,this.deliverReuse("edit",e.session,n)}async prompt(e){let n=this.activeSession(e);return n?(this.startCorpusBuild(),this.promoteHeld(n,e.session),this.deliverReuse("prompt",e.session,n)):this.unsupported(e)}async stop(e){let n=this.activeSession(e);if(!n)return this.unsupported(e);let{session:i}=e;this.startCorpusBuild(),this.promoteHeld(n,i);let s=this.settings(),r=this.reuseFindings(n,this.ledger(i)),o=await this.stopAnalysis(n,i,s),a={findings:[...r.findings,...o.findings],suppressed:r.suppressed+o.suppressed,details:new Map([...r.details,...o.details])},{findings:l}=a,d=this.ledger(i),u=T({event:"stop",findings:l,settings:s,alreadyDelivered:new Set(d.delivered),alreadyBlocked:new Set(d.blocked),stopHookActive:e.stopHookActive===!0,serviceStatus:this.status(),...o.unverifiedReason?{unverifiedReason:o.unverifiedReason}:{}});this.commit(n,i,u,a);let c=ie(u),f=o.notes.map(g=>`codebaseiq sentinel: ${g}`),p=[u.userText,...f].filter(g=>g!==void 0).join(`
13
+ `);p&&(c.userText=p);let m={pending:n.analyses.size+n.held.length,suppressed:a.suppressed,shadowed:u.shadowed.length};return this.respond(l,c,this.status(m))}async sessionEnd(e){return Vt(this.deps.stateDir,e.session,this.deps.now()),this.sessions.delete(e.session),this.runtimes.delete(e.session),this.respond([],{},this.status())}runtimeFor(e){let n=this.runtimes.get(e);return n||(n={unsupported:!1,baselines:new Map,held:[],ready:new Map,delivered:new Map,restored:!1,analyses:new Map,shadowRecorded:new Set},this.runtimes.set(e,n)),n}sessionEntry(e){let n=this.sessions.get(e);return n||(n={lastSeenAt:0,endedAt:void 0,touched:new Set,changedKeys:new Map},this.sessions.set(e,n)),n}track(e){if(!e)return;let n=this.sessionEntry(e.session);n.lastSeenAt=e.lastSeenAt,n.endedAt=e.endedAt,n.touched=new Set(Object.keys(e.touched))}indexLiveSessions(){try{let e=Zt(this.deps.stateDir,this.deps.now(),this.loadSettings().leaseIdleMs,n=>this.logOnce(n));for(let n of e)this.track(n)}catch(e){this.deps.log(`sentinel could not index the live sessions: ${b(e)}`)}}pruneIfDue(){try{let e=this.deps.now();if(this.lastPruneAt!==void 0&&e-this.lastPruneAt<Ts)return;this.lastPruneAt=e;let n=Math.max(Ms,Ls*this.loadSettings().leaseIdleMs);Qt(this.deps.stateDir,n,e,i=>this.logOnce(i));for(let[i,s]of this.sessions)e-s.lastSeenAt>n&&this.sessions.delete(i)}catch(e){this.deps.log(`sentinel could not prune old sessions: ${b(e)}`)}}activeSession(e){let n=this.runtimeFor(e.session);return n.unsupported?null:w(this.deps.stateDir,e.session)||this.openLedger(e,"resume")?n:null}openLedger(e,n){let i=this.runtimeFor(e.session),s=new Set((e.files??[]).map(r=>r.path));try{let r=Wt({stateDir:this.deps.stateDir,session:e.session,host:e.host,source:n,capture:()=>this.captureBaseline(s),now:this.deps.now()});return this.track(r),i.unsupported=!1,r}catch(r){if(!(r instanceof se))throw r;return i.unsupported=!0,null}}captureBaseline(e=new Set){let n=It({projectRoot:this.deps.projectRoot,stateDir:this.deps.stateDir,isTrackedInput:s=>this.deps.isInputPath(s)});if(n.kind==="not-a-repository")throw new se;if(e.size===0)return n.baseline;let i=n.baseline.dirty.filter(s=>!e.has(s.path));return{...n.baseline,dirty:i,approximated:!0}}ledger(e){let n=w(this.deps.stateDir,e);if(!n)throw new Error(`no sentinel ledger for session ${e}`);return n}repin(e,n){this.track(Xt(this.deps.stateDir,n.session,this.captureBaseline(),this.deps.now())),e.baselines.clear(),this.sessionEntry(n.session).changedKeys.clear(),e.held=[]}async baselineEntry(e,n,i){let s=`${n.baseline.capturedAt}:${i}`,r=e.baselines.get(s);if(r)return r;let o;try{o=await Ot(n.baseline,i,this.reader(),this.deps.stateDir)}catch(l){return this.deps.log(`sentinel could not read the baseline of ${i}: ${b(l)}`),{units:"unknown",createdInSession:!1}}let a=o===null?{units:null,createdInSession:!0}:{units:G(this.currentDb(),i,o)?.units??"unknown",createdInSession:!1};return e.baselines.set(s,a),a}reader(){if(this.closed)throw new Error("sentinel service is closed");return this.blobReader??=new V(this.deps.projectRoot)}currentDb(){if(this.db)return this.db;let e=this.deps.openDb();if(this.dbMissing=e===null,!e)throw new x;return this.logged.delete(new x().message),this.db=e,e}corpusStatus(){return this.corpusState==="ready"?this.dbMissing?"unavailable":"ready":this.corpusState==="unavailable"?"unavailable":"building"}startCorpusBuild(){if(this.corpusState==="building"||this.corpusState==="ready")return this.corpusDone;let e=this.createAnalyzer();return this.analyzer=e,this.corpusState="building",this.corpusDone=this.buildCorpus(e).then(()=>{this.analyzer!==e||this.closed||(this.corpusState="ready",this.drainChanges())},n=>{this.analyzer===e&&(this.analyzer=null,this.corpusState="unavailable",this.logOnce(`sentinel corpus is unavailable: ${b(n)}`))}),this.corpusDone}createAnalyzer(){let e=()=>this.currentDb();return new q({get db(){return e()},readText:n=>this.deps.readText(n),isInputPath:n=>this.deps.isInputPath(n),allowsDependency:(n,i)=>_t(this.deps.config,n,i)})}async buildCorpus(e){let n=this.inputPaths();for(let i=0;i<n.length;i+=1){if(this.closed||this.analyzer!==e)return;this.updateCorpusFile(e,n[i]),(i+1)%mn===0&&await gn()}}inputPaths(){let e=this.currentDb(),n=this.deps.listInputPaths();if(n===null)throw new Error("the list of indexed files is unavailable");if(n.length===0&&W(e,{includeIgnored:!1}).some(i=>this.deps.isInputPath(i)))throw new Error("the list of indexed files is empty although the index holds source files");return n}updateCorpusFile(e,n){try{e.updateFile(n)}catch(i){if(i instanceof x)throw i;this.deps.log(`sentinel left ${n} out of the corpus: ${b(i)}`)}}async drainChanges(){if(this.draining||this.corpusState==="building")return;let e=this.analyzer;if(!e||this.corpusState!=="ready"){this.changed.clear();return}this.draining=!0;try{let n=0;for(let i of this.changed){this.changed.delete(i);try{this.updateCorpusFile(e,i)}catch(s){throw this.changed.add(i),s}if(n+=1,n%mn===0&&(await gn(),this.closed||this.analyzer!==e))break}}catch(n){n instanceof x||this.deps.log(`sentinel corpus update failed: ${b(n)}`)}finally{this.draining=!1}}refreshTouched(e){try{let n=this.deps.now(),{leaseIdleMs:i}=this.loadSettings();for(let[s,r]of this.sessions){if(!$e(r,n,i))continue;let o=e===null?[...r.touched]:e.filter(l=>r.touched.has(l));if(o.length===0)continue;let a=o.map(l=>{let d=this.deps.readText(l);return{path:l,sha256:d===null?null:Is("sha256").update(d).digest("hex"),change:d===null?"delete":"write"}});this.track(Gt(this.deps.stateDir,s,a,n))}}catch(n){this.deps.log(`sentinel could not refresh touched files: ${b(n)}`)}}startAnalysis(e,n,i){let s=i.filter(l=>this.deps.isInputPath(l.path));if(s.length===0)return Promise.resolve();let r=this.analysisKey(s),o=e.analyses.get(r);if(o)return o;let a=this.analyze(e,n,s).catch(l=>this.logOnce(`sentinel analysis failed: ${b(l)}`)).finally(()=>e.analyses.delete(r));return e.analyses.set(r,a),a}analysisKey(e){return e.some(n=>n.sha256===void 0)?`unhashed:${this.analysisCounter+=1}`:e.map(n=>`${n.path}\0${n.sha256}\0${n.change}`).sort().join(`
14
+ `)}async analyze(e,n,i){do await this.startCorpusBuild();while(!this.closed&&(this.corpusState==="idle"||this.corpusState==="building"));let s=this.analyzer;if(!s||this.corpusState!=="ready")return;let r=w(this.deps.stateDir,n);if(!r)return;let o=this.sessionEntry(n);for(let u of i)o.changedKeys.delete(u.path);let a=[];for(let u of i){let c=await this.baselineEntry(e,r,u.path);a.push({path:u.path,baselineUnits:c.units,createdInSession:c.createdInSession})}let l=await this.inFlightKeys(s),d=s.analyzeEdit({session:n,files:a,inFlight:l});e.held.push(...d.held),this.addReady(e,d.matches,yn(w(this.deps.stateDir,n))),d.skipped.length>0&&this.deps.log(`sentinel skipped ${d.skipped.join(", ")}: the session baseline is unknown`)}async inFlightKeys(e){let n=new Set,i=this.deps.now(),{leaseIdleMs:s}=this.loadSettings();for(let[r,o]of this.sessions){if(!$e(o,i,s))continue;let a;for(let l of o.touched){if(!this.deps.isInputPath(l))continue;let d=o.changedKeys.get(l);if(!d){if(a??=w(this.deps.stateDir,r),!a)break;let u=await this.baselineEntry(this.runtimeFor(r),a,l),c=e.currentUnits(l);d=c?ct(l,u.units,c):new Set,o.changedKeys.set(l,d)}for(let u of d)n.add(u)}}return n}addReady(e,n,i){let s=new Set;for(let r of n){let o=ne(r);if(s.has(o))continue;s.add(o);let a=e.delivered.get(o);a?e.delivered.set(o,{...a,match:r}):i.has(o)||e.ready.set(o,r)}}promoteHeld(e,n){let i=this.analyzer;if(!(!i||e.held.length===0))try{let s=i.recheckHeld(e.held);e.held=[],this.addReady(e,s,yn(w(this.deps.stateDir,n)))}catch(s){if(!(s instanceof x))throw s}}verifyReady(e){let n=this.analyzer;if(!(!n||e.ready.size===0))try{let i=n.recheckHeld([...e.ready.values()]);e.ready=new Map(i.map(s=>[ne(s),s]))}catch(i){if(!(i instanceof x))throw i}}restoreDelivered(e,n){if(e.restored)return;let i=w(this.deps.stateDir,n);if(e.restored=!0,!!i?.deliveredFindings)for(let[s,r]of Object.entries(i.deliveredFindings))try{let o=Ws(r,i.timesSeen[s]??0);o&&!e.delivered.has(o.finding.id)&&e.delivered.set(o.finding.id,o)}catch(o){this.logOnce(`sentinel could not restore the delivered finding ${s}: ${b(o)}`)}}forgetDelivered(e,n){n.length>0&&this.track(Jt(this.deps.stateDir,e,n,this.deps.now()))}checkActedOn(e,n){this.restoreDelivered(e,n);let i=this.analyzer;if(!i||e.delivered.size===0)return;let s=[];try{for(let[r,{finding:o}]of e.delivered){let a=o.counterpart;if(!a)continue;let l=i.currentUnits(o.subject.file);xt(o,l,i.currentUnits(a.file))&&(e.delivered.delete(r),s.push(r),this.recordOutcome(n,o,"acted-on"))}}catch(r){if(!(r instanceof x))throw r}finally{this.forgetDelivered(n,s)}}unresolvedDelivered(e,n){let i=this.analyzer;if(!i||e.delivered.size===0)return[];let s;try{s=i.recheckHeld([...e.delivered.values()].map(l=>l.match))}catch(l){if(l instanceof x)return[];throw l}let r=new Map(s.map(l=>[ne(l),l])),o=[],a=[];for(let[l,d]of e.delivered){let u=r.get(l);u?o.push({...d,match:u}):(e.delivered.delete(l),a.push(l))}return this.forgetDelivered(n,a),o}reuseFindings(e,n){this.verifyReady(e);let i={findings:[],suppressed:0,details:new Map};for(let[s,r]of e.ready){let o=this.decorate(Y(r,n.timesSeen[s]??0),n);if(this.isSuppressed(o)){i.suppressed+=1;continue}i.findings.push(o),i.details.set(o.id,Ae(o,r.subject,r.counterpart))}return i}deliverReuse(e,n,i){let s=this.ledger(n),r=this.reuseFindings(i,s),{findings:o,suppressed:a}=r,l=T({event:e,findings:o,settings:this.settings(),alreadyDelivered:new Set(s.delivered),alreadyBlocked:new Set(s.blocked),stopHookActive:!1,serviceStatus:this.status()});this.commit(i,n,l,r);let d=Math.max(o.length-l.delivered.length-l.shadowed.length,0),u={pending:i.analyses.size+i.held.length+d,suppressed:a,shadowed:l.shadowed.length};return this.respond(o,ie(l),this.status(u))}relist(e,n){this.checkActedOn(e,n);let i=this.ledger(n),s={findings:[],suppressed:0,details:new Map};for(let{match:l}of this.unresolvedDelivered(e,n)){let d=this.decorate(Y(l,i.timesSeen[ne(l)]??0),i);if(e.delivered.set(d.id,{finding:d,match:l}),this.isSuppressed(d)){s.suppressed+=1;continue}s.findings.push(d),s.details.set(d.id,Ae(d,l.subject,l.counterpart))}let{findings:r,suppressed:o}=s,a=T({event:"session-start",findings:r,settings:this.settings(),alreadyDelivered:new Set(i.delivered),alreadyBlocked:new Set(i.blocked),stopHookActive:!1,serviceStatus:this.status()});return this.commit(e,n,a,s,"redelivered"),this.respond(r,ie(a),this.status({suppressed:o,shadowed:a.shadowed.length}))}commit(e,n,i,s,r){let o=new Map(s.findings.map(c=>[c.id,c])),a=(c,f)=>{let p=s.details.get(c);return p!==void 0&&f?`${p} | ${f}`:p},l=this.deps.now(),d=new Map;for(let c of i.delivered){let f=o.get(c),p=e.ready.get(c)??e.delivered.get(c)?.match;f?.family==="reuse-match"&&p&&d.set(c,{finding:f,match:p})}let u=Object.fromEntries([...d].map(([c,f])=>[c,zs(f)]));this.track(qt(this.deps.stateDir,n,i.delivered,l,u));for(let c of i.delivered){let f=o.get(c);f&&this.recordOutcome(n,f,"shown",a(c,r))}for(let[c,f]of d)e.delivered.set(c,f),e.ready.delete(c);i.blocked.length>0&&this.track(Yt(this.deps.stateDir,n,i.blocked,l));for(let c of i.blocked){let f=o.get(c);f&&this.recordOutcome(n,f,"blocked",a(c))}for(let c of i.shadowed)e.shadowRecorded.has(c.id)||(e.shadowRecorded.add(c.id),this.recordOutcome(n,c,"shadowed",a(c.id)))}recordOutcome(e,n,i,s){try{this.outcomes.append({at:new Date(this.deps.now()).toISOString(),session:e,findingId:n.id,family:n.family,kind:i,...s?{detail:s}:{}})}catch(r){this.deps.log(`sentinel could not record a ${i} outcome: ${b(r)}`)}}decorate(e,n){return n.baseline.approximated?{...e,labels:[...e.labels,"baseline-approximated"]}:e}isSuppressed(e){let n=this.deps.now(),i=(this.deps.config.suppressions??[]).filter(r=>!(r.expiresAt&&Date.parse(r.expiresAt)<=n));return yt(e,i,r=>this.deps.readText(r)?.split(/\r?\n/)??null)!==null}async stopAnalysis(e,n,i){let s={findings:[],suppressed:0,details:new Map,notes:[]},r=this.ledger(n),o=d=>Object.values(i.delivery).includes("live")?d:void 0,a;try{a=Tt({projectRoot:this.deps.projectRoot,baseline:r.baseline,ledgerPaths:Object.keys(r.touched)})}catch(d){return this.deps.log(`sentinel stop could not read the session delta: ${b(d)}`),s.unverifiedReason=o(b(d)),s}if(a.head==="unrelated")return this.repin(e,r),s.notes.push("HEAD moved to unrelated history; session baseline reset"),s;let l=a.revertedOrStashed.filter(d=>this.deps.isInputPath(d)).length;if(l>0&&s.notes.push(`${l} edited ${l===1?"file":"files"} reverted or stashed; unverified`),this.corpusStatus()!=="ready")return s;try{let d=await this.unwiredFindings(e,r,a.changed.filter(u=>this.deps.isInputPath(u)));s.findings.push(...d.findings),s.suppressed+=d.suppressed;for(let[u,c]of d.details)s.details.set(u,c)}catch(d){if(!(d instanceof x))throw d;s.unverifiedReason=o(d.message)}return s}async unwiredFindings(e,n,i){let s=this.analyzer,r={findings:[],suppressed:0,details:new Map};if(!s)return r;let o=[];for(let f of i){let p=s.currentUnits(f);if(!p)continue;let m=await this.baselineEntry(e,n,f);if(m.units!=="unknown")for(let g of Ks(m.units,p))o.push({file:f,unit:g})}if(o.length===0)return r;let{projectRoot:a}=this.deps,l,d;try{let f=[...new Set(o.map(({unit:p})=>p.name))];l=bt(a,f,{pathspecs:Hs,timeoutMs:Os})}catch(f){d=f instanceof Error?f:new Error(String(f))}let u=f=>this.deps.readText(f),c=un({projectRoot:a,candidates:o,readText:u,grep:()=>{if(!l)throw d??new Error("the repository search did not run");return l},isTestPath:Nt,entryModules:Dt(a,u),definitionCountByName:l?this.definitionCounts(s,l):new Map});for(let f of c){if(f.status!=="unwired")continue;let{file:p,unit:m}=f,g=n.timesSeen[M("unwired",p,m.container,m.name)]??0,S=this.decorate(mt(f,g),n);if(this.isSuppressed(S)){r.suppressed+=1;continue}r.findings.push(S),r.details.set(S.id,Ae(S,{file:p,unit:m}))}return r}definitionCounts(e,n){let i=new Map,s=new Map;for(let[r,o]of n){let a=0;for(let l of o){if(!this.deps.isInputPath(l))continue;let d=i.get(l);d||(d=e.currentUnits(l)??[],i.set(l,d)),a+=d.filter(u=>u.name===r).length}s.set(r,a)}return s}loadSettings(){return ln(this.deps.stateDir,e=>this.logOnce(e))}settings(){let e=this.loadSettings(),n={...e.delivery};for(let i of js){if(!(n[i]==="live"&&Et(this.outcomes.readRecent(i,Bs),i))){this.muted.delete(i);continue}if(n[i]="shadow",this.muted.has(i))continue;this.muted.add(i);let{window:r,minActedOnRate:o}=C;this.deps.log(`sentinel muted ${i}: under ${Math.round(o*100)}% of the last ${r} delivered findings were acted on`)}return{...e,delivery:n}}status(e={}){return{corpus:this.corpusStatus(),pending:0,suppressed:0,shadowed:0,...e}}respond(e,n,i){return{ok:!0,serviceVersion:this.deps.serviceVersion,token:this.deps.token,findings:e,delivery:n,status:i}}failure(e){return{ok:!1,serviceVersion:this.deps.serviceVersion,token:this.deps.token,reason:e}}unsupported(e){let n={corpus:"unavailable",pending:0,suppressed:0,shadowed:0};if(e.event!=="stop")return this.respond([],{},n);let i=T({event:"stop",findings:[],settings:this.settings(),alreadyDelivered:new Set,alreadyBlocked:new Set,stopHookActive:!1,serviceStatus:n,unverifiedReason:"not a git repository"});return this.respond([],ie(i),n)}logOnce(e){this.logged.has(e)||(this.logged.size>=Us&&this.logged.clear(),this.logged.add(e),this.deps.log(e))}};function ne(t){return M("reuse-match",t.subject.file,t.subject.unit.container,t.subject.unit.name)}function yn(t){return new Set(t?.delivered)}function $e(t,e,n){return t.endedAt===void 0&&e-t.lastSeenAt<=n}function Ae(t,e,n){let i=n?`${Ie(e)} <-> ${Ie(n)}`:Ie(e);return`${t.summary} | ${i}`}function Ie({file:t,unit:e}){return`${t}#${[...e.container,e.name].join(".")}`}function zs({finding:t,match:e}){return{family:t.family,subject:Sn(e.subject),counterpart:Sn(e.counterpart),labels:t.labels,summary:t.summary}}function Sn({file:t,unit:e}){return{file:t,name:e.name,container:e.container,ordinal:e.ordinal,exactHash:e.exactHash,line:e.startLine+1,signature:e.signature}}function Ws(t,e){let{counterpart:n}=t;if(t.family!=="reuse-match"||!n)return null;let i={subject:bn(t.subject),counterpart:bn(n),basis:t.labels.includes("exact-body-same-name")?"exact-body-same-name":"exact-body",inFlight:t.labels.includes("in-flight"),crossBoundary:t.labels.includes("cross-boundary")};return{finding:{...Y(i,e),labels:t.labels,summary:t.summary},match:i}}function bn(t){let e=t.line-1;return{file:t.file,unit:{name:t.name,container:t.container,ordinal:t.ordinal,startLine:e,endLine:e,bodyStartLine:e,bodyLines:0,tokenCount:0,signature:t.signature,exactHash:t.exactHash,shapeHash:"",calleeLeaves:[],exported:!1}}}function ie({modelText:t,userText:e,block:n}){return{...t!==void 0?{modelText:t}:{},...e!==void 0?{userText:e}:{},...n!==void 0?{block:n}:{}}}function Ks(t,e){let n=new Set((t??[]).map(vn));return O(t,e).filter(i=>!n.has(vn(i)))}function vn(t){return`${t.container.join(".")}#${t.name}`}function b(t){return t instanceof Error?t.message:String(t)}var tr=5e3,nr=64,ir=5e3,sr=5e3;async function rr(t,e,n={}){let i=h=>e.postMessage({kind:"log",message:h}),s=Ys.native(t.projectRoot),r=et(s),o=nt(r,tt()),a=Gs(16).toString("hex"),l=or((n.loadConfig??Xe)(s),s,i),d=ar(s,l),u=lr(n.openIndex??(()=>kn(t.dbPath)?Qe(s):null),d.isInputPath,i),c=(n.createService??wn)({projectRoot:s,stateDir:_n(t.cacheDir,Je),config:l,openDb:u.openDb,readText:d.readText,listInputPaths:u.listInputPaths,isInputPath:d.isInputPath,serviceVersion:t.cliVersion,token:a,now:Date.now,log:i}),f=-1,p=(h=!1)=>{let v=0;try{v=c.liveSessionCount()}catch(ae){i(`session count failed: ${E(ae)}`)}!h&&v===f||(f=v,e.postMessage({kind:"sessions",live:v}))},m=setInterval(()=>p(!0),n.sessionReportIntervalMs??ir);m.unref();let g=h=>({ok:!1,serviceVersion:t.cliVersion,token:a,reason:h}),S=async h=>{try{return await c.handle(h)}catch(v){return i(`request failed: ${E(v)}`),g("internal error")}finally{p()}},$=new Set,H=Zs(h=>{$.add(h),h.once("close",()=>$.delete(h)),dr(h,S,g)});H.maxConnections=nr;let re,Me,Dn=new Promise(h=>{Me=h}),oe=()=>(re??=(async()=>{clearInterval(m),rt(t.userCacheRoot,r,process.pid);let h=fr(H);try{await c.close()}catch(v){i(`service close failed: ${E(v)}`)}for(let v of $)v.destroy();await h,u.close(),Me()})(),re);try{cr(o),await ur(H,o),H.on("error",h=>i(`pipe error: ${h.message}`)),st(t.userCacheRoot,r,{pid:process.pid,socketPath:o,serviceVersion:t.cliVersion,projectRoot:s,startedAt:new Date().toISOString(),token:a})}catch(h){throw await oe(),h}let Nn=h=>{switch(h.kind){case"filesChanged":c.filesChanged(h.paths);break;case"releaseDb":try{c.releaseDb()}finally{u.release()}break;case"generationPublished":u.published(),c.generationPublished();break;case"shutdown":oe();break}};e.on("message",h=>{let v=mr(h);if(!v){i("ignored an unrecognized command");return}try{Nn(v)}catch(ae){i(`${v.kind} failed: ${E(ae)}`)}});let Pn=pr(it(t.userCacheRoot,r),async h=>{await S({...h,wait:!1})},()=>re!==void 0,i).catch(h=>i(`inbox replay failed: ${E(h)}`));return p(!0),{socketPath:o,inboxDrained:Pn,closed:Dn,close:oe}}function or(t,e,n){let i=t.suppressions??[],s=i,r=Number.NEGATIVE_INFINITY;return Object.defineProperty({...t},"suppressions",{enumerable:!0,get(){let o=Date.now();if(o-r>=sr){r=o;try{s=[...i,...Ze(e).suppressions]}catch(a){n(`repository suppressions could not be read: ${E(a)}`)}}return s}})}function ar(t,e){let n=e.languages&&e.languages.length>0?e.languages:Ue,i;return{isInputPath(s){let r=Fn(s);return!r||Le(r,n)!=="source"?!1:(i??=qe(t),!i.isIgnored(r))},readText(s){let r=Fn(s);if(!r)return null;try{return ue(_n(t,r),{maxBytes:le,inputKind:"sentinel source file"})}catch{return null}}}}function Fn(t){let e=xn.normalize(t.replaceAll("\\","/"));if(!(e===".."||e.startsWith("../")||xn.isAbsolute(e))&&!/^[A-Za-z]:/u.test(e))return e}function lr(t,e,n){let i=null,s,r=()=>{let a=i;if(i=null,!!a)try{a.close()}catch(l){n(`closing the index failed: ${E(l)}`)}},o=()=>{if(i)return i;try{i=t()}catch(a){n(`index unavailable: ${E(a)}`)}return i};return{openDb:o,listInputPaths(){if(!s){let a=o();if(!a)return[];s=W(a,{includeIgnored:!1}).filter(e)}return[...s]},release:r,published(){r(),s=void 0},close:r}}function dr(t,e,n){let i=!1,s=o=>{if(t.destroyed)return;let a;try{a=me(o,ge)}catch{a=me(n("response exceeded the size limit"),ge)}t.end(a)},r=ot(he,o=>{i||(i=!0,t.setTimeout(0),pe(o)?e(o).then(s):s(n("malformed sentinel request")))},o=>s(n(o.message)));t.setTimeout(tr),t.on("timeout",()=>t.destroy()),t.on("data",o=>r.push(o)),t.on("error",()=>t.destroy())}function cr(t){if(process.platform==="win32")return;let e=Qs(t);if(Js(e,{recursive:!0,mode:448}),typeof process.getuid=="function"&&Xs(e).uid!==process.getuid())throw new Error(`sentinel socket directory ${e} is owned by another user`);qs(e,448),Te(t,{force:!0})}function ur(t,e){return new Promise((n,i)=>{t.once("error",i),t.listen(e,()=>{t.off("error",i),n()})})}function fr(t){return new Promise(e=>{t.close(()=>e())})}async function pr(t,e,n,i){let s=`${t}.draining`;for(let r=0;r<2&&!n();r+=1){if(!kn(s))try{Vs(t,s)}catch(a){a.code!=="ENOENT"&&i(`inbox could not be claimed: ${E(a)}`);return}let o;try{o=ue(s,{maxBytes:le,inputKind:"sentinel inbox"})}catch(a){i(`inbox was discarded: ${E(a)}`),Te(s,{force:!0});continue}for(let a of hr(o.split(`
15
+ `).flatMap(l=>gr(l)??[]))){if(n())return;await e(a)}Te(s,{force:!0})}}function hr(t){let e=new Map;for(let n of t){if(n.event!=="edit")continue;let i=e.get(n.session)??new Map;for(let s of n.files??[])i.set(s.path,s);e.set(n.session,i)}return t.map(n=>{let i=n.event==="session-start"?e.get(n.session):void 0;return i&&i.size>0?{...n,files:[...i.values()]}:n})}function gr(t){if(!(t.trim().length===0||t.length>he))try{let e=JSON.parse(t);return pe(e)?e:void 0}catch{return}}function mr(t){if(typeof t!="object"||t===null)return;let{kind:e,paths:n}=t;switch(e){case"filesChanged":return Array.isArray(n)&&n.every(i=>typeof i=="string")?{kind:e,paths:n}:void 0;case"generationPublished":case"releaseDb":case"shutdown":return{kind:e};default:return}}function E(t){return t instanceof Error?t.message:String(t)}function yr(t){return typeof t=="object"&&t!==null&&t.kind==="sentinel-worker"}if(!er&&En&&yr(Rn)){let t=En;rr(Rn,t).then(e=>e.closed.then(()=>t.close()),e=>{t.postMessage({kind:"log",message:`failed to start: ${E(e)}`}),t.close()})}export{rr as runSentinelWorker};
16
+ //# sourceMappingURL=sentinel-worker.js.map
@@ -1,2 +1,2 @@
1
- import{a as c,c as u}from"./chunk-6BQ3DSPK.js";import"./chunk-FAJQ7LWY.js";import{M as l}from"./chunk-Z54RD7VL.js";import{f as d}from"./chunk-FDGD5AB5.js";import"./chunk-RU65DDUP.js";import"./chunk-QW7EP6WI.js";import"./chunk-3IER7Q6H.js";import"./chunk-FM5BPL4V.js";import"./chunk-DRENNWRG.js";import"./chunk-RDBI2RXU.js";import{g as a,h as s}from"./chunk-R2NOK63J.js";import"./chunk-EF2R3WNQ.js";import"./chunk-WE5RZHZ7.js";import{parentPort as p,workerData as S}from"worker_threads";var i=k(S);if(!p)throw new Error("TypeScript mailbox worker requires a parent port.");if(i.kind==="index"){let t=new c({projectRoot:i.projectRoot,currentGeneration:()=>d(i.dbPath)});p.on("message",e=>{let r=m(e);y(r,()=>t.handle(r.payload.baseGeneration,r.payload.request),()=>t.status())})}else{let t=new u({openDb:()=>l(i.projectRoot)});p.on("message",e=>{let r=m(e),o=a();s(r.payload.profileEnvironment??{});try{y(r,()=>t.handle(r.payload.generation,r.payload.request),()=>t.status())}finally{s(o)}})}function y(t,e,r){let o;try{if(Date.now()>t.deadlineAtMs)throw new Error("TypeScript mailbox request expired before processing.");let n=e();if(Date.now()>t.deadlineAtMs)throw new Error("TypeScript mailbox request expired while the worker was processing it.");o={kind:"response",requestId:t.requestId,ok:!0,result:n,status:r()}}catch(n){o={kind:"response",requestId:t.requestId,ok:!1,error:n instanceof Error?n.message:String(n),status:r()}}p.postMessage(o)}function k(t){if(!t||typeof t!="object")throw new Error("TypeScript mailbox worker data is missing.");let e=t;if(e.kind==="index"&&typeof e.projectRoot=="string"&&typeof e.dbPath=="string")return{kind:"index",projectRoot:e.projectRoot,dbPath:e.dbPath};if(e.kind==="semantic"&&typeof e.projectRoot=="string")return{kind:"semantic",projectRoot:e.projectRoot};throw new Error("TypeScript mailbox worker data is invalid.")}function m(t){if(!t||typeof t!="object")throw new Error("TypeScript mailbox worker request is missing.");let e=t;if(e.kind!=="request"||typeof e.requestId!="string"||!Number.isSafeInteger(e.deadlineAtMs)||typeof e.payload!="object"||e.payload===null)throw new Error("TypeScript mailbox worker request is invalid.");return e}
1
+ import{a as c,c as u}from"./chunk-QVWDQTMG.js";import"./chunk-3AC56WAR.js";import{f as d}from"./chunk-IBM3F2BJ.js";import"./chunk-M7LAIM77.js";import"./chunk-FWY2PRIF.js";import"./chunk-DRENNWRG.js";import{ma as l}from"./chunk-WJOQC4P7.js";import"./chunk-IYBIBMPF.js";import"./chunk-XYLV727H.js";import"./chunk-4NHWNAWQ.js";import"./chunk-2VKB5CMA.js";import"./chunk-ACZDU5GK.js";import{g as a,h as s}from"./chunk-R2NOK63J.js";import"./chunk-6URCE5QY.js";import"./chunk-4O52YNKL.js";import{parentPort as p,workerData as S}from"worker_threads";var i=k(S);if(!p)throw new Error("TypeScript mailbox worker requires a parent port.");if(i.kind==="index"){let t=new c({projectRoot:i.projectRoot,currentGeneration:()=>d(i.dbPath)});p.on("message",e=>{let r=m(e);y(r,()=>t.handle(r.payload.baseGeneration,r.payload.request),()=>t.status())})}else{let t=new u({openDb:()=>l(i.projectRoot)});p.on("message",e=>{let r=m(e),o=a();s(r.payload.profileEnvironment??{});try{y(r,()=>t.handle(r.payload.generation,r.payload.request),()=>t.status())}finally{s(o)}})}function y(t,e,r){let o;try{if(Date.now()>t.deadlineAtMs)throw new Error("TypeScript mailbox request expired before processing.");let n=e();if(Date.now()>t.deadlineAtMs)throw new Error("TypeScript mailbox request expired while the worker was processing it.");o={kind:"response",requestId:t.requestId,ok:!0,result:n,status:r()}}catch(n){o={kind:"response",requestId:t.requestId,ok:!1,error:n instanceof Error?n.message:String(n),status:r()}}p.postMessage(o)}function k(t){if(!t||typeof t!="object")throw new Error("TypeScript mailbox worker data is missing.");let e=t;if(e.kind==="index"&&typeof e.projectRoot=="string"&&typeof e.dbPath=="string")return{kind:"index",projectRoot:e.projectRoot,dbPath:e.dbPath};if(e.kind==="semantic"&&typeof e.projectRoot=="string")return{kind:"semantic",projectRoot:e.projectRoot};throw new Error("TypeScript mailbox worker data is invalid.")}function m(t){if(!t||typeof t!="object")throw new Error("TypeScript mailbox worker request is missing.");let e=t;if(e.kind!=="request"||typeof e.requestId!="string"||!Number.isSafeInteger(e.deadlineAtMs)||typeof e.payload!="object"||e.payload===null)throw new Error("TypeScript mailbox worker request is invalid.");return e}
2
2
  //# sourceMappingURL=typescript-mailbox-worker.js.map
@@ -1,8 +1,8 @@
1
- import{A as Vt,B as Bt,C as Re,D as Ut,E as Gt,H as Pe,a as Rt,b as Pt,c as It,d as Mt,e as we,f as Tt,g as Ce,h as At,i as kt,j as Ot,k as ne,l as Lt,m as qt,p as Dt,q as _t,r as Wt,s as jt,t as Nt,u as j,w as x,x as $t,y as Ee,z as Ft}from"./chunk-HOA5YGOH.js";import{c as Yt,d as Xt,e as Jt,f as Kt,g as Zt,h as er}from"./chunk-LTA3BRZX.js";import{tb as Qt,vb as Ht,xb as zt}from"./chunk-GTIYTDRE.js";import{c as tr}from"./chunk-Q5ELPRKQ.js";import{a as be,b as ee}from"./chunk-ZZ3MWF33.js";import{f as ot,g as J}from"./chunk-PYAB5SM6.js";import{U as ut,X as Z}from"./chunk-NCZUNH3E.js";import"./chunk-YUKYB54I.js";import{a as lt}from"./chunk-AAQQPKCU.js";import"./chunk-NNO6A2PO.js";import"./chunk-P5XHIJHI.js";import"./chunk-KUW32IRO.js";import"./chunk-5VKBFZZU.js";import"./chunk-7MGU3HPH.js";import{b as mt,d as Et}from"./chunk-6BQ3DSPK.js";import"./chunk-FAJQ7LWY.js";import{E as bt,F as A,H as re,J as xt,K as B,M as wt,O as xe,P as Ct,h as pt,j as ht,o as V,p as ft,q as yt,r as gt,s as te,t as vt,u as W,v as St}from"./chunk-Z54RD7VL.js";import{c as K,d as ct,e as dt}from"./chunk-FDGD5AB5.js";import{c as nt}from"./chunk-RU65DDUP.js";import{d as Ye}from"./chunk-QW7EP6WI.js";import"./chunk-3IER7Q6H.js";import"./chunk-FM5BPL4V.js";import"./chunk-DRENNWRG.js";import{A as it,B as st,C as ge,D as ve,E as Se,F as at,j as rt}from"./chunk-RDBI2RXU.js";import{a as Xe,b as Je,c as Ke,d as Ze,e as et}from"./chunk-R2NOK63J.js";import{c as q,d as D}from"./chunk-EF2R3WNQ.js";import{G as b,N as tt,S as _,X as ye,b as Ge,h as X,m as Qe,n as He,o as ze}from"./chunk-WE5RZHZ7.js";import"./chunk-2Q2LW5JW.js";import v from"process";import{rmSync as Mr}from"fs";import{resolve as kn}from"path";import{pathToFileURL as On}from"url";var oe=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(t,r={}){this.root=t,this.now=r.now??Date.now,this.randomId=r.randomId,this.retryDelayMs=Math.max(1,Math.floor(r.retryDelayMs??1e3)),this.currentStatus=Ce(t)}initializeAfterOwnershipAcquired(){let t=Tt(this.root),r=At(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:t,prunedHistory:r}}observeLegacyRequest(t,r){Pt(this.root,r??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${t}`,now:()=>new Date(t)}),this.refreshStatus()}poll(t,r){if(this.active||t.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let o=It(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),o.requests.length===0)return!1;this.active=o;try{return r(Ar(o)),!0}catch(n){throw we(this.root,o),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),n}}completeActive(){return this.active?(Mt(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(we(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=Ce(this.root)}};function Ar(e){if(e.requests.length===1)return e.requests[0].detail;let r=[...new Set(e.requests.map(o=>o.detail))].slice(0,3).join("; ");return`${e.requests.length} coalesced refresh requests${r?`: ${r}`:""}`.slice(0,2048)}import{createHash as hn}from"crypto";import{readdirSync as fn,statSync as yn}from"fs";import{join as Oe}from"path";import{performance as Le}from"perf_hooks";var Ie;function Me(e){Ie=e}function rr(){return Ie||{argv:process.argv.slice(2),execPath:process.execPath,...process.argv[1]!==void 0?{scriptPath:process.argv[1]}:{},cwd:process.cwd()}}import{Command as an,Help as cn}from"commander";import{Option as Or}from"commander";function Te(e){return e.evidence?e.evidence:kr.has(e.id)?"mixed":e.heuristic?"heuristic":"graph-fact"}var kr=new Set(["health","context","co-change"]);function nr(e){if(e.claims){if(e.claims.origin==="mixed"&&!e.claims.families?.length)throw new Error(`Mixed command ${e.id} must declare at least one claim family.`);return e.claims}let t=Te(e);if(t==="mixed")throw new Error(`Mixed command ${e.id} must declare claim families.`);let r=e.agent?Xt(e.agent.operation):[];return r.length>0&&r.every(n=>n==="repository-observation"||n==="repository-preview")?{origin:t==="heuristic"?"heuristic":"compiler-graph",observedSources:["index-generation"],producerValidation:{status:"not-evaluated"}}:{origin:"unknown",observedSources:["process"],producerValidation:{status:"not-evaluated"}}}function or(e,t){return Kt(new Map(t.map(r=>[r.id,Te(r)]))),er(new Map(t.map(r=>[r.id,nr(r)]))),Zt(new Map(t.flatMap(r=>r.agent?[[r.id,{...r.agent,resultUnits:qr(r)}]]:[]))),t.map(r=>{let o=r.hidden?e.command(r.command,{hidden:!0}):e.command(r.command);o.description(r.description),r.helpAfter&&o.addHelpText("after",`
1
+ import{c as nr}from"./chunk-37TKC6MB.js";import{a as rr}from"./chunk-L3YSDLNB.js";import{a as It,b as j,d as w,e as Vt,f as Ce,g as Bt,h as Ft,i as Ut,j as Re,k as Qt,l as Gt,o as Ee}from"./chunk-36WRYYTE.js";import{c as Xt,d as Jt,e as Kt,f as Zt,g as er,h as tr}from"./chunk-NJA4MMBD.js";import{j as Ht,l as zt,n as Yt}from"./chunk-CDWSLAPN.js";import{a as Tt,b as Mt,c as At,d as we,e as Ot,f as xe,g as Lt,i as Wt,j as Dt,k as qt,o as _t,q as Nt,r as jt,s as $t}from"./chunk-TAJ6UGCO.js";import"./chunk-BLKYYQ7C.js";import{f as it,g as J}from"./chunk-HBXZAGY6.js";import{a as ye,b as F}from"./chunk-ZZ3MWF33.js";import{U as lt,X as ut}from"./chunk-IGQQUENU.js";import"./chunk-YUKYB54I.js";import{a as mt}from"./chunk-AAQQPKCU.js";import"./chunk-HCMQZPEO.js";import"./chunk-P5XHIJHI.js";import"./chunk-H5QXP63L.js";import"./chunk-2Q2LW5JW.js";import"./chunk-EXMVF3JR.js";import"./chunk-5IO2APSS.js";import{b as pt,d as Rt}from"./chunk-QVWDQTMG.js";import"./chunk-3AC56WAR.js";import{c as K,d as ct,e as dt}from"./chunk-IBM3F2BJ.js";import"./chunk-M7LAIM77.js";import"./chunk-FWY2PRIF.js";import"./chunk-DRENNWRG.js";import{c as Et,d as Pt,j as kt}from"./chunk-5XEVXVTK.js";import"./chunk-SV2LEFVM.js";import{B as ft,D as ht,P as ve,Q as gt,R as yt,T as Z,U as vt,V as N,W as St,da as bt,ea as A,ga as ee,ja as wt,ka as Se,ma as xt,oa as be,pa as Ct}from"./chunk-WJOQC4P7.js";import{c as nt}from"./chunk-IYBIBMPF.js";import{d as ze}from"./chunk-XYLV727H.js";import"./chunk-4NHWNAWQ.js";import"./chunk-2VKB5CMA.js";import{A as ot,B as st,C as fe,D as he,E as ge,F as at,j as tt}from"./chunk-ACZDU5GK.js";import{a as Ye,b as Xe,c as Je,d as Ke,e as Ze}from"./chunk-R2NOK63J.js";import{c as D,d as q}from"./chunk-6URCE5QY.js";import{G as R,N as et,Q as rt,T as _,Y as pe,b as Ue,h as X,m as Qe,n as Ge,o as He}from"./chunk-4O52YNKL.js";import v from"process";import{rmSync as qr}from"fs";import{resolve as $n}from"path";import{pathToFileURL as Vn}from"url";var te=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(t,r={}){this.root=t,this.now=r.now??Date.now,this.randomId=r.randomId,this.retryDelayMs=Math.max(1,Math.floor(r.retryDelayMs??1e3)),this.currentStatus=xe(t)}initializeAfterOwnershipAcquired(){let t=Ot(this.root),r=Lt(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:t,prunedHistory:r}}observeLegacyRequest(t,r){Tt(this.root,r??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${t}`,now:()=>new Date(t)}),this.refreshStatus()}poll(t,r){if(this.active||t.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let i=Mt(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),i.requests.length===0)return!1;this.active=i;try{return r(Nr(i)),!0}catch(n){throw we(this.root,i),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),n}}completeActive(){return this.active?(At(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(we(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=xe(this.root)}};function Nr(e){if(e.requests.length===1)return e.requests[0].detail;let r=[...new Set(e.requests.map(i=>i.detail))].slice(0,3).join("; ");return`${e.requests.length} coalesced refresh requests${r?`: ${r}`:""}`.slice(0,2048)}import{createHash as yn}from"crypto";import{readdirSync as vn,statSync as Sn}from"fs";import{join as Me}from"path";import{performance as Ae}from"perf_hooks";var Pe;function ke(e){Pe=e}function ir(){return Pe||{argv:process.argv.slice(2),execPath:process.execPath,...process.argv[1]!==void 0?{scriptPath:process.argv[1]}:{},cwd:process.cwd()}}import{Command as ln,Help as un}from"commander";import{Option as $r}from"commander";function Ie(e){return e.evidence?e.evidence:jr.has(e.id)?"mixed":e.heuristic?"heuristic":"graph-fact"}var jr=new Set(["health","context","co-change"]);function or(e){if(e.claims){if(e.claims.origin==="mixed"&&!e.claims.families?.length)throw new Error(`Mixed command ${e.id} must declare at least one claim family.`);return e.claims}let t=Ie(e);if(t==="mixed")throw new Error(`Mixed command ${e.id} must declare claim families.`);let r=e.agent?Jt(e.agent.operation):[];return r.length>0&&r.every(n=>n==="repository-observation"||n==="repository-preview")?{origin:t==="heuristic"?"heuristic":"compiler-graph",observedSources:["index-generation"],producerValidation:{status:"not-evaluated"}}:{origin:"unknown",observedSources:["process"],producerValidation:{status:"not-evaluated"}}}function sr(e,t){return Zt(new Map(t.map(r=>[r.id,Ie(r)]))),tr(new Map(t.map(r=>[r.id,or(r)]))),er(new Map(t.flatMap(r=>r.agent?[[r.id,{...r.agent,resultUnits:Br(r)}]]:[]))),t.map(r=>{let i=r.hidden?e.command(r.command,{hidden:!0}):e.command(r.command);i.description(r.description),r.helpAfter&&i.addHelpText("after",`
2
2
  ${r.helpAfter.trim()}
3
- `);for(let n of r.arguments??[])o.argument(n.name);for(let n of r.options??[])if(n.hidden){let i=new Or(n.flags,n.description).hideHelp();n.parser&&i.argParser(n.parser),Object.hasOwn(n,"defaultValue")&&i.default(n.defaultValue),o.addOption(i)}else n.parser&&Object.hasOwn(n,"defaultValue")?o.option(n.flags,n.description,n.parser,n.defaultValue):n.parser?o.option(n.flags,n.description,n.parser):Object.hasOwn(n,"defaultValue")?o.option(n.flags,n.description,n.defaultValue):o.option(n.flags,n.description);return o.action(async(...n)=>{try{let i=o.optsWithGlobals();Lr(i);let s=rr(),d=()=>r.id===Qt?r.handler(...n):Ht({command:r.id,producerVersion:b,invocationPrefix:s.scriptPath?[s.execPath,s.scriptPath]:["codebaseiq"],argv:[...s.argv],cwd:s.cwd,json:i.json===!0,sourceSession:i.session!==!1,reemitSource:i.reemit===!0,...typeof i.outputPageSize=="number"?{pageSize:i.outputPageSize}:{},...typeof i.outputCursor=="string"?{cursor:i.outputCursor}:{}},()=>r.handler(...n)),h=r.agent?Yt(r.agent.operation,{args:n.slice(0,-1),options:i}):void 0;await(h?Jt(h,d):d())}catch(i){Dr(i)}finally{A(void 0),yt()}}),{descriptor:r,command:o}})}function Lr(e){if(e.resultOnly===!0&&e.json!==!0)throw new Error("--result-only requires --json.");if(e.compact===!0&&e.json!==!0)throw new Error("--compact requires --json.")}function qr(e){let t=e.agent?.resultUnits;if(t?.kind==="field"&&t.field.trim()==="")throw new Error(`Command ${e.id} declares an empty result-unit field.`);return t||(e.renderShape==="list"||e.renderShape==="table"||e.renderShape==="grouped-by-file"?{kind:"rows"}:{kind:"report"})}function Dr(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${ee(t)}`),process.exitCode=1}var _r=new Set(Pe),ir=new Map(Pe.map((e,t)=>[e,t])),Wr=new Set(["Navigation","Graph","Impact","Exploration"]),jr=new Set(["Cleanup","Health"]),Nr=new Set(["Indexing","Core","Maintenance"]);function $r(e){if(e.hidden||e.agent?.semantic?.compatibility==="deprecated")return"compatibility";if(_r.has(e.id))return"primary-exploration";let t=e.docs?.category;if(t&&Wr.has(t))return"specialized-analysis";if(t&&jr.has(t))return"quality-cleanup";if(t&&Nr.has(t))return"maintenance";if(t==="Formal Models")return"formal-modeling";throw new Error(`Visible command ${e.id} has no cockpit panel (docs category: ${t??"missing"}).`)}function Fr(e,t={}){return[{id:"primary-exploration",title:"Primary exploration",purpose:"Locate exact referents, project chosen relationships, and read only named implementation gaps."},{id:"specialized-analysis",title:"Specialized analysis",purpose:"Run a named graph, impact, or structural analysis when that exact analysis answers the task."},{id:"quality-cleanup",title:"Quality and cleanup",purpose:"Evaluate repository quality, cleanup candidates, and configured architecture findings."},{id:"maintenance",title:"Maintenance",purpose:"Build, inspect, configure, and maintain the project index and local integrations."},{id:"formal-modeling",title:"Formal modeling",purpose:"Create, verify, and check explicit state-machine models and traces."},{id:"compatibility",title:"Compatibility and deprecated controls",purpose:"Preserved invocation surfaces for existing consumers; do not choose these for new workflows."}].map(n=>({...n,commands:e.filter(i=>$r(i)===n.id).sort((i,s)=>n.id==="primary-exploration"?(ir.get(i.id)??Number.MAX_SAFE_INTEGER)-(ir.get(s.id)??Number.MAX_SAFE_INTEGER):0)})).filter(n=>n.commands.length>0&&(t.includeCompatibility||n.id!=="compatibility"))}function sr(e,t,r={}){let o=[`Usage: ${e.name()} [options] [command]`,"",e.description(),"","Options:"],n=e.options.map(s=>s.flags),i=Math.max(...n.map(s=>s.length),0);for(let s of e.options)o.push(` ${s.flags.padEnd(i)} ${s.description}`);o.push(` ${"-h, --help".padEnd(i)} Display this grouped command help`);for(let s of Fr(t,r)){o.push("",`${s.title}:`,` ${s.purpose}`);let d=Math.max(...s.commands.map(h=>h.command.length),0);for(let h of s.commands)o.push(` ${h.command.padEnd(d)} ${h.description}`)}return r.includeCompatibility||o.push("","Run `codebaseiq --help-all` to include compatibility and deprecated controls."),o.push("Run `codebaseiq <command> --help` for one control's options and examples.",""),o.join(`
4
- `)}import{existsSync as Vr,mkdirSync as Br,writeFileSync as Ur}from"fs";import{homedir as Gr}from"os";import{join as ie}from"path";var Qr=1440*60*1e3,cr="update-check.json",Hr="https://registry.npmjs.org/codebaseiq/latest";async function Ae(e={}){let t=e.env??process.env;if(t.CODEBASEIQ_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let r=e.cacheDir??Xr(t),o=e.now??Date.now(),n=e.currentVersion??b,i=Jr(r),s=i&&o-i.checkedAt<Qr?i.latestVersion:await Kr(r,e.fetchLatestVersion??en,o);if(!s||!Yr(s,n))return;(e.writeNotice??(h=>console.error(h)))(zr(n,s))}function zr(e,t){return[`codebaseiq update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g codebaseiq@latest",""].join(`
5
- `)}function Yr(e,t){let r=ar(e),o=ar(t);if(!r||!o)return e!==t;for(let n=0;n<r.length;n++){let i=r[n]-o[n];if(i>0)return!0;if(i<0)return!1}return!1}function Xr(e){let t=e.XDG_CACHE_HOME||ie(Gr(),".cache");return ie(t,"codebaseiq")}function Jr(e){let t=ie(e,cr);if(!Vr(t))return null;try{let r=JSON.parse(X(t,"update notice cache"));return typeof r.checkedAt=="number"&&(typeof r.latestVersion=="string"||r.latestVersion===null)?{checkedAt:r.checkedAt,latestVersion:r.latestVersion}:null}catch{return null}}async function Kr(e,t,r){let o;try{o=await t()}catch{o=null}return Zr(e,{checkedAt:r,latestVersion:o}),o}function Zr(e,t){try{Br(e,{recursive:!0}),Ur(ie(e,cr),`${JSON.stringify(t,null,2)}
6
- `)}catch{}}async function en(){let e=await fetch(Hr,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function ar(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}var tn=5e3,rn=100,nn={prepare:xt,freshness:V,ensureService:ne,inspectService:qt,requestRefresh:_t,async reindex(e,t,r,o){let{reindexConfiguredProject:n}=await import("./project-reindex-5JOKXAXT.js");return n(e,t,r,o)},wait(e){return new Promise(t=>setTimeout(t,e))},now:Date.now};async function dr(e,t=nn,r={}){if(e.dbPathSource==="env")return{source:"explicit-index",service:{kind:"skipped",reason:"environment"}};let o=on(e,t),n=t.prepare(e.projectRoot,e.config,e.paths,{gitContext:e.gitContext,...o?{watcherGeneration:o}:{}}),i=t.freshness(e.projectRoot,e.config,e.paths),s=t.ensureService({commandName:e.commandName,projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:b,config:e.config,gitContext:e.gitContext});if(i.state==="fresh")return{source:n.kind==="local-fresh"?"existing":"shared-generation",service:s};if((s.kind==="started"||s.kind==="reused")&&(t.requestRefresh(Z(e.paths.cacheDir).activityPath,`evidence command ${e.commandName} requires a fresh generation`),i=await sn(e,i,t,r,s),i.state==="fresh"))return{source:"watcher",service:s};try{await t.reindex(e.projectRoot,e.config,e.paths,{allowPartial:!1,skipAutoInstall:!0,trigger:{kind:"watch-demand",detail:`codebaseiq ${e.commandName}`},onStatus:()=>{}})}catch(d){throw new Error(`Could not prepare fresh evidence for codebaseiq ${e.commandName}: ${d instanceof Error?d.message:String(d)}`,{cause:d})}if(i=t.freshness(e.projectRoot,e.config,e.paths),i.state!=="fresh")throw new Error(`Could not prepare fresh evidence for codebaseiq ${e.commandName}: index remained ${i.state} (${i.reason})`);return{source:"synchronous-reindex",service:s}}function on(e,t){if(e.config.watch?.enabled===!0)try{return kt(t.inspectService({projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:b,gitContext:e.gitContext}))}catch{return}}async function sn(e,t,r,o,n){if(n.state.watcher.state==="budget-paused")return t;let i=Math.max(0,o.waitMs??tn),s=Math.max(1,o.pollMs??rn),d=r.now()+i,h=t;for(;r.now()<d;)if(await r.wait(Math.min(s,Math.max(1,d-r.now()))),gt(),h=r.freshness(e.projectRoot,e.config,e.paths),h.state==="fresh")return h;return h}async function lr(e={}){let t=new an;e.resident&&t.exitOverride(),e.terminalOutput&&t.configureOutput({writeOut:n=>process.stdout.write(be(n)),writeErr:n=>process.stderr.write(be(n))}),t.name("codebaseiq").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(b).option("--output-page-size <characters>","Return bounded output pages with an exact continuation command",zt).option("--output-cursor <cursor>","Continue a bounded output page").option("--no-session","Disable the explicit exploration evidence ledger").option("--reemit","Recovery only: render source and graph evidence again instead of citing session receipts").option("--help-all","Display every command, including compatibility and deprecated controls");let r=await tr(e.invocationCommand);or(t,r);let o=new cn;return t.configureHelp({formatHelp:(n,i)=>n===t?sr(t,r):o.formatHelp(n,i)}),t.hook("preAction",async(n,i)=>{let s=i.name();if(e.resident){await e.resident.preAction(s);return}let d=B(s),h=Ot(s);if(!d&&!h){ur(),await Ae({commandName:s});return}let u=bt(),c=_(u);ft(c);let l=re(u,c);A(l),ur(),await Ae({commandName:s});let{config:p,paths:a}=l;if(d){let f=await dr({commandName:s,projectRoot:u,config:p,paths:a,dbPathSource:l.dbPathSource,gitContext:c});process.env.CODEBASEIQ_DEBUG&&console.error(`evidence-freshness: ${f.source}`),f.service.kind==="failed"&&console.error(`warning: codebaseiq watch service did not start: ${f.service.message}`),(f.service.kind==="failed"||f.service.kind==="skipped")&&j(u,b);return}if(!h){j(u,b);return}let g=ne({commandName:s,projectRoot:u,cacheDir:a.cacheDir,cliVersion:b,config:p,gitContext:c});g.kind==="failed"&&console.error(`warning: codebaseiq watch service did not start: ${g.message}`),(g.kind==="failed"||g.kind==="skipped")&&j(u,b)}),t.hook("postAction",()=>A(void 0)),{program:t,descriptors:r}}function ur(){if(Ke(),!Xe()||Ze())return;let e=null;try{e=Ct(t=>nt(t))}catch{}et({command:Je()??`codebaseiq ${process.argv.slice(2).join(" ")}`,toolVersion:b,projectFingerprint:e})}import{execFileSync as mr}from"child_process";import{lstatSync as dn}from"fs";import{join as un}from"path";var ke=3e4,pr={encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:ke,killSignal:"SIGKILL"};function hr(e){return{generation:e.generation,epoch:e.epoch,changeSequence:e.changeSequence,headCommit:e.headCommit,treeOid:e.treeOid,fingerprintByPath:new Map(e.snapshot.files.map(t=>[t.path,t.hash])),languages:[...e.snapshot.languages],markerFiles:[...e.config.indexer?.typescript?.projects??[],...e.config.indexer?.clojure?.configPath?[e.config.indexer.clojure.configPath]:[]]}}function fr(e,t,r){if(r.epoch!==t.epoch)return{continuous:!1,reason:"the watcher observation epoch advanced since this generation was published"};if(r.changeSequence!==t.changeSequence)return{continuous:!1,reason:"the watcher observed a change after this generation was published"};let o,n;try{o=ln(e),n=mn(e)}catch(i){return{continuous:!1,reason:`git state could not be read: ${i instanceof Error?i.message:String(i)}`}}if(o.headCommit!==t.headCommit||o.treeOid!==t.treeOid)return{continuous:!1,reason:"the git HEAD tree moved since this generation was published"};for(let i of n){if(He(i,t.languages,t.markerFiles)==="other")continue;let s=t.fingerprintByPath.get(i),d=pn(un(e,i));if(d===null)return{continuous:!1,reason:`indexed input ${i} is no longer readable as a plain file`};if(s!==d)return{continuous:!1,reason:s===void 0?`indexed input ${i} appeared after this generation was published`:`indexed input ${i} changed after this generation was published`}}return{continuous:!0}}function ln(e){let t=mr("git",["-C",e,"rev-parse","HEAD","HEAD^{tree}"],{...pr,timeout:ke}).split(`
7
- `).map(n=>n.trim()).filter(Boolean),[r,o]=t;if(!/^[0-9a-f]{40,64}$/.test(r??"")||!/^[0-9a-f]{40,64}$/.test(o??""))throw new Error("git did not report a resolved HEAD tree");return{headCommit:r,treeOid:o}}function mn(e){return mr("git",["-C",e,"status","--porcelain=v1","-z","--untracked-files=all","--no-renames","--","."],{...pr,timeout:ke}).split("\0").filter(t=>t.length>=4&&t[2]===" ").map(t=>t.slice(3))}function pn(e){try{return dn(e).isFile()?Qe(e,{maxBytes:Ge,inputKind:"project-file"}):null}catch{return null}}var R=class extends Error{constructor(r,o){super(o);this.code=r}code};function Sr(e){let t=!1,r,o=()=>{let u=r;if(r=void 0,!!u)try{u.db.close()}catch{}},n=()=>{let u=e.indexGeneration();if(!u)throw new R("stale-index","The resident index is not idle-fresh; run the command in-process.");return u},i=u=>{let c=e.observation();if(!c||c.published.generation!==u)throw new R("stale-index","No provable observation is bound to the published generation; run the command in-process.");let l=fr(e.projectRoot,c.published,{epoch:c.epoch,changeSequence:c.changeSequence});if(!l.continuous)throw new R("stale-index",`${l.reason}; run the command in-process.`)},s=()=>{let u=n(),c=Sn(e.projectRoot);if(r&&(r.generation!==u||r.stamp!==c||W(e.dbPath)!==u)&&o(),!r){let l=wt(e.projectRoot);if(W(e.dbPath)!==u){try{l.close()}catch{}throw new R("stale-index","The published generation moved while opening the resident database.")}r={generation:u,stamp:c,db:l}}return r.db},d=u=>{if(!B(u))throw new R("ineligible-command",`Command ${u} always executes in-process.`);n();let c=re(e.projectRoot,_(e.projectRoot));if(c.dbPathSource!=="configured")throw new R("stale-index","The resident host does not serve fallback index locations.");A(c)};return{execute:async u=>{if(t)return U("busy","The resident host is executing another request; run the command in-process.");let c=u.argv[0];if(!c||c.startsWith("-")||!B(c))return U("ineligible-command","Only evidence commands are served by the resident host.");let l;try{l=n(),i(l)}catch(y){return yr(y)}t=!0;let p=Le.now(),a=new qe(u.tty),g=vn(u.envAllowlist),f=process.exitCode;process.exitCode=0,Me({argv:u.argv,execPath:u.clientInvocation?.execPath??process.execPath,...u.clientInvocation?.scriptPath!==void 0?{scriptPath:u.clientInvocation.scriptPath}:{},cwd:u.cwd}),xe(s);try{let{program:y}=await lr({invocationCommand:c,resident:{preAction:d}});a.install();try{await y.parseAsync([...u.argv],{from:"user"})}finally{a.restore()}let S=typeof process.exitCode=="number"?process.exitCode:0;return{ok:!0,kind:"executed",protocolVersion:x,serverPid:process.pid,exitCode:S,stdout:a.stdout(),stderr:a.stderr(),generation:l,durationMs:Le.now()-p}}catch(y){return y instanceof R?yr(y):gn(y)?{ok:!0,kind:"executed",protocolVersion:x,serverPid:process.pid,exitCode:y.exitCode,stdout:a.stdout(),stderr:a.stderr(),generation:l,durationMs:Le.now()-p}:U("execution-error",`Resident execution failed: ${y instanceof Error?y.message:String(y)}`)}finally{xe(void 0),Me(void 0),A(void 0),process.exitCode=f,g(),t=!1}},releaseDatabase:o}}function U(e,t){return{ok:!1,protocolVersion:x,code:e,message:t}}function yr(e){return e instanceof R?U(e.code,e.message):U("execution-error",e instanceof Error?e.message:String(e))}function gn(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&(e.code.startsWith("commander.")||e.code==="commander")&&typeof e.exitCode=="number"}function vn(e){let t=new Map;for(let r of Vt){t.set(r,process.env[r]);let o=e?.[r];o===void 0?delete process.env[r]:process.env[r]=o}return()=>{for(let[r,o]of t)o===void 0?delete process.env[r]:process.env[r]=o}}var qe=class{constructor(t){this.tty=t}tty;stdoutChunks=[];stderrChunks=[];restorers=[];install(){this.restorers=[gr(process.stdout,this.stdoutChunks),gr(process.stderr,this.stderrChunks),se(process.stdout,"isTTY",this.tty?.isTTY??!1),se(process.stderr,"isTTY",this.tty?.isTTY??!1),se(process.stdout,"columns",this.tty?.columns),se(process.stderr,"columns",this.tty?.columns)]}restore(){for(let t of this.restorers.reverse())t();this.restorers=[]}stdout(){return this.stdoutChunks.join("")}stderr(){return this.stderrChunks.join("")}};function gr(e,t){let r=e.write,o=(n,i,s)=>{t.push(typeof n=="string"?n:Buffer.isBuffer(n)?n.toString(typeof i=="string"?i:"utf8"):String(n));let d=typeof s=="function"?s:typeof i=="function"?i:void 0;return typeof d=="function"&&d(),!0};return e.write=o,()=>{e.write=r}}function se(e,t,r){let o=Object.hasOwn(e,t),n=o?Object.getOwnPropertyDescriptor(e,t):void 0;return r===void 0?o&&Reflect.deleteProperty(e,t):Object.defineProperty(e,t,{value:r,configurable:!0,writable:!0}),()=>{n?Object.defineProperty(e,t,n):Reflect.deleteProperty(e,t)}}function Sn(e){let t=hn("sha256");for(let o of[".codebaseiq.json",".codebaseiq-baseline.json"])t.update(o),t.update(vr(Oe(e,o)));let r=Oe(e,".codebaseiq","suppressions");t.update(r);try{for(let o of fn(r).sort())t.update(o),t.update(vr(Oe(r,o)))}catch{t.update("absent")}return t.digest("hex")}function vr(e){try{let t=yn(e);return`${t.size}:${t.mtimeMs}`}catch{return"absent"}}import{chmodSync as bn,mkdirSync as xn,rmSync as br}from"fs";import{createServer as wn}from"net";import{dirname as Cn}from"path";var xr=1e4,En=5e3,Rn=6e5;function wr(e){let t=ye(e.projectRoot),r=0,o,n,i=new Set,s=wn(c=>{i.add(c),c.setTimeout(xr,()=>c.destroy()),c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c));let l=Ut($t,p=>{r+=1,o=new Date().toISOString(),e.onActivity?.(),d(p,c).then(a=>u(c,a)).catch(a=>{n=a instanceof Error?a.message:String(a),c.destroy()})},p=>{n=p.message,u(c,{ok:!1,protocolVersion:x,code:"invalid-request",message:p.message})});c.on("data",p=>{try{l.push(p)}catch(a){n=a instanceof Error?a.message:String(a),c.destroy()}})}),d=async(c,l)=>{let p=Gt(c);return p?ye(p.projectRoot)!==t?{ok:!1,protocolVersion:x,code:"wrong-project",message:"This query lane serves a different project root."}:h(p,l):{ok:!1,protocolVersion:x,code:"invalid-request",message:"The query lane received a request it could not validate."}},h=async(c,l)=>{if(c.kind==="ping"){let a=e.indexGeneration();return{ok:!0,kind:"pong",protocolVersion:x,serverPid:process.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{},cliVersion:e.cliVersion,projectRoot:t,...a?{indexGeneration:a}:{}}}if(!e.execute)return{ok:!1,protocolVersion:x,code:"unsupported",message:"Resident execution is not enabled on this service; run the command in-process."};let p=Math.max(c.deadlineMs??Ft,xr);l.setTimeout(Math.min(p+En,Rn));try{l.write(Re({ok:!0,kind:"accepted",protocolVersion:x,serverPid:process.pid},Ee))}catch(a){return n=a instanceof Error?a.message:String(a),l.destroy(),{ok:!1,protocolVersion:x,code:"execution-error",message:"The query lane could not acknowledge the request."}}try{return await e.execute(c)}catch(a){return n=a instanceof Error?a.message:String(a),{ok:!1,protocolVersion:x,code:"execution-error",message:`Resident execution failed: ${n}`}}},u=(c,l)=>{try{c.end(Re(l,Ee))}catch(p){n=p instanceof Error?p.message:String(p),c.destroy()}};return process.platform!=="win32"&&(xn(Cn(e.socketPath),{recursive:!0,mode:448}),br(e.socketPath,{force:!0})),new Promise((c,l)=>{s.once("error",l),s.listen(e.socketPath,()=>{if(s.removeListener("error",l),s.on("error",p=>{n=p.message}),process.platform!=="win32")try{bn(e.socketPath,384)}catch{}c({status:()=>({protocolVersion:x,socketPath:e.socketPath,requests:r,...o!==void 0?{lastRequestAt:o}:{},...n!==void 0?{lastError:n}:{}}),close:()=>new Promise(p=>{for(let a of i)a.destroy();s.close(()=>{process.platform!=="win32"&&br(e.socketPath,{force:!0}),p()})})})})})}import{randomUUID as In}from"crypto";import{Worker as Mn}from"worker_threads";var ae=class{constructor(t){this.options=t;this.now=t.now??Date.now,this.setTimer=t.setTimer??setTimeout,this.clearTimer=t.clearTimer??clearTimeout}options;now;setTimer;clearTimer;worker=null;active=null;activeFailure=null;terminating=null;closed=!1;workerGeneration=0;canAccept(){return!this.closed&&this.active===null&&this.terminating===null}start(t){if(!this.canAccept())return!1;if(t.deadlineAtMs<this.now()){try{this.options.onReject(t,`${this.options.name} request expired before processing.`)}catch(i){this.closed=!0,this.options.onFatal(De(i))}return!0}let r=this.ensureWorker(),o=Math.max(1,Math.min(2147483647,t.deadlineAtMs-this.now())),n=this.setTimer(()=>{this.failActiveAfterTermination(`${this.options.name} request exceeded its deadline.`)},o);this.active={request:t,timer:n};try{r.postMessage({kind:"request",...t})}catch(i){this.failActiveAfterTermination(Cr(i))}return!0}async close(t=`${this.options.name} service is shutting down.`){if(this.closed=!0,this.active){await this.failActiveAfterTermination(t);return}await this.terminateWorker()}ensureWorker(){if(this.worker)return this.worker;let t=this.options.createWorker(),r=++this.workerGeneration;return t.on("message",o=>this.handleMessage(r,o)),t.on("error",o=>{r===this.workerGeneration&&this.failActiveAfterTermination(`${this.options.name} worker failed: ${o.message}`)}),t.on("exit",o=>{r!==this.workerGeneration||this.terminating||(this.worker=null,this.active&&this.failActiveAfterTermination(`${this.options.name} worker exited unexpectedly with code ${o}.`))}),this.worker=t,t}handleMessage(t,r){if(t!==this.workerGeneration||this.closed||!this.active)return;let o=Pn(r);if(!o){this.failActiveAfterTermination(`${this.options.name} worker returned an invalid response.`);return}if(o.requestId!==this.active.request.requestId){this.failActiveAfterTermination(`${this.options.name} worker returned a mismatched request identity.`);return}if(this.now()>this.active.request.deadlineAtMs){this.failActiveAfterTermination(`${this.options.name} request expired while it was processing.`);return}let n=this.active;try{this.options.onStatus(o.status),o.ok?this.options.onComplete(n.request,o.result,o.status):this.options.onReject(n.request,o.error,o.status)}catch(i){this.closed=!0,this.clearTimer(n.timer),this.options.onFatal(De(i));return}this.releaseActive(n)}async failActiveAfterTermination(t){if(this.activeFailure){await this.activeFailure;return}let r=this.active;if(!r){await this.terminateWorker();return}this.clearTimer(r.timer);let o=(async()=>{if(await this.terminateWorker()){try{this.options.onReject(r.request,t)}catch(i){this.closed=!0,this.options.onFatal(De(i));return}this.releaseActive(r)}})();this.activeFailure=o;try{await o}finally{this.activeFailure===o&&(this.activeFailure=null)}}releaseActive(t){this.active===t&&(this.active=null,this.clearTimer(t.timer))}async terminateWorker(){if(this.terminating)return this.terminating;let t=this.worker;if(!t)return!0;this.worker=null;let r=++this.workerGeneration;return this.terminating=(async()=>{try{return await t.terminate(),!0}catch(o){return this.closed=!0,this.options.onFatal(new Error(`${this.options.name} worker termination failed: ${Cr(o)}`,{cause:o})),!1}finally{r===this.workerGeneration&&(this.terminating=null)}})(),this.terminating}};function Pn(e){if(!e||typeof e!="object")return null;let t=e;if(t.kind!=="response"||typeof t.requestId!="string"||!("status"in t))return null;if(t.ok===!0){if(!("result"in t)||"error"in t)return null}else if(t.ok===!1){if("result"in t||typeof t.error!="string")return null}else return null;return t}function De(e){return e instanceof Error?e:new Error(String(e))}function Cr(e){return e instanceof Error?e.message:String(e)}function Er(e){let t=()=>({protocolVersion:K,state:"idle",requests:0,sessionsCreated:0,sessionsReplaced:0,initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0});return Pr({name:"TypeScript index",paths:e.paths,now:e.now,limits:e.limits,initialStatus:t,parseEnvelope:dt,createWorker:()=>Ir(e,{kind:"index",projectRoot:e.projectRoot,dbPath:e.dbPath}),complete(r,o,n,i){ge(e.paths,r,{ok:!0,protocolVersion:K,id:o.id,baseGeneration:o.baseGeneration,response:n},{nowMs:i,limits:e.limits})},reject(r,o,n,i){ve(e.paths,r,{ok:!1,protocolVersion:K,id:o,error:n},n,{nowMs:i,limits:e.limits})},onBusy:e.onBusy,onFatal:e.onFatal})}function Rr(e){let t=()=>({protocolVersion:te,state:"idle",requests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0});return Pr({name:"TypeScript semantic",paths:e.paths,now:e.now,limits:e.limits,initialStatus:t,parseEnvelope:St,createWorker:()=>Ir(e,{kind:"semantic",projectRoot:e.projectRoot}),complete(r,o,n,i){ge(e.paths,r,{ok:!0,protocolVersion:te,id:o.id,generation:o.generation,response:n},{nowMs:i,limits:e.limits})},reject(r,o,n,i){ve(e.paths,r,{ok:!1,protocolVersion:te,id:o,error:n},n,{nowMs:i,limits:e.limits})},onBusy:e.onBusy,onFatal:e.onFatal})}function Pr(e){let t=e.now??Date.now,r=q(process.pid),o={pid:process.pid,...r?{processIdentity:r}:{}},n=`${e.name.toLowerCase().replaceAll(" ","-")}-${process.pid}-${In()}`,i={...e.limits,maxBatch:1},s=null,d=e.initialStatus(),h=!1,u=a=>{h=!0,e.onFatal(a)},c=new ae({name:e.name,createWorker:e.createWorker,now:t,onComplete(a,g,f){let y=l(a.requestId);d=f,e.complete(y.claim,y.envelope,g,t()),p(y)},onReject(a,g,f){let y=l(a.requestId);f!==void 0&&(d=f),e.reject(y.claim,y.envelope.id,g,t()),p(y)},onStatus(a){d=a},onFatal:u});return{poll(){if(h||!c.canAccept())return 0;let a=it(e.paths,{ownerId:n,nowMs:t(),limits:i,owner:o,liveness:{isProcessAlive:rt,readProcessIdentity:q}})[0];if(!a)return 0;let g=a.requestId;try{let f=e.parseEnvelope(st(a,i));if(g=f.id,f.id!==a.requestId)throw new Error(`${e.name} request identity does not match its mailbox path.`);if(f.deadlineAtMs<t())throw new Error(`${e.name} request expired before processing.`);if(s={claim:a,envelope:f},e.onBusy?.(f.deadlineAtMs),!c.start({requestId:f.id,deadlineAtMs:f.deadlineAtMs,payload:f}))throw new Error(`${e.name} worker lane closed admission after claiming a request.`)}catch(f){let y=An(f);try{e.reject(a,g,y,t()),s?.claim===a&&p(s)}catch(S){u(Tn(S))}}return 1},status(){return{...d,mailbox:at(e.paths)}},async close(a){await c.close(a)}};function l(a){let g=s;if(!g||g.envelope.id!==a)throw new Error(`${e.name} parent lost the active mailbox claim.`);return g}function p(a){s===a&&(s=null,e.onBusy?.(void 0))}}function Ir(e,t){if(e.createWorker)return e.createWorker(t);let r=e.workerUrl??new URL("./typescript-mailbox-worker.js",import.meta.url);return new Mn(r,{workerData:t})}function Tn(e){return e instanceof Error?e:new Error(String(e))}function An(e){return e instanceof Error?e.message:String(e)}var Ln=1e3,qn=250,Dn=6e4,_n=10,Wn=50,jn=250;function Nn(e,t=1){if(e>0)return _n;let r=Math.max(0,Math.min(3,t-1));return Math.min(jn,Wn*2**r)}async function $n(e,t){let r=t.processIndexRequests(),o=t.processSemanticRequests(),n=r+o,i=n>0?0:e+1;if(t.afterMailboxPoll({indexRequests:r,semanticRequests:o,processedRequests:n}),t.shouldStop())return{indexRequests:r,semanticRequests:o,processedRequests:n,consecutiveIdlePolls:i,stopped:!0};let s=Nn(n,i);return await t.wait(s),{indexRequests:r,semanticRequests:o,processedRequests:n,consecutiveIdlePolls:i,stopped:!1,delayMs:s}}function Fn(e){return e==="fresh"?null:{kind:"watch-startup",detail:`index ${e} when watch service started`}}async function Vn(e,t,r={}){let o=Lt(e,t),n=o.projectRoot;v.env.CODEBASEIQ_PROJECT_ROOT=n;let i=pt(n);i.watch={...i.watch,...r};let s=ht(i);if(!s.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let d=tt(n,i),h=Z(d.cacheDir),u=q(v.pid),c=jt(h.lockPath,n,{readProcessIdentity:m=>m===v.pid?u:q(m)});if(!c.acquired)return;let l=new oe(h.refreshRequestsPath,{retryDelayMs:Math.max(1e3,s.cooldownMs)});l.initializeAfterOwnershipAcquired();let p=Date.now(),a=D(),g=p,f=a,y={state:"idle"},S,G,P,Q,ce=J(d.dbPath),de=!1,_e=!1,We=0,je=Number.NEGATIVE_INFINITY,Ne=Number.NEGATIVE_INFINITY,$e=Number.NEGATIVE_INFINITY,Fe=Number.NEGATIVE_INFINITY,ue,le,Ve=0,me=vt(d.cacheDir),pe=ct(d.cacheDir);Et(me),mt(pe);let H,N,O,Be=m=>{if(O=void 0,!!m)try{let C=_(n);if(!C?.headCommit||!C.treeOid)return;let w=Ye(X(d.metaPath,"reindex metadata"));if(w.kind!=="legacy"&&w.kind!=="supported")return;let I=ze(w.metadata.fingerprint);if(!I)return;O=hr({generation:m,...L.observation(),headCommit:C.headCommit,treeOid:C.treeOid,snapshot:I,config:i})}catch{}},E=(m=!1,C=m?"durable":"visibility")=>{if(!_e)return;let w=Date.now(),I=D();!m&&I-je<Ln||(je=I,Dt(h.statePath,{version:1,protocolVersion:ut,pid:v.pid,...u?{processIdentity:u}:{},projectRoot:n,...o.worktreeId?{worktreeId:o.worktreeId}:{},cliVersion:t,startedAt:new Date(p).toISOString(),heartbeatAt:new Date(w).toISOString(),lastActivityAt:new Date(g).toISOString(),...s.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(g+s.idleTimeoutMs).toISOString()},watcher:y,...y.state==="idle"&&S?{indexGeneration:S}:{},...G?{lastRefresh:G}:{},...P?{lastError:P}:{},reindexActivity:ce,refreshRequests:l.status(),typescriptSemantic:{...he.status(),...ue===void 0?{}:{busyUntil:new Date(ue).toISOString()}},typescriptIndex:{...fe.status(),...le===void 0?{}:{busyUntil:new Date(le).toISOString()}},...H?{queryLane:H.status()}:{}},{durability:C}))},M=()=>{g=Date.now(),f=D()},Ue=m=>{M(),Q??=m,P={at:new Date().toISOString(),message:m.message},E(!0,"visibility")},he=Rr({paths:me,projectRoot:n,onBusy(m){ue=m===void 0?void 0:m+5e3,E(!0,"visibility")},onFatal:Ue}),fe=Er({paths:pe,projectRoot:n,dbPath:d.dbPath,onBusy(m){le=m===void 0?void 0:m+5e3,E(!0,"visibility")},onFatal:Ue}),L=new Rt({projectRoot:n,config:{...i,watch:s},outputDb:d.dbPath,languages:i.languages,onStatus(m){y=m,m.state!=="idle"&&(S=void 0,O=void 0,N?.releaseDatabase(),M()),E(!0)},onReindexComplete(){M();let m=V(n,i,d);return G=m.lastRefresh,S=m.state==="fresh"?W(d.dbPath)??void 0:void 0,Be(S),ce=J(d.dbPath),l.completeActive(),P=void 0,E(!0),m.state==="fresh"},onReindexError(){l.failActive()},onRefreshSuppressed(m){let C=ot(d.dbPath,m);C.state==="failed"&&(P={at:new Date().toISOString(),message:`Suppressed-refresh telemetry was not recorded: ${C.reason}`},E(!0,"visibility")),ce=J(d.dbPath)},onError(m){M(),S=void 0,O=void 0,P={at:new Date().toISOString(),message:m.message},E(!0)}}),z=()=>{de=!0};v.once("SIGINT",z),v.once("SIGTERM",z);let $=!1,Y,F;try{try{N=v.env.CODEBASEIQ_DAEMON==="1"||i.daemon?.enabled===!0?Sr({projectRoot:n,dbPath:d.dbPath,indexGeneration:()=>S,observation:()=>O?{published:O,...L.observation()}:void 0}):void 0,H=await wr({socketPath:Bt(d.cacheDir),projectRoot:n,cliVersion:t,...u?{processIdentity:u}:{},indexGeneration:()=>S,onActivity:M,...N?{execute:I=>N.execute(I)}:{}})}catch(w){P={at:new Date().toISOString(),message:`Query lane did not start: ${w instanceof Error?w.message:String(w)}`}}L.start();let m=V(n,i,d);G=m.lastRefresh,S=m.state==="fresh"?W(d.dbPath)??void 0:void 0,Be(S);let C=Fn(m.state);for(C&&L.requestRefresh(C,{immediate:!0}),M(),_e=!0,E(!0);!de;){let w=await $n(Ve,{processIndexRequests:()=>fe.poll(),processSemanticRequests:()=>he.poll(),afterMailboxPoll:({processedRequests:I})=>{let k=D();if(k-Fe>=Dn&&(Fe=k,Se(pe),Se(me)),k-$e>=6e4&&($e=k,j(n,t)),k-Ne>=qn){Ne=k;let T=Wt(h.activityPath);T&&T.atMs>g&&(g=T.atMs,f=k),T?.refreshRequestedAtMs!==void 0&&T.refreshRequestedAtMs>We&&(We=T.refreshRequestedAtMs,l.observeLegacyRequest(T.refreshRequestedAtMs,T.refreshDetail??"stale index observed by a legacy command")),l.poll(y,Tr=>{M(),L.requestRefresh({kind:"watch-demand",detail:Tr},{immediate:!0})})}I>0&&(M(),E(!0,"visibility")),E()},shouldStop:()=>de||Q!==void 0||Nt({watcher:y,lastActivityAtMs:f,nowMs:D(),idleTimeoutMs:s.idleTimeoutMs}),wait:Bn});if(Ve=w.consecutiveIdlePolls,w.stopped)break}}catch(m){$=!0,Y=m}finally{v.off("SIGINT",z),v.off("SIGTERM",z),await H?.close(),N?.releaseDatabase(),await Promise.all([he.close("TypeScript semantic service stopped before completing the request."),fe.close("TypeScript index service stopped before completing the request.")]);let m=await L.stop();m.state==="stopped"?(Mr(h.statePath,{force:!0}),Mr(h.activityPath,{force:!0}),c.release()):(P={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${m.reasons.join("; ")}`},E(!0),F=new Error(P.message))}if(!$&&Q&&($=!0,Y=Q),$&&F)throw new AggregateError([Y,F],"Watch service execution and shutdown both failed.");if($)throw Y;if(F)throw F}function Bn(e){return new Promise(t=>setTimeout(t,e))}function Un(e,t={report:r=>console.error(r),exit:r=>v.exit(r)}){return t.report(`watch-service: ${ee(e instanceof Error?e.message:String(e))}`),t.exit(1)}var Gn=v.argv[1]?On(kn(v.argv[1])).href:null;if(Gn===import.meta.url){lt();let e=v.argv[2],t=v.argv[3],r=Qn(v.argv[4]);if(!e||!t)console.error("watch-service: expected <project-root> <cli-version>"),v.exitCode=1;else try{await Vn(e,t,r)}catch(o){Un(o)}}function Qn(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}export{$n as runWatchServiceLoopIteration,Vn as runWatchServiceServer,Fn as startupRefreshTrigger,Un as terminateWatchServiceProcess,Nn as watchServiceLoopDelayMs};
3
+ `);for(let n of r.arguments??[])i.argument(n.name);for(let n of r.options??[])if(n.hidden){let o=new $r(n.flags,n.description).hideHelp();n.parser&&o.argParser(n.parser),Object.hasOwn(n,"defaultValue")&&o.default(n.defaultValue),i.addOption(o)}else n.parser&&Object.hasOwn(n,"defaultValue")?i.option(n.flags,n.description,n.parser,n.defaultValue):n.parser?i.option(n.flags,n.description,n.parser):Object.hasOwn(n,"defaultValue")?i.option(n.flags,n.description,n.defaultValue):i.option(n.flags,n.description);return i.action(async(...n)=>{try{let o=i.optsWithGlobals();Vr(o);let a=ir(),l=()=>r.id===Ht?r.handler(...n):zt({command:r.id,producerVersion:R,invocationPrefix:a.scriptPath?[a.execPath,a.scriptPath]:["codebaseiq"],argv:[...a.argv],cwd:a.cwd,json:o.json===!0,sourceSession:o.session!==!1,reemitSource:o.reemit===!0,...typeof o.outputPageSize=="number"?{pageSize:o.outputPageSize}:{},...typeof o.outputCursor=="string"?{cursor:o.outputCursor}:{}},()=>r.handler(...n)),y=r.agent?Xt(r.agent.operation,{args:n.slice(0,-1),options:o}):void 0;await(y?Kt(y,l):l())}catch(o){Fr(o)}finally{A(void 0),yt()}}),{descriptor:r,command:i}})}function Vr(e){if(e.resultOnly===!0&&e.json!==!0)throw new Error("--result-only requires --json.");if(e.compact===!0&&e.json!==!0)throw new Error("--compact requires --json.")}function Br(e){let t=e.agent?.resultUnits;if(t?.kind==="field"&&t.field.trim()==="")throw new Error(`Command ${e.id} declares an empty result-unit field.`);return t||(e.renderShape==="list"||e.renderShape==="table"||e.renderShape==="grouped-by-file"?{kind:"rows"}:{kind:"report"})}function Fr(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${F(t)}`),process.exitCode=1}var Ur=new Set(Ee),ar=new Map(Ee.map((e,t)=>[e,t])),Qr=new Set(["Navigation","Graph","Impact","Exploration"]),Gr=new Set(["Cleanup","Health"]),Hr=new Set(["Indexing","Core","Maintenance"]);function zr(e){if(e.hidden||e.agent?.semantic?.compatibility==="deprecated")return"compatibility";if(Ur.has(e.id))return"primary-exploration";let t=e.docs?.category;if(t&&Qr.has(t))return"specialized-analysis";if(t&&Gr.has(t))return"quality-cleanup";if(t&&Hr.has(t))return"maintenance";if(t==="Formal Models")return"formal-modeling";throw new Error(`Visible command ${e.id} has no cockpit panel (docs category: ${t??"missing"}).`)}function Yr(e,t={}){return[{id:"primary-exploration",title:"Primary exploration",purpose:"Locate exact referents, project chosen relationships, and read only named implementation gaps."},{id:"specialized-analysis",title:"Specialized analysis",purpose:"Run a named graph, impact, or structural analysis when that exact analysis answers the task."},{id:"quality-cleanup",title:"Quality and cleanup",purpose:"Evaluate repository quality, cleanup candidates, and configured architecture findings."},{id:"maintenance",title:"Maintenance",purpose:"Build, inspect, configure, and maintain the project index and local integrations."},{id:"formal-modeling",title:"Formal modeling",purpose:"Create, verify, and check explicit state-machine models and traces."},{id:"compatibility",title:"Compatibility and deprecated controls",purpose:"Preserved invocation surfaces for existing consumers; do not choose these for new workflows."}].map(n=>({...n,commands:e.filter(o=>zr(o)===n.id).sort((o,a)=>n.id==="primary-exploration"?(ar.get(o.id)??Number.MAX_SAFE_INTEGER)-(ar.get(a.id)??Number.MAX_SAFE_INTEGER):0)})).filter(n=>n.commands.length>0&&(t.includeCompatibility||n.id!=="compatibility"))}function cr(e,t,r={}){let i=[`Usage: ${e.name()} [options] [command]`,"",e.description(),"","Options:"],n=e.options.map(a=>a.flags),o=Math.max(...n.map(a=>a.length),0);for(let a of e.options)i.push(` ${a.flags.padEnd(o)} ${a.description}`);i.push(` ${"-h, --help".padEnd(o)} Display this grouped command help`);for(let a of Yr(t,r)){i.push("",`${a.title}:`,` ${a.purpose}`);let l=Math.max(...a.commands.map(y=>y.command.length),0);for(let y of a.commands)i.push(` ${y.command.padEnd(l)} ${y.description}`)}return r.includeCompatibility||i.push("","Run `codebaseiq --help-all` to include compatibility and deprecated controls."),i.push("Run `codebaseiq <command> --help` for one control's options and examples.",""),i.join(`
4
+ `)}import{existsSync as Xr,mkdirSync as Jr,writeFileSync as Kr}from"fs";import{homedir as Zr}from"os";import{join as re}from"path";var en=1440*60*1e3,lr="update-check.json",tn="https://registry.npmjs.org/codebaseiq/latest";async function ur(e={}){let t=e.env??process.env;if(t.CODEBASEIQ_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let r=e.cacheDir??on(t),i=e.now??Date.now(),n=e.currentVersion??R,o=sn(r),a=o&&i-o.checkedAt<en?o.latestVersion:await an(r,e.fetchLatestVersion??dn,i);if(!a||!nn(a,n))return;(e.writeNotice??(y=>console.error(y)))(rn(n,a))}function rn(e,t){return[`codebaseiq update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g codebaseiq@latest",""].join(`
5
+ `)}function nn(e,t){let r=dr(e),i=dr(t);if(!r||!i)return e!==t;for(let n=0;n<r.length;n++){let o=r[n]-i[n];if(o>0)return!0;if(o<0)return!1}return!1}function on(e){let t=e.XDG_CACHE_HOME||re(Zr(),".cache");return re(t,"codebaseiq")}function sn(e){let t=re(e,lr);if(!Xr(t))return null;try{let r=JSON.parse(X(t,"update notice cache"));return typeof r.checkedAt=="number"&&(typeof r.latestVersion=="string"||r.latestVersion===null)?{checkedAt:r.checkedAt,latestVersion:r.latestVersion}:null}catch{return null}}async function an(e,t,r){let i;try{i=await t()}catch{i=null}return cn(e,{checkedAt:r,latestVersion:i}),i}function cn(e,t){try{Jr(e,{recursive:!0}),Kr(re(e,lr),`${JSON.stringify(t,null,2)}
6
+ `)}catch{}}async function dn(){let e=await fetch(tn,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function dr(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}async function fr(e={}){let t=new ln;e.resident&&t.exitOverride(),e.terminalOutput&&t.configureOutput({writeOut:n=>process.stdout.write(ye(n)),writeErr:n=>process.stderr.write(ye(n))}),t.name("codebaseiq").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(R).option("--output-page-size <characters>","Return bounded output pages with an exact continuation command",Yt).option("--output-cursor <cursor>","Continue a bounded output page").option("--no-session","Disable the explicit exploration evidence ledger").option("--reemit","Recovery only: render source and graph evidence again instead of citing session receipts").option("--help-all","Display every command, including compatibility and deprecated controls");let r=await nr(e.invocationCommand);sr(t,r);let i=new un;return t.configureHelp({formatHelp:(n,o)=>n===t?cr(t,r):i.formatHelp(n,o)}),t.hook("preAction",async(n,o)=>{let a=o.name();if(e.resident){await e.resident.preAction(a);return}let l=wt(a),y=Wt(a);if(!l&&!y){pr(),await mr(a);return}let d=bt(),c=_(d);gt(c);let u=ee(d,c);A(u),pr(),await mr(a);let{config:f,paths:s}=u;if(l){let g=await rr({commandName:a,projectRoot:d,config:f,paths:s,dbPathSource:u.dbPathSource,gitContext:c});process.env.CODEBASEIQ_DEBUG&&console.error(`evidence-freshness: ${g.source}`),g.service.kind==="failed"&&console.error(`warning: codebaseiq watch service did not start: ${g.service.message}`),(g.service.kind==="failed"||g.service.kind==="skipped")&&j(d,R);return}if(!y){j(d,R);return}let h=Dt({commandName:a,projectRoot:d,cacheDir:s.cacheDir,cliVersion:R,config:f,gitContext:c});h.kind==="failed"&&console.error(`warning: codebaseiq watch service did not start: ${h.message}`),(h.kind==="failed"||h.kind==="skipped")&&j(d,R)}),t.hook("postAction",()=>A(void 0)),{program:t,descriptors:r}}async function mr(e){e.startsWith("__")||await ur({commandName:e})}function pr(){if(Je(),!Ye()||Ke())return;let e=null;try{e=Ct(t=>nt(t))}catch{}Ze({command:Xe()??`codebaseiq ${process.argv.slice(2).join(" ")}`,toolVersion:R,projectFingerprint:e})}import{execFileSync as hr}from"child_process";import{lstatSync as mn}from"fs";import{join as pn}from"path";var Te=3e4;function gr(){return{env:rt(),encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:Te,killSignal:"SIGKILL"}}function yr(e){return{generation:e.generation,epoch:e.epoch,changeSequence:e.changeSequence,headCommit:e.headCommit,treeOid:e.treeOid,fingerprintByPath:new Map(e.snapshot.files.map(t=>[t.path,t.hash])),languages:[...e.snapshot.languages],markerFiles:[...e.config.indexer?.typescript?.projects??[],...e.config.indexer?.clojure?.configPath?[e.config.indexer.clojure.configPath]:[]]}}function vr(e,t,r){if(r.epoch!==t.epoch)return{continuous:!1,reason:"the watcher observation epoch advanced since this generation was published"};if(r.changeSequence!==t.changeSequence)return{continuous:!1,reason:"the watcher observed a change after this generation was published"};let i,n;try{i=fn(e),n=hn(e)}catch(o){return{continuous:!1,reason:`git state could not be read: ${o instanceof Error?o.message:String(o)}`}}if(i.headCommit!==t.headCommit||i.treeOid!==t.treeOid)return{continuous:!1,reason:"the git HEAD tree moved since this generation was published"};for(let o of n){if(Ge(o,t.languages,t.markerFiles)==="other")continue;let a=t.fingerprintByPath.get(o),l=gn(pn(e,o));if(l===null)return{continuous:!1,reason:`indexed input ${o} is no longer readable as a plain file`};if(a!==l)return{continuous:!1,reason:a===void 0?`indexed input ${o} appeared after this generation was published`:`indexed input ${o} changed after this generation was published`}}return{continuous:!0}}function fn(e){let t=hr("git",["-C",e,"rev-parse","HEAD","HEAD^{tree}"],{...gr(),timeout:Te}).split(`
7
+ `).map(n=>n.trim()).filter(Boolean),[r,i]=t;if(!/^[0-9a-f]{40,64}$/.test(r??"")||!/^[0-9a-f]{40,64}$/.test(i??""))throw new Error("git did not report a resolved HEAD tree");return{headCommit:r,treeOid:i}}function hn(e){return hr("git",["-C",e,"status","--porcelain=v1","-z","--untracked-files=all","--no-renames","--","."],{...gr(),timeout:Te}).split("\0").filter(t=>t.length>=4&&t[2]===" ").map(t=>t.slice(3))}function gn(e){try{return mn(e).isFile()?Qe(e,{maxBytes:Ue,inputKind:"project-file"}):null}catch{return null}}var E=class extends Error{constructor(r,i){super(i);this.code=r}code};function xr(e){let t=!1,r,i=()=>{let d=r;if(r=void 0,!!d)try{d.db.close()}catch{}},n=()=>{let d=e.indexGeneration();if(!d)throw new E("stale-index","The resident index is not idle-fresh; run the command in-process.");return d},o=d=>{let c=e.observation();if(!c||c.published.generation!==d)throw new E("stale-index","No provable observation is bound to the published generation; run the command in-process.");let u=vr(e.projectRoot,c.published,{epoch:c.epoch,changeSequence:c.changeSequence});if(!u.continuous)throw new E("stale-index",`${u.reason}; run the command in-process.`)},a=()=>{let d=n(),c=xn(e.projectRoot);if(r&&(r.generation!==d||r.stamp!==c||N(e.dbPath)!==d)&&i(),!r){let u=xt(e.projectRoot);if(N(e.dbPath)!==d){try{u.close()}catch{}throw new E("stale-index","The published generation moved while opening the resident database.")}r={generation:d,stamp:c,db:u}}return r.db},l=d=>{if(!Se(d))throw new E("ineligible-command",`Command ${d} always executes in-process.`);n();let c=ee(e.projectRoot,_(e.projectRoot));if(c.dbPathSource!=="configured")throw new E("stale-index","The resident host does not serve fallback index locations.");A(c)};return{execute:async d=>{if(t)return U("busy","The resident host is executing another request; run the command in-process.");let c=d.argv[0];if(!c||c.startsWith("-")||!Se(c))return U("ineligible-command","Only evidence commands are served by the resident host.");let u;try{u=n(),o(u)}catch(p){return Sr(p)}t=!0;let f=Ae.now(),s=new Oe(d.tty),h=wn(d.envAllowlist),g=process.exitCode;process.exitCode=0,ke({argv:d.argv,execPath:d.clientInvocation?.execPath??process.execPath,...d.clientInvocation?.scriptPath!==void 0?{scriptPath:d.clientInvocation.scriptPath}:{},cwd:d.cwd}),be(a);try{let{program:p}=await fr({invocationCommand:c,resident:{preAction:l}});s.install();try{await p.parseAsync([...d.argv],{from:"user"})}finally{s.restore()}let b=typeof process.exitCode=="number"?process.exitCode:0;return{ok:!0,kind:"executed",protocolVersion:w,serverPid:process.pid,exitCode:b,stdout:s.stdout(),stderr:s.stderr(),generation:u,durationMs:Ae.now()-f}}catch(p){return p instanceof E?Sr(p):bn(p)?{ok:!0,kind:"executed",protocolVersion:w,serverPid:process.pid,exitCode:p.exitCode,stdout:s.stdout(),stderr:s.stderr(),generation:u,durationMs:Ae.now()-f}:U("execution-error",`Resident execution failed: ${p instanceof Error?p.message:String(p)}`)}finally{be(void 0),ke(void 0),A(void 0),process.exitCode=g,h(),t=!1}},releaseDatabase:i}}function U(e,t){return{ok:!1,protocolVersion:w,code:e,message:t}}function Sr(e){return e instanceof E?U(e.code,e.message):U("execution-error",e instanceof Error?e.message:String(e))}function bn(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&(e.code.startsWith("commander.")||e.code==="commander")&&typeof e.exitCode=="number"}function wn(e){let t=new Map;for(let r of Ft){t.set(r,process.env[r]);let i=e?.[r];i===void 0?delete process.env[r]:process.env[r]=i}return()=>{for(let[r,i]of t)i===void 0?delete process.env[r]:process.env[r]=i}}var Oe=class{constructor(t){this.tty=t}tty;stdoutChunks=[];stderrChunks=[];restorers=[];install(){this.restorers=[br(process.stdout,this.stdoutChunks),br(process.stderr,this.stderrChunks),ne(process.stdout,"isTTY",this.tty?.isTTY??!1),ne(process.stderr,"isTTY",this.tty?.isTTY??!1),ne(process.stdout,"columns",this.tty?.columns),ne(process.stderr,"columns",this.tty?.columns)]}restore(){for(let t of this.restorers.reverse())t();this.restorers=[]}stdout(){return this.stdoutChunks.join("")}stderr(){return this.stderrChunks.join("")}};function br(e,t){let r=e.write,i=(n,o,a)=>{t.push(typeof n=="string"?n:Buffer.isBuffer(n)?n.toString(typeof o=="string"?o:"utf8"):String(n));let l=typeof a=="function"?a:typeof o=="function"?o:void 0;return typeof l=="function"&&l(),!0};return e.write=i,()=>{e.write=r}}function ne(e,t,r){let i=Object.hasOwn(e,t),n=i?Object.getOwnPropertyDescriptor(e,t):void 0;return r===void 0?i&&Reflect.deleteProperty(e,t):Object.defineProperty(e,t,{value:r,configurable:!0,writable:!0}),()=>{n?Object.defineProperty(e,t,n):Reflect.deleteProperty(e,t)}}function xn(e){let t=yn("sha256");for(let i of[".codebaseiq.json",".codebaseiq-baseline.json"])t.update(i),t.update(wr(Me(e,i)));let r=Me(e,".codebaseiq","suppressions");t.update(r);try{for(let i of vn(r).sort())t.update(i),t.update(wr(Me(r,i)))}catch{t.update("absent")}return t.digest("hex")}function wr(e){try{let t=Sn(e);return`${t.size}:${t.mtimeMs}`}catch{return"absent"}}import{chmodSync as Cn,mkdirSync as Rn,rmSync as Cr}from"fs";import{createServer as En}from"net";import{dirname as Pn}from"path";var Rr=1e4,kn=5e3,In=6e5;function Er(e){let t=pe(e.projectRoot),r=0,i,n,o=new Set,a=En(c=>{o.add(c),c.setTimeout(Rr,()=>c.destroy()),c.on("error",()=>c.destroy()),c.on("close",()=>o.delete(c));let u=Qt(Vt,f=>{r+=1,i=new Date().toISOString(),e.onActivity?.(),l(f,c).then(s=>d(c,s)).catch(s=>{n=s instanceof Error?s.message:String(s),c.destroy()})},f=>{n=f.message,d(c,{ok:!1,protocolVersion:w,code:"invalid-request",message:f.message})});c.on("data",f=>{try{u.push(f)}catch(s){n=s instanceof Error?s.message:String(s),c.destroy()}})}),l=async(c,u)=>{let f=Gt(c);return f?pe(f.projectRoot)!==t?{ok:!1,protocolVersion:w,code:"wrong-project",message:"This query lane serves a different project root."}:y(f,u):{ok:!1,protocolVersion:w,code:"invalid-request",message:"The query lane received a request it could not validate."}},y=async(c,u)=>{if(c.kind==="ping"){let s=e.indexGeneration();return{ok:!0,kind:"pong",protocolVersion:w,serverPid:process.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{},cliVersion:e.cliVersion,projectRoot:t,...s?{indexGeneration:s}:{}}}if(!e.execute)return{ok:!1,protocolVersion:w,code:"unsupported",message:"Resident execution is not enabled on this service; run the command in-process."};let f=Math.max(c.deadlineMs??Bt,Rr);u.setTimeout(Math.min(f+kn,In));try{u.write(Re({ok:!0,kind:"accepted",protocolVersion:w,serverPid:process.pid},Ce))}catch(s){return n=s instanceof Error?s.message:String(s),u.destroy(),{ok:!1,protocolVersion:w,code:"execution-error",message:"The query lane could not acknowledge the request."}}try{return await e.execute(c)}catch(s){return n=s instanceof Error?s.message:String(s),{ok:!1,protocolVersion:w,code:"execution-error",message:`Resident execution failed: ${n}`}}},d=(c,u)=>{try{c.end(Re(u,Ce))}catch(f){n=f instanceof Error?f.message:String(f),c.destroy()}};return process.platform!=="win32"&&(Rn(Pn(e.socketPath),{recursive:!0,mode:448}),Cr(e.socketPath,{force:!0})),new Promise((c,u)=>{a.once("error",u),a.listen(e.socketPath,()=>{if(a.removeListener("error",u),a.on("error",f=>{n=f.message}),process.platform!=="win32")try{Cn(e.socketPath,384)}catch{}c({status:()=>({protocolVersion:w,socketPath:e.socketPath,requests:r,...i!==void 0?{lastRequestAt:i}:{},...n!==void 0?{lastError:n}:{}}),close:()=>new Promise(f=>{for(let s of o)s.destroy();a.close(()=>{process.platform!=="win32"&&Cr(e.socketPath,{force:!0}),f()})})})})})}import{randomUUID as Mn}from"crypto";import{Worker as An}from"worker_threads";var ie=class{constructor(t){this.options=t;this.now=t.now??Date.now,this.setTimer=t.setTimer??setTimeout,this.clearTimer=t.clearTimer??clearTimeout}options;now;setTimer;clearTimer;worker=null;active=null;activeFailure=null;terminating=null;closed=!1;workerGeneration=0;canAccept(){return!this.closed&&this.active===null&&this.terminating===null}start(t){if(!this.canAccept())return!1;if(t.deadlineAtMs<this.now()){try{this.options.onReject(t,`${this.options.name} request expired before processing.`)}catch(o){this.closed=!0,this.options.onFatal(Le(o))}return!0}let r=this.ensureWorker(),i=Math.max(1,Math.min(2147483647,t.deadlineAtMs-this.now())),n=this.setTimer(()=>{this.failActiveAfterTermination(`${this.options.name} request exceeded its deadline.`)},i);this.active={request:t,timer:n};try{r.postMessage({kind:"request",...t})}catch(o){this.failActiveAfterTermination(Pr(o))}return!0}async close(t=`${this.options.name} service is shutting down.`){if(this.closed=!0,this.active){await this.failActiveAfterTermination(t);return}await this.terminateWorker()}ensureWorker(){if(this.worker)return this.worker;let t=this.options.createWorker(),r=++this.workerGeneration;return t.on("message",i=>this.handleMessage(r,i)),t.on("error",i=>{r===this.workerGeneration&&this.failActiveAfterTermination(`${this.options.name} worker failed: ${i.message}`)}),t.on("exit",i=>{r!==this.workerGeneration||this.terminating||(this.worker=null,this.active&&this.failActiveAfterTermination(`${this.options.name} worker exited unexpectedly with code ${i}.`))}),this.worker=t,t}handleMessage(t,r){if(t!==this.workerGeneration||this.closed||!this.active)return;let i=Tn(r);if(!i){this.failActiveAfterTermination(`${this.options.name} worker returned an invalid response.`);return}if(i.requestId!==this.active.request.requestId){this.failActiveAfterTermination(`${this.options.name} worker returned a mismatched request identity.`);return}if(this.now()>this.active.request.deadlineAtMs){this.failActiveAfterTermination(`${this.options.name} request expired while it was processing.`);return}let n=this.active;try{this.options.onStatus(i.status),i.ok?this.options.onComplete(n.request,i.result,i.status):this.options.onReject(n.request,i.error,i.status)}catch(o){this.closed=!0,this.clearTimer(n.timer),this.options.onFatal(Le(o));return}this.releaseActive(n)}async failActiveAfterTermination(t){if(this.activeFailure){await this.activeFailure;return}let r=this.active;if(!r){await this.terminateWorker();return}this.clearTimer(r.timer);let i=(async()=>{if(await this.terminateWorker()){try{this.options.onReject(r.request,t)}catch(o){this.closed=!0,this.options.onFatal(Le(o));return}this.releaseActive(r)}})();this.activeFailure=i;try{await i}finally{this.activeFailure===i&&(this.activeFailure=null)}}releaseActive(t){this.active===t&&(this.active=null,this.clearTimer(t.timer))}async terminateWorker(){if(this.terminating)return this.terminating;let t=this.worker;if(!t)return!0;this.worker=null;let r=++this.workerGeneration;return this.terminating=(async()=>{try{return await t.terminate(),!0}catch(i){return this.closed=!0,this.options.onFatal(new Error(`${this.options.name} worker termination failed: ${Pr(i)}`,{cause:i})),!1}finally{r===this.workerGeneration&&(this.terminating=null)}})(),this.terminating}};function Tn(e){if(!e||typeof e!="object")return null;let t=e;if(t.kind!=="response"||typeof t.requestId!="string"||!("status"in t))return null;if(t.ok===!0){if(!("result"in t)||"error"in t)return null}else if(t.ok===!1){if("result"in t||typeof t.error!="string")return null}else return null;return t}function Le(e){return e instanceof Error?e:new Error(String(e))}function Pr(e){return e instanceof Error?e.message:String(e)}function kr(e){let t=()=>({protocolVersion:K,state:"idle",requests:0,sessionsCreated:0,sessionsReplaced:0,initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0});return Tr({name:"TypeScript index",paths:e.paths,now:e.now,limits:e.limits,initialStatus:t,parseEnvelope:dt,createWorker:()=>Mr(e,{kind:"index",projectRoot:e.projectRoot,dbPath:e.dbPath}),complete(r,i,n,o){fe(e.paths,r,{ok:!0,protocolVersion:K,id:i.id,baseGeneration:i.baseGeneration,response:n},{nowMs:o,limits:e.limits})},reject(r,i,n,o){he(e.paths,r,{ok:!1,protocolVersion:K,id:i,error:n},n,{nowMs:o,limits:e.limits})},onBusy:e.onBusy,onFatal:e.onFatal})}function Ir(e){let t=()=>({protocolVersion:Z,state:"idle",requests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0});return Tr({name:"TypeScript semantic",paths:e.paths,now:e.now,limits:e.limits,initialStatus:t,parseEnvelope:St,createWorker:()=>Mr(e,{kind:"semantic",projectRoot:e.projectRoot}),complete(r,i,n,o){fe(e.paths,r,{ok:!0,protocolVersion:Z,id:i.id,generation:i.generation,response:n},{nowMs:o,limits:e.limits})},reject(r,i,n,o){he(e.paths,r,{ok:!1,protocolVersion:Z,id:i,error:n},n,{nowMs:o,limits:e.limits})},onBusy:e.onBusy,onFatal:e.onFatal})}function Tr(e){let t=e.now??Date.now,r=D(process.pid),i={pid:process.pid,...r?{processIdentity:r}:{}},n=`${e.name.toLowerCase().replaceAll(" ","-")}-${process.pid}-${Mn()}`,o={...e.limits,maxBatch:1},a=null,l=e.initialStatus(),y=!1,d=s=>{y=!0,e.onFatal(s)},c=new ie({name:e.name,createWorker:e.createWorker,now:t,onComplete(s,h,g){let p=u(s.requestId);l=g,e.complete(p.claim,p.envelope,h,t()),f(p)},onReject(s,h,g){let p=u(s.requestId);g!==void 0&&(l=g),e.reject(p.claim,p.envelope.id,h,t()),f(p)},onStatus(s){l=s},onFatal:d});return{poll(){if(y||!c.canAccept())return 0;let s=ot(e.paths,{ownerId:n,nowMs:t(),limits:o,owner:i,liveness:{isProcessAlive:tt,readProcessIdentity:D}})[0];if(!s)return 0;let h=s.requestId;try{let g=e.parseEnvelope(st(s,o));if(h=g.id,g.id!==s.requestId)throw new Error(`${e.name} request identity does not match its mailbox path.`);if(g.deadlineAtMs<t())throw new Error(`${e.name} request expired before processing.`);if(a={claim:s,envelope:g},e.onBusy?.(g.deadlineAtMs),!c.start({requestId:g.id,deadlineAtMs:g.deadlineAtMs,payload:g}))throw new Error(`${e.name} worker lane closed admission after claiming a request.`)}catch(g){let p=Ln(g);try{e.reject(s,h,p,t()),a?.claim===s&&f(a)}catch(b){d(On(b))}}return 1},status(){return{...l,mailbox:at(e.paths)}},async close(s){await c.close(s)}};function u(s){let h=a;if(!h||h.envelope.id!==s)throw new Error(`${e.name} parent lost the active mailbox claim.`);return h}function f(s){a===s&&(a=null,e.onBusy?.(void 0))}}function Mr(e,t){if(e.createWorker)return e.createWorker(t);let r=e.workerUrl??new URL("./typescript-mailbox-worker.js",import.meta.url);return new An(r,{workerData:t})}function On(e){return e instanceof Error?e:new Error(String(e))}function Ln(e){return e instanceof Error?e.message:String(e)}import{existsSync as Wn}from"fs";import{fileURLToPath as Ar}from"url";import{Worker as Dn}from"worker_threads";var qn=2e3;function Wr(e){let t=e.userCacheRoot??Et(),r={kind:"sentinel-worker",projectRoot:e.projectRoot,cacheDir:e.indexPaths.cacheDir,dbPath:e.indexPaths.dbPath,cliVersion:e.cliVersion,userCacheRoot:t},i=e.createWorker??_n,n,o=0,a=!1,l=!1,y,d=()=>{let s;try{s=i(r)}catch(p){e.log(`worker could not be started: ${Lr(p)}`);return}let h,g={worker:s,exited:new Promise(p=>{h=p})};n=g,s.on("message",p=>{n===g&&c(p)}),s.on("error",p=>e.log(`worker failed: ${p.message}`)),s.on("exit",p=>{if(h(),n===g&&(n=void 0,o=0,!l)){if(e.log(`worker exited unexpectedly with code ${p}`),Or(t,e.projectRoot),a){e.log("worker will not be restarted again");return}a=!0,d()}})},c=s=>{let h=Nn(s);h?.kind==="sessions"?o=h.live:h?.kind==="log"&&e.log(h.message)},u=s=>{try{n?.worker.postMessage(s)}catch(h){e.log(`${s.kind} could not be posted: ${Lr(h)}`)}},f=async()=>{l=!0;let s=n;s&&(u({kind:"shutdown"}),await jn(s.exited,e.stopTimeoutMs??qn),n===s&&(n=void 0,await s.worker.terminate().catch(()=>{}))),o=0,Or(t,e.projectRoot)};return d(),{filesChanged:s=>u({kind:"filesChanged",paths:s}),generationPublished:()=>u({kind:"generationPublished"}),releaseDb:()=>u({kind:"releaseDb"}),liveSessionCount:()=>o,stop:()=>y??=f()}}function Dr(){let e,t=!1;return{attach(r){e=r},filesChanged:r=>e?.filesChanged(r),bulkChange:()=>e?.filesChanged([]),watcherStatus(r){r.state==="idle"?t=!1:e&&!t&&(t=!0,e.releaseDb())},generationPublished(){t=!1,e?.generationPublished()},liveSessionCount:()=>e?.liveSessionCount()??0,async stop(){await e?.stop()}}}function _n(e){let t=new URL("./sentinel-worker.js",import.meta.url);if(!Wn(Ar(t)))throw new Error(`sentinel worker was not found at ${Ar(t)}. Run npm run build first.`);let r=new Dn(t,{workerData:e});return r.unref(),r}function Nn(e){if(typeof e!="object"||e===null)return;let{kind:t,live:r,message:i}=e;if(t==="sessions"&&typeof r=="number"&&Number.isInteger(r)&&r>=0)return{kind:t,live:r};if(t==="log"&&typeof i=="string")return{kind:t,message:i}}function Or(e,t){try{kt(e,Pt(t),process.pid)}catch{}}async function jn(e,t){let r,i=new Promise(n=>{r=setTimeout(n,t)});try{await Promise.race([e,i])}finally{clearTimeout(r)}}function Lr(e){return e instanceof Error?e.message:String(e)}var Bn=1e3,Fn=250,Un=6e4,Qn=10,Gn=50,Hn=250;function zn(e,t=1){if(e>0)return Qn;let r=Math.max(0,Math.min(3,t-1));return Math.min(Hn,Gn*2**r)}async function Yn(e,t){let r=t.processIndexRequests(),i=t.processSemanticRequests(),n=r+i,o=n>0?0:e+1;if(t.afterMailboxPoll({indexRequests:r,semanticRequests:i,processedRequests:n}),t.shouldStop())return{indexRequests:r,semanticRequests:i,processedRequests:n,consecutiveIdlePolls:o,stopped:!0};let a=zn(n,o);return await t.wait(a),{indexRequests:r,semanticRequests:i,processedRequests:n,consecutiveIdlePolls:o,stopped:!1,delayMs:a}}function Xn(e,t=v.env){return e==="fresh"||t.CODEBASEIQ_SENTINEL_ENSURE==="1"?null:{kind:"watch-startup",detail:`index ${e} when watch service started`}}async function Jn(e,t,r={}){let i=qt(e,t),n=i.projectRoot;v.env.CODEBASEIQ_PROJECT_ROOT=n;let o=ft(n);o.watch={...o.watch,...r};let a=ht(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let l=et(n,o),y=ut(l.cacheDir),d=D(v.pid),c=jt(y.lockPath,n,{readProcessIdentity:m=>m===v.pid?d:D(m)});if(!c.acquired)return;let u=new te(y.refreshRequestsPath,{retryDelayMs:Math.max(1e3,a.cooldownMs)});u.initializeAfterOwnershipAcquired();let f=Date.now(),s=q(),h=f,g=s,p={state:"idle"},b,Q,P,G,oe=J(l.dbPath),se=!1,We=!1,De=0,qe=Number.NEGATIVE_INFINITY,_e=Number.NEGATIVE_INFINITY,Ne=Number.NEGATIVE_INFINITY,je=Number.NEGATIVE_INFINITY,ae,ce,$e=0,de=vt(l.cacheDir),le=ct(l.cacheDir);Rt(de),pt(le);let H,$,L,Ve=o.sentinel?.enabled===!0,I=Dr(),Be=m=>{if(L=void 0,!!m)try{let x=_(n);if(!x?.headCommit||!x.treeOid)return;let S=ze(X(l.metaPath,"reindex metadata"));if(S.kind!=="legacy"&&S.kind!=="supported")return;let k=He(S.metadata.fingerprint);if(!k)return;L=yr({generation:m,...W.observation(),headCommit:x.headCommit,treeOid:x.treeOid,snapshot:k,config:o})}catch{}},C=(m=!1,x=m?"durable":"visibility")=>{if(!We)return;let S=Date.now(),k=q();!m&&k-qe<Bn||(qe=k,_t(y.statePath,{version:1,protocolVersion:lt,pid:v.pid,...d?{processIdentity:d}:{},projectRoot:n,...i.worktreeId?{worktreeId:i.worktreeId}:{},cliVersion:t,startedAt:new Date(f).toISOString(),heartbeatAt:new Date(S).toISOString(),lastActivityAt:new Date(h).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date((I.liveSessionCount()>0?S:h)+a.idleTimeoutMs).toISOString()},watcher:p,...p.state==="idle"&&b?{indexGeneration:b}:{},...Q?{lastRefresh:Q}:{},...P?{lastError:P}:{},reindexActivity:oe,refreshRequests:u.status(),typescriptSemantic:{...ue.status(),...ae===void 0?{}:{busyUntil:new Date(ae).toISOString()}},typescriptIndex:{...me.status(),...ce===void 0?{}:{busyUntil:new Date(ce).toISOString()}},...H?{queryLane:H.status()}:{}},{durability:x}))},T=()=>{h=Date.now(),g=q()},Fe=m=>{T(),G??=m,P={at:new Date().toISOString(),message:m.message},C(!0,"visibility")},ue=Ir({paths:de,projectRoot:n,onBusy(m){ae=m===void 0?void 0:m+5e3,C(!0,"visibility")},onFatal:Fe}),me=kr({paths:le,projectRoot:n,dbPath:l.dbPath,onBusy(m){ce=m===void 0?void 0:m+5e3,C(!0,"visibility")},onFatal:Fe}),W=new It({projectRoot:n,config:{...o,watch:a},outputDb:l.dbPath,languages:o.languages,onStatus(m){p=m,I.watcherStatus(m),m.state!=="idle"&&(b=void 0,L=void 0,$?.releaseDatabase(),T()),C(!0)},...Ve?{onFileChanged:I.filesChanged,onBulkChange:I.bulkChange}:{},onReindexComplete(){T();let m=ve(n,o,l);return Q=m.lastRefresh,b=m.state==="fresh"?N(l.dbPath)??void 0:void 0,Be(b),oe=J(l.dbPath),u.completeActive(),P=void 0,C(!0),I.generationPublished(),m.state==="fresh"},onReindexError(){u.failActive()},onRefreshSuppressed(m){let x=it(l.dbPath,m);x.state==="failed"&&(P={at:new Date().toISOString(),message:`Suppressed-refresh telemetry was not recorded: ${x.reason}`},C(!0,"visibility")),oe=J(l.dbPath)},onError(m){T(),b=void 0,L=void 0,P={at:new Date().toISOString(),message:m.message},C(!0)}}),z=()=>{se=!0};v.once("SIGINT",z),v.once("SIGTERM",z);let V=!1,Y,B;try{try{$=v.env.CODEBASEIQ_DAEMON==="1"||o.daemon?.enabled===!0?xr({projectRoot:n,dbPath:l.dbPath,indexGeneration:()=>b,observation:()=>L?{published:L,...W.observation()}:void 0}):void 0,H=await Er({socketPath:Ut(l.cacheDir),projectRoot:n,cliVersion:t,...d?{processIdentity:d}:{},indexGeneration:()=>b,onActivity:T,...$?{execute:k=>$.execute(k)}:{}})}catch(S){P={at:new Date().toISOString(),message:`Query lane did not start: ${S instanceof Error?S.message:String(S)}`}}Ve&&I.attach(Wr({projectRoot:n,indexPaths:l,cliVersion:t,log(S){v.env.CODEBASEIQ_DEBUG&&console.error(`sentinel: ${F(S)}`)}})),W.start();let m=ve(n,o,l);Q=m.lastRefresh,b=m.state==="fresh"?N(l.dbPath)??void 0:void 0,Be(b);let x=Xn(m.state);for(x&&W.requestRefresh(x,{immediate:!0}),T(),We=!0,C(!0);!se;){let S=await Yn($e,{processIndexRequests:()=>me.poll(),processSemanticRequests:()=>ue.poll(),afterMailboxPoll:({processedRequests:k})=>{let O=q();if(O-je>=Un&&(je=O,ge(le),ge(de)),O-Ne>=6e4&&(Ne=O,j(n,t)),O-_e>=Fn){_e=O;let M=Nt(y.activityPath);M&&M.atMs>h&&(h=M.atMs,g=O),M?.refreshRequestedAtMs!==void 0&&M.refreshRequestedAtMs>De&&(De=M.refreshRequestedAtMs,u.observeLegacyRequest(M.refreshRequestedAtMs,M.refreshDetail??"stale index observed by a legacy command")),u.poll(p,_r=>{T(),W.requestRefresh({kind:"watch-demand",detail:_r},{immediate:!0})})}k>0&&(T(),C(!0,"visibility")),C()},shouldStop:()=>se||G!==void 0||$t({watcher:p,lastActivityAtMs:g,nowMs:q(),idleTimeoutMs:a.idleTimeoutMs,liveSessions:I.liveSessionCount()}),wait:Kn});if($e=S.consecutiveIdlePolls,S.stopped)break}}catch(m){V=!0,Y=m}finally{v.off("SIGINT",z),v.off("SIGTERM",z),await H?.close(),await I.stop(),$?.releaseDatabase(),await Promise.all([ue.close("TypeScript semantic service stopped before completing the request."),me.close("TypeScript index service stopped before completing the request.")]);let m=await W.stop();m.state==="stopped"?(qr(y.statePath,{force:!0}),qr(y.activityPath,{force:!0}),c.release()):(P={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${m.reasons.join("; ")}`},C(!0),B=new Error(P.message))}if(!V&&G&&(V=!0,Y=G),V&&B)throw new AggregateError([Y,B],"Watch service execution and shutdown both failed.");if(V)throw Y;if(B)throw B}function Kn(e){return new Promise(t=>setTimeout(t,e))}function Zn(e,t={report:r=>console.error(r),exit:r=>v.exit(r)}){return t.report(`watch-service: ${F(e instanceof Error?e.message:String(e))}`),t.exit(1)}var ei=v.argv[1]?Vn($n(v.argv[1])).href:null;if(ei===import.meta.url){mt();let e=v.argv[2],t=v.argv[3],r=ti(v.argv[4]);if(!e||!t)console.error("watch-service: expected <project-root> <cli-version>"),v.exitCode=1;else try{await Jn(e,t,r)}catch(i){Zn(i)}}function ti(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}export{Yn as runWatchServiceLoopIteration,Jn as runWatchServiceServer,Xn as startupRefreshTrigger,Zn as terminateWatchServiceProcess,zn as watchServiceLoopDelayMs};
8
8
  //# sourceMappingURL=watch-server.js.map
@@ -61,8 +61,8 @@ The operator chooses the material question and deliberately selects a control. T
61
61
  | Locate exact roots | `search <exact-text>`, `outline <file>`, `fan-in [symbol]`, `entrypoints [text]` |
62
62
  | Project typed relationships | `evidence`, `entry-map <entry>` |
63
63
  | Read selected behavior/source | `inspect`, `code <selectors...>` |
64
- | Analyze declared result units | `stats`, `files <pattern>`, `methods <className>`, `refs <symbol>`, `trace <symbol>`, `deps <file>`, `rdeps <file>`, `system <module>`, `surface <module>`, `dead [scope]`, `hotspots`, `imports <file>`, `imported-by <symbol>`, `unused-imports <file>`, `members <symbol>`, `fan-out [file]`, `coupling [file1] [file2]`, `cycles`, `architecture`, `bottlenecks`, `isolated`, `by-kind <kind>`, `kind-counts`, `dependency-depth`, `hierarchy <symbol>`, `call-graph <symbol>`, `similar [symbol] [other]`, `similar-files [file]`, `react-component-duplicates [file]`, `react-hook-candidates [file]`, `react-large-component-pressure [file]`, `vue-component-duplicates [file]`, `vue-composable-candidates [file]`, `vue-large-view-pressure [file]`, `similar-chains`, `extract-candidates`, `locality-candidates [symbol-or-file]`, `affected <symbol>`, `change-surface <file>`, `cleanup-plan`, `co-change [file]`, `recent-duplicates`, `doc-drift [doc]`, `unused-params`, `incomplete-migration`, `context <target>`, `drift [module]`, `wrapper-candidates`, `passthrough-candidates`, `stale-abstractions`, `complexity-hotspots`, `self-audit`, `complexity <symbol>`, `reference-neighborhood <symbol>`, `value-flow <symbol>`, `dependence-slice <symbol-or-location>`, `reference-reachability <symbol>`, `redundant-reexports`, `duplicate-bodies`, `twin-drift`, `twin-ab <symbolA> <symbolB>`, `not-implemented`, `decorative-checkers`, `test-quality`, `similar-signatures`, `diff-impact`, `check-deps`, `capabilities`, `config-validate`, `doctor`, `status` |
65
- | Maintain repository/tool state | `reindex`, `augment-sources`, `augment-vue`, `session`, `tla <operation> [spec]`, `health`, `install-skills`, `init`, `suppress <id>`, `setup`, `setup-agent`, `uninstall`, `watch` |
64
+ | Analyze declared result units | `stats`, `files <pattern>`, `methods <className>`, `refs <symbol>`, `trace <symbol>`, `deps <file>`, `rdeps <file>`, `system <module>`, `surface <module>`, `dead [scope]`, `hotspots`, `imports <file>`, `imported-by <symbol>`, `unused-imports <file>`, `members <symbol>`, `fan-out [file]`, `coupling [file1] [file2]`, `cycles`, `architecture`, `bottlenecks`, `isolated`, `by-kind <kind>`, `kind-counts`, `dependency-depth`, `hierarchy <symbol>`, `call-graph <symbol>`, `similar [symbol] [other]`, `similar-files [file]`, `react-component-duplicates [file]`, `react-hook-candidates [file]`, `react-large-component-pressure [file]`, `vue-component-duplicates [file]`, `vue-composable-candidates [file]`, `vue-large-view-pressure [file]`, `similar-chains`, `extract-candidates`, `locality-candidates [symbol-or-file]`, `affected <symbol>`, `change-surface <file>`, `cleanup-plan`, `co-change [file]`, `recent-duplicates`, `doc-drift [doc]`, `unused-params`, `incomplete-migration`, `context <target>`, `reuse [description]`, `drift [module]`, `wrapper-candidates`, `passthrough-candidates`, `stale-abstractions`, `complexity-hotspots`, `self-audit`, `complexity <symbol>`, `reference-neighborhood <symbol>`, `value-flow <symbol>`, `dependence-slice <symbol-or-location>`, `reference-reachability <symbol>`, `redundant-reexports`, `duplicate-bodies`, `twin-drift`, `twin-ab <symbolA> <symbolB>`, `not-implemented`, `decorative-checkers`, `test-quality`, `similar-signatures`, `diff-impact`, `check-deps`, `capabilities`, `config-validate`, `doctor`, `status` |
65
+ | Maintain repository/tool state | `reindex`, `augment-sources`, `augment-vue`, `session`, `tla <operation> [spec]`, `health`, `install-skills`, `init`, `suppress <id>`, `setup`, `setup-agent`, `uninstall`, `watch`, `view` |
66
66
 
67
67
  ### Typed relationship meanings
68
68
 
@@ -243,6 +243,7 @@ An unavailable frontier is a relationship class for which no registered analyzer
243
243
  | `entrypoints [text]` | Find callables where control may enter from outside the indexed call graph | bounded | `evidence`, `inspect`, `code` | `-s, --scope <path>`<br>`--json`<br>`--result-only`<br>`--compact` |
244
244
  | `entry-map <entry>` | Map the complete indexed call graph from one detected entry point, collapsed by file | bounded | `inspect`, `code` | `--expand <region-id>`<br>`--json`<br>`--result-only`<br>`--compact` |
245
245
  | `call-graph <symbol>` | Show static may-call edges with exact/candidate evidence and explicit blind spots | variable | `inspect`, `code` | `--full`<br>`--json`<br>`--result-only`<br>`--compact` |
246
+ | `view` | Open a local browser map of folders, files, and one symbol at a time | variable | - | `--focus <selector>`<br>`--scope <dir>`<br>`--file <path>`<br>`--port <n>`<br>`--no-open` |
246
247
 
247
248
  ### Impact
248
249
 
@@ -265,6 +266,7 @@ An unavailable frontier is a relationship class for which no registered analyzer
265
266
  | Command | Description | Cost | Closes disclosed gaps with | Options |
266
267
  |---|---|---|---|---|
267
268
  | `context <target>` | Compiler-backed context for a symbol, file, or module | bounded | `inspect`, `code` | `--impact-depth <n>`<br>`--slice-depth <n>`<br>`-s, --scope <path>`<br>`-n, --limit <n>`<br>`--detail`<br>`--full`<br>`--json`<br>`--result-only`<br>`--compact` |
269
+ | `reuse [description]` | Heuristic reuse candidates for code about to be written: existing symbols matching your probes or a described intent | bounded | `code`, `evidence`, `inspect` | `--term <group>`<br>`--name <identifier>`<br>`--calls <callee>`<br>`--param <word>`<br>`--returns <word>`<br>`--kind <kind>`<br>`--probes <file>`<br>`--mode <mode>`<br>`--endpoint <name>`<br>`--agent <name>`<br>`--bucket <bucket>`<br>`-n, --limit <n>`<br>`--full`<br>`-s, --scope <path>`<br>`--providers`<br>`--refresh-embeddings`<br>`--timeout <ms>`<br>`--json`<br>`--result-only`<br>`--compact` |
268
270
 
269
271
  ### Health
270
272
 
@@ -285,7 +287,7 @@ An unavailable frontier is a relationship class for which no registered analyzer
285
287
  | `config-validate` | Validate .codebaseiq.json, structured suppressions, architecture, and coupling groups | bounded | `inspect`, `code` | `--json`<br>`--result-only`<br>`--compact` |
286
288
  | `suppress <id>` | Record an accepted finding under .codebaseiq/suppressions with a required reason | variable | - | `--reason <text>`<br>`--reason-code <code>`<br>`--evidence <kind:referent>`<br>`--check <check>`<br>`--file <path>`<br>`--expires-at <iso>`<br>`--replace <revision>`<br>`--json`<br>`--result-only`<br>`--compact` |
287
289
  | `doctor` | Diagnose configuration, index freshness, dependencies, and project capabilities | bounded | `inspect`, `code` | `--json`<br>`--result-only`<br>`--compact` |
288
- | `setup` | Install skills, write agent guidance, refresh the index, and report repository health | variable | - | `--guided`<br>`--yes`<br>`--no-skills`<br>`--no-parsers`<br>`--install-missing`<br>`--no-health`<br>`--dossier-dir <path>`<br>`--json`<br>`--result-only`<br>`--compact` |
290
+ | `setup` | Install skills, write agent guidance, refresh the index, and report repository health | variable | - | `--guided`<br>`--yes`<br>`--no-skills`<br>`--no-parsers`<br>`--install-missing`<br>`--no-health`<br>`--dossier-dir <path>`<br>`--builder-mode <mode>`<br>`--embeddings-endpoint <name=url>`<br>`--embeddings-model <model>`<br>`--agent-command <name>`<br>`--builder-scope <scope>`<br>`--sentinel`<br>`--no-sentinel`<br>`--sentinel-live [families]`<br>`--json`<br>`--result-only`<br>`--compact` |
289
291
  | `setup-agent` | Write concise codebaseiq mapping and cleanup guidance to AGENTS.md and CLAUDE.md | variable | - | - |
290
292
  | `uninstall` | Remove selected codebaseiq-owned skills or project guidance | variable | - | `--global`<br>`--project`<br>`--dry-run`<br>`--verbose`<br>`--json`<br>`--result-only`<br>`--compact` |
291
293
  | `watch` | Watch in the foreground or manage the project refresh service | variable | - | `--daemon`<br>`--status`<br>`--stop`<br>`--debounce <ms>`<br>`--cooldown <ms>`<br>`--git-poll <ms>`<br>`--idle-timeout <ms>`<br>`--json`<br>`--result-only`<br>`--compact` |