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
package/dist/runtime.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { P as ProjectConfig, W as WatchConfig, a as WatchResourceBudgetConfig, S as SupportedLanguage, T as TypeScriptProjectMode, D as DerivedObservationStateAuthority, O as ObservationSourceKind, b as ObservationReceipt } from './config-types-BNoC96J3.js';
2
- export { c as DecodedObservationReceipt, L as LEGACY_OBSERVATION_RECEIPT_SCHEMA_VERSION, d as OBSERVATION_IDENTITY_CANONICALIZATION_VERSION, e as OBSERVATION_IDENTITY_HASH_ALGORITHM, f as OBSERVATION_IDENTITY_SCHEMA_VERSION, g as OBSERVATION_RECEIPT_SCHEMA_VERSION, h as OBSERVATION_STATE_AUTHORITY_POLICY_VERSION, i as ObservationAuthorityKind, j as ObservationComparedFact, k as ObservationComparisonReason, l as ObservationIdentity, m as ObservationReceiptComparison, n as ObservationReceiptV1, o as ObservationReceiptV2, p as ObservationRelationshipJudgment, q as ObservationRelationshipState, r as ObservationSourceFact, s as ObservationStabilityProof, t as ObservationStabilityProofKind, u as ObservationStateAuthority, R as RelevantInputIdentity, v as RelevantInputRelationshipJudgment, w as compareObservationReceipts, x as createObservationIdentity, y as decodeObservationReceipt, z as deriveObservationStateAuthority, A as isObservationReceipt, B as observationReceiptGenerationIdentity, E as observationReceiptStabilityLabel, F as observationReceiptWorkspaceIdentity } from './config-types-BNoC96J3.js';
1
+ import { P as ProjectConfig, W as WatchConfig, a as WatchResourceBudgetConfig, S as SupportedLanguage, T as TypeScriptProjectMode, D as DerivedObservationStateAuthority, O as ObservationSourceKind, b as ObservationReceipt } from './config-types-D6X5S68_.js';
2
+ export { c as DecodedObservationReceipt, L as LEGACY_OBSERVATION_RECEIPT_SCHEMA_VERSION, d as OBSERVATION_IDENTITY_CANONICALIZATION_VERSION, e as OBSERVATION_IDENTITY_HASH_ALGORITHM, f as OBSERVATION_IDENTITY_SCHEMA_VERSION, g as OBSERVATION_RECEIPT_SCHEMA_VERSION, h as OBSERVATION_STATE_AUTHORITY_POLICY_VERSION, i as ObservationAuthorityKind, j as ObservationComparedFact, k as ObservationComparisonReason, l as ObservationIdentity, m as ObservationReceiptComparison, n as ObservationReceiptV1, o as ObservationReceiptV2, p as ObservationRelationshipJudgment, q as ObservationRelationshipState, r as ObservationSourceFact, s as ObservationStabilityProof, t as ObservationStabilityProofKind, u as ObservationStateAuthority, R as RelevantInputIdentity, v as RelevantInputRelationshipJudgment, w as compareObservationReceipts, x as createObservationIdentity, y as decodeObservationReceipt, z as deriveObservationStateAuthority, A as isObservationReceipt, B as observationReceiptGenerationIdentity, E as observationReceiptStabilityLabel, F as observationReceiptWorkspaceIdentity } from './config-types-D6X5S68_.js';
3
3
  import { watch } from 'chokidar';
4
- import { R as RefreshTrigger, W as WatcherStatus } from './scip-cli-B7N3haxa.js';
5
- export { g as getScipVersion, i as isScipInstalled, p as printScipInstallInstructions } from './scip-cli-B7N3haxa.js';
4
+ import { R as RefreshTrigger, W as WatcherStatus } from './scip-cli-BRFKkHQn.js';
5
+ export { g as getScipVersion, i as isScipInstalled, p as printScipInstallInstructions } from './scip-cli-BRFKkHQn.js';
6
6
 
7
7
  /**
8
8
  * One operating-system process instance. A PID alone names a reusable slot;
@@ -79,6 +79,14 @@ interface WatcherOptions {
79
79
  onReindexComplete?: (durationMs: number, trigger: RefreshTrigger) => boolean | void;
80
80
  onReindexError?: (error: Error, trigger: RefreshTrigger) => void;
81
81
  onRefreshSuppressed?: (trigger: RefreshTrigger) => void;
82
+ /**
83
+ * Indexed-input changes, coalesced over a short trailing window. Independent
84
+ * of reindex scheduling: it fires while a refresh is debounced, cooling down,
85
+ * or budget-paused.
86
+ */
87
+ onFileChanged?: (paths: string[]) => void;
88
+ /** A window saw too many distinct paths to enumerate; `onFileChanged` stays silent for it. */
89
+ onBulkChange?: () => void;
82
90
  onError?: (error: Error) => void;
83
91
  }
84
92
  type WatchBudgetInspector = (outputDb: string, config: ResolvedWatchConfig['resourceBudget'], now: Date) => ReindexActivityBudgetDecision;
@@ -174,6 +182,8 @@ declare class Watcher {
174
182
  private onReindexComplete;
175
183
  private onReindexError;
176
184
  private onRefreshSuppressed;
185
+ private onFileChanged?;
186
+ private onBulkChange?;
177
187
  private onError;
178
188
  private reindexRunner;
179
189
  private subscriptionFactory;
@@ -191,6 +201,9 @@ declare class Watcher {
191
201
  private pendingTrigger;
192
202
  private reindexInFlight;
193
203
  private lastReindexEnd;
204
+ private fileChangeTimer;
205
+ private pendingFileChanges;
206
+ private bulkChangePending;
194
207
  private fsWatchers;
195
208
  private sourcePollingFallbackStarted;
196
209
  private gitPollTimer;
@@ -222,6 +235,13 @@ declare class Watcher {
222
235
  private handleSourceWatcherError;
223
236
  private isIgnoredWatchPath;
224
237
  private handleFileChange;
238
+ /**
239
+ * Collect a path into the current window; the first path of a window starts
240
+ * its timer, so delivery latency is bounded however long changes keep coming.
241
+ */
242
+ private noteFileChange;
243
+ private flushFileChangeWindow;
244
+ private clearFileChangeWindow;
225
245
  private relativeWatchPath;
226
246
  private scheduleReindex;
227
247
  private triggerReindex;
package/dist/runtime.js CHANGED
@@ -1,4 +1,4 @@
1
- import{b as _e,c as Pe,e as Mt,f as Dt,g as $t,l as Ae,o as Ne}from"./chunk-YVCIMIOC.js";import{a as Te}from"./chunk-NEDP5RFQ.js";import{c as Se,e as $,f as Oe,k as Ie,l as Ee}from"./chunk-ZKX2FRS6.js";import"./chunk-OANDYLJQ.js";import"./chunk-3LCDIREB.js";import{$ as ke,A as be,B as ve,G as Re,I as Ce,Q as xe,T as we,Y as z,ca as P,da as L,i as ye,n as l,p as g,q as x,r as h,t as _}from"./chunk-NNJ2KZZG.js";import{existsSync as fn}from"fs";import{randomUUID as mn}from"crypto";import{isAbsolute as ji,join as et,relative as Vi,resolve as Mi}from"path";var S=1,I=2,Lt="./node_modules/codebaseiq/docs/schemas/project-config.schema.json";function X(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(c){return{kind:"malformed",reason:`invalid JSON: ${c instanceof Error?c.message:String(c)}`}}if(!l(t))return{kind:"malformed",reason:"project config must be a JSON object"};let n=t.schemaVersion;if(n!==void 0&&!Number.isInteger(n))return{kind:"malformed",reason:"schemaVersion must be an integer"};let i=n===void 0?S:n;if(i!==S&&i!==I)return{kind:"unsupported",schemaVersion:i,direction:i<S?"older":"future"};let r=t.$schema;if(r!==void 0&&(typeof r!="string"||r.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let s=F(t),o=i!==I||typeof t.$schema!="string";return i===S?{kind:"legacy",sourceVersion:S,config:s,needsMigration:o}:{kind:"supported",sourceVersion:I,config:s,needsMigration:o}}function F(e){let t=e,{$schema:n,schemaVersion:i,...r}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:Lt,schemaVersion:I,...r}}function je(e){return`${JSON.stringify(F(e),null,2)}
2
- `}import{createHash as Ft}from"crypto";var m=1,C=2,W=1,N=1,A="sha256",te=1;function Le(e,t,n){if(!h(e)||!qe(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:W,canonicalizationVersion:N,hashAlgorithm:A,projection:{name:e,version:t},digest:Ft(A).update(Wt(e,t,n)).digest("hex")}}function Wt(e,t,n){return`{"canonicalizationVersion":${N},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function ne(e){if(!l(e))return{kind:"malformed",reason:"observation receipt must be an object"};let t=e.schemaVersion;if(!Number.isInteger(t))return{kind:"malformed",reason:"observation receipt schemaVersion must be an integer"};if(t===m)return Yt(e)?{kind:"legacy",schemaVersion:m,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===C)return Ht(e)?{kind:"supported",schemaVersion:C,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<m?"older":"future"}}function G(e){let t=ne(e);return t.kind==="legacy"||t.kind==="supported"}function ie(e,t){return{collaborationDomain:O(y(e,n=>n.facts.collaborationDomain),y(t,n=>n.facts.collaborationDomain)),repositoryLineage:O(y(e,n=>n.facts.repositoryLineage),y(t,n=>n.facts.repositoryLineage)),workspaceInstance:O(y(e,n=>n.facts.workspaceInstance),y(t,n=>n.facts.workspaceInstance)),wholeContent:O(y(e,n=>n.facts.wholeContent),y(t,n=>n.facts.wholeContent)),relevantInputs:Gt(e,t),indexInput:O(y(e,n=>n.facts.index?.inputs),y(t,n=>n.facts.index?.inputs)),indexGeneration:Bt(e,t),observationStability:Ut(e,t)}}function B(e,t,n=ie(e,t)){let i=[["collaborationDomain",n.collaborationDomain],["wholeContent",n.wholeContent],["observationStability",n.observationStability]],r=[];for(let[o,c]of i)c.state!=="established"&&r.push(`${o}:${c.state}`);for(let[o,c]of[["left",e],["right",t]]){let a=qt(c);a!=="not-applicable"&&a!=="established"&&r.push(`${o}IndexAlignment:${a}`)}let s=i.some(([,o])=>o.state==="disproven")||r.some(o=>o.endsWith(":disproven"));return{policyVersion:te,authority:r.length===0?"completion":s?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:r}}function Fe(e){return e.schemaVersion===m?e.index?.generationIdentity:e.facts.index?.generation.digest}function We(e){return e.schemaVersion===m?void 0:e.facts.workspaceInstance?.digest}function Ge(e){if(e.schemaVersion===m)return e.index?.alignment??"not-established";let t=e.stabilityProofs.filter(n=>n.source!=="process");return t.some(n=>n.kind==="invalidated")?"invalidated":t.length>0&&t.every(n=>n.kind==="immutable"||n.kind==="fixed-snapshot")?"fixed":t.some(n=>n.kind==="bracketed")?"bracketed":"not-established"}function Gt(e,t){let n=Ve(e),i=Ve(t);return[...new Set([...n.keys(),...i.keys()])].sort().map(s=>{let o=n.get(s),c=i.get(s),a=o?.subject??c?.subject??s,d=o?.identity.projection.name??c?.identity.projection.name??s;return{subject:a,projection:d,judgment:O(o?.identity,c?.identity)}})}function Ve(e){return e.schemaVersion!==C?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function Bt(e,t){return e.schemaVersion===m&&t.schemaVersion===m?Jt(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===m||t.schemaVersion===m?v("unknown",["legacy-fact-not-comparable"],De(e),De(t)):O(e.facts.index?.generation,t.facts.index?.generation)}function Jt(e,t){let n=e?[{kind:"legacy-index-generation",value:e}]:[],i=t?[{kind:"legacy-index-generation",value:t}]:[];return e===void 0||t===void 0?Be(n,i):v(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,i)}function O(e,t){let n=e?[{kind:"identity",identity:e}]:[],i=t?[{kind:"identity",identity:t}]:[];return!e||!t?Be(n,i):re(e,t)?v(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,i):v("unknown",["identity-projections-not-comparable"],n,i)}function Ut(e,t){if(e.schemaVersion===m||t.schemaVersion===m)return v("unknown",["legacy-fact-not-comparable"],[],[]);let n=$e(e),i=$e(t),r=Me(e),s=Me(t);return r==="invalidated"||s==="invalidated"?v("disproven",[...r==="invalidated"?["left-observation-invalidated"]:[],...s==="invalidated"?["right-observation-invalidated"]:[]],n,i):r!=="fixed"||s!=="fixed"?v("unknown",[...r==="no-repository-source"?["left-observation-has-no-repository-source"]:r!=="fixed"?["left-observation-not-fixed"]:[],...s==="no-repository-source"?["right-observation-has-no-repository-source"]:s!=="fixed"?["right-observation-not-fixed"]:[]],n,i):v("established",["all-observed-sources-fixed"],n,i)}function Me(e){let t=e.observedSources.filter(i=>i.kind!=="process");if(t.length===0)return"no-repository-source";let n=new Map(e.stabilityProofs.map(i=>[i.source,i.kind]));return t.some(i=>n.get(i.kind)==="invalidated")?"invalidated":t.every(i=>{let r=n.get(i.kind);return r==="immutable"||r==="fixed-snapshot"})?"fixed":"unknown"}function qt(e){if(e.schemaVersion!==C)return e.index?"unknown":"not-applicable";if(!e.observedSources.some(i=>i.kind==="index-generation"))return"not-applicable";let t=e.facts.index?.inputs;if(!t)return"unknown";let n=(e.facts.relevantInputs??[]).find(i=>re(i.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function y(e,t){return e.schemaVersion===C?t(e):void 0}function De(e){return e.schemaVersion===m&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===C&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function $e(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function Be(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return v("unknown",[n],e,t)}function v(e,t,n,i){return{state:e,reasons:t,facts:{left:n,right:i}}}function re(e,t){return e.schemaVersion===t.schemaVersion&&e.canonicalizationVersion===t.canonicalizationVersion&&e.hashAlgorithm===t.hashAlgorithm&&e.projection.name===t.projection.name&&e.projection.version===t.projection.version}function Yt(e){if(!l(e))return!1;let t=e.index,n=e.worktree;return Ue(e.observedAt)&&h(e.projectIdentity)&&tn(e.authorityKind)&&(t===void 0||l(t)&&h(t.generationIdentity)&&(t.source==="immutable"||t.source==="legacy")&&(t.alignment==="not-certified"||t.alignment==="leased"))&&(n===void 0||l(n)&&h(n.identity)&&typeof n.clean=="boolean"&&(n.headCommit===void 0||h(n.headCommit))&&(n.treeOid===void 0||h(n.treeOid)))&&en(e.authorityKind,t,n)}function Ht(e){if(!l(e))return!1;let t=e.facts,n=e.observedSources,i=e.stabilityProofs;if(!Ue(e.observedAt)||!l(t)||!Array.isArray(n)||n.length===0||!n.every(Qt)||!ee(n,a=>a.kind)||!Array.isArray(i)||!i.every(zt)||!ee(i,a=>a.source)||i.some(a=>!n.some(d=>d.kind===a.source))||!i.every(a=>Zt(a,t))||["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(a=>t[a]!==void 0&&!R(t[a])))return!1;let s=t.relevantInputs;if(s!==void 0&&(!Array.isArray(s)||!s.every(Kt)||!ee(s,a=>`${a.subject}\0${a.identity.projection.name}`)))return!1;let o=t.index;if(o!==void 0&&(!l(o)||!R(o.generation)||o.inputs!==void 0&&!R(o.inputs)||o.source!=="immutable"&&o.source!=="legacy"))return!1;let c=e.diagnostics;return(c===void 0||l(c)&&(c.clean===void 0||typeof c.clean=="boolean")&&(c.headCommit===void 0||h(c.headCommit))&&(c.treeOid===void 0||h(c.treeOid)))&&Xt(t,n)}function R(e){return!l(e)||!l(e.projection)?!1:e.schemaVersion===W&&e.canonicalizationVersion===N&&e.hashAlgorithm===A&&h(e.projection.name)&&qe(e.projection.version)&&typeof e.digest=="string"&&/^[a-f0-9]{64}$/u.test(e.digest)}function Kt(e){return l(e)&&h(e.subject)&&R(e.identity)}function Qt(e){return l(e)&&Je(e.kind)&&(e.identity===void 0||R(e.identity))}function zt(e){return l(e)&&Je(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function Xt(e,t){let n=e.index,i=t.find(a=>a.kind==="index-generation");if(i){if(!l(n)||!R(n.generation)||i.identity&&!Z(i.identity,n.generation))return!1}else if(n!==void 0)return!1;let r=e.workspaceInstance,s=t.find(a=>a.kind==="live-workspace");if(s?.identity&&(!R(r)||!Z(s.identity,r)))return!1;let o=e.wholeContent,c=t.find(a=>a.kind==="repository-snapshot");return!(c?.identity&&(!R(o)||!Z(c.identity,o)))}function Zt(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&l(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function Z(e,t){return re(e,t)&&e.digest===t.digest}function en(e,t,n){return e==="index-worktree"?t!==void 0&&n!==void 0:e==="index-only"?t!==void 0&&n===void 0:e==="worktree-only"?t===void 0&&n!==void 0:e==="process-local"&&t===void 0&&n===void 0}function tn(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function Je(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function Ue(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function qe(e){return Number.isSafeInteger(e)&&e>0}function ee(e,t){return new Set(e.map(t)).size===e.length}import{createHash as Ye}from"crypto";import{closeSync as nn,fstatSync as He,openSync as rn,rmSync as on}from"fs";import{dirname as sn}from"path";var an=2e3,cn=10,dn=3,U=class extends Error{constructor(n,i,r){super(`Concurrent edit detected for ${n}; expected revision ${Qe(i)}, but found ${Qe(r)}. The latest file was left untouched.`);this.path=n;this.original=i;this.latest=r;this.name="FileRevisionConflictError"}path;original;latest};function ze(e,t,n={}){let i=ln(e,n.lockTimeoutMs??an,n.monotonicNow??$);try{let r=Math.max(0,Math.floor(n.maxRetries??dn));for(let s=0;;s+=1){let o=J(e),c=t(o,s);if(c.kind==="unchanged")return{changed:!1,attempts:s+1,previous:o,current:o};n.onBeforeCommit?.({attempt:s,snapshot:o,mutation:c});let a=J(e);if(!pn(o.revision,a.revision)){if(s<r)continue;throw new U(e,o.revision,a.revision)}try{un(e,c,o.revision)}catch(d){if(d.code==="EEXIST"){let p=J(e);if(s<r)continue;throw new U(e,o.revision,p.revision)}throw d}return{changed:!0,attempts:s+1,previous:o,current:J(e)}}}finally{i.release()}}function J(e){for(let t=0;t<4;t+=1){let n;try{n=rn(e,"r");let i=Ke(He(n)),r=Ce(n,{maxBytes:ve,inputKind:"revisioned text file"}),s=Ke(He(n));if(!Xe(i,s))continue;return{path:e,text:r,revision:{exists:!0,hash:Ye("sha256").update(r).digest("hex"),identity:s}}}catch(i){if(i.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:Ye("sha256").update("").digest("hex")}};throw i}finally{n!==void 0&&nn(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function ln(e,t,n){let i=`${e}.codebaseiq-write.lock`,r=n()+Math.max(0,t);for(;;){let s=Oe(i,{kind:"revisioned-file-mutation",detail:{target:e}});if(s.kind==="acquired")return s.lock;if(n()>=r)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,cn)}}function un(e,t,n){if(t.kind==="delete"){if(!n.exists)return;on(e),xe(sn(e));return}let i=t.mode??n.identity?.mode;n.exists?Ie(e,t.text,{durability:"durable",mode:i}):Ee(e,t.text,{durability:"durable",mode:i})}function pn(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&Xe(e.identity,t.identity))}function Ke(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function Xe(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function Qe(e){return e.exists?e.hash.slice(0,12):"<absent>"}var j=".codebaseiq.json",tt=2e3,nt=5e3,oe=nt,se=3*6e4,hn=60*6e4,ae={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},gn={enabled:!1,debounceMs:tt,cooldownMs:oe,gitPollMs:2e3,idleTimeoutMs:se,autoRefresh:!0,ignore:[],resourceBudget:ae};var Wi=new Set(_);function q(e){let t=et(e,j);if(!fn(t))return{};let n;try{n=Re(t,{maxBytes:be,inputKind:"codebaseiq project config"})}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(`unable to read ${j} at ${t}: ${r}`,{cause:i})}return rt(X(n),t,"read").config}function it(e){return{...gn,...e.watch,idleTimeoutMs:e.watch?.idleTimeoutMs??(e.daemon?.enabled===!0?hn:se),cooldownMs:Math.max(nt,e.watch?.cooldownMs??oe),resourceBudget:{...ae,...e.watch?.resourceBudget}}}function yn(e,t){return bn(e,t).configPath}function bn(e,t){let n=et(e,j),i=mn(),r={collaborationDomainId:i,languages:t,watch:{enabled:!0,debounceMs:tt,cooldownMs:oe,gitPollMs:2e3,idleTimeoutMs:se,autoRefresh:!0,resourceBudget:{...ae}}},s=ze(n,o=>{if(!o.revision.exists)return{kind:"write",text:Ze(r)};let c=vn(o,r);return c.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:Ze({...c.config,collaborationDomainId:i})}});return{configPath:n,changed:s.changed}}function vn(e,t){if(!e.revision.exists)return{config:F(t),needsMigration:!0};let n=rt(X(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function Ze(e){return je(e)}function rt(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let r=n==="read"?`invalid ${j} at ${t}: ${e.reason}`:`Cannot update ${t}: the latest project config is ${e.reason}.`;throw new Error(`${r} The file was left untouched.`)}let i=n==="read"?`invalid ${j} at ${t}`:`Cannot update ${t}: the latest project config is invalid`;throw new Error(`${i} (unsupported ${e.direction} schemaVersion ${e.schemaVersion}; this codebaseiq reads legacy v${S} and current v${I}). Upgrade codebaseiq before retrying; the file was left untouched.`)}import{statSync as ot}from"fs";import{basename as Rn,isAbsolute as Cn,join as V,relative as Sn}from"path";import{fileURLToPath as On}from"url";import{watch as xn}from"chokidar";import In from"ignore";var pt=5e3,de=class{projectRoot;config;watchConfig;outputDb;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;budgetInspector;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;budgetTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;observationEpoch=0;changeSequence=0;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=it(t.config),this.outputDb=t.outputDb??V(we(this.projectRoot,t.config),"index.db"),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onReindexError=t.onReindexError??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{});let n=t.onError??(i=>console.error(i.message));this.onError=i=>{this.observationEpoch+=1,n(i)},this.clock=t.clock??Tn,ft.set(this,Mn(t.stopTimeoutMs??pt,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??gt(),this.subscriptionFactory=t.subscriptionFactory??_n,this.budgetInspector=t.budgetInspector??Ne,mt.set(this,{gitReader:t.gitReader??ke,languages:yt(t.languages??t.config.languages),stagedIndexEntries:null,gitSignalPaths:null,lastGitSignal:null}),this.gitignoreFilter=Te(t.projectRoot),this.extraIgnore=In(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,Y(this).errors=[],this.sourcePollingFallbackStarted=!1,this.observationEpoch+=1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let t=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.clearGitPollTimer();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...Y(this).closures],r=wn(this),s=this.clock.now()+r;return this.stopPromise=this.finishStop(t,i,n,s,r).catch(o=>{throw this.stopInProgress=!1,o}),this.stopPromise}observation(){return{epoch:this.observationEpoch,changeSequence:this.changeSequence}}requestRefresh(t,n={}){if(!this.stopped){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"||this.status.state==="budget-paused"){this.scheduleReindex(t);return}this.pendingTrigger=ct(this.pendingTrigger,t),this.changedFiles+=1,this.changeSequence+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(i,r)=>this.isIgnoredWatchPath(i,r?.isDirectory()??!1),usePolling:t,...t?{interval:500,binaryInterval:1e3}:{}});n.on("all",(i,r)=>{!this.stopped&&i!=="addDir"&&i!=="unlinkDir"&&this.handleFileChange(r)}),n.on("error",i=>this.handleSourceWatcherError(n,i,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,i){if(i||this.sourcePollingFallbackStarted||!Vn(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.observationEpoch+=1,this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(r=>r!==t),kn(Y(this),t,r=>this.onError(r));try{this.startSourceWatcher(!0)}catch(r){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(r)}`))}}isIgnoredWatchPath(t,n){let i=this.relativeWatchPath(t);if(!i)return!1;let r=n?`${i}/`:i;return r===".git/"||r.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)}handleFileChange(t){let n=this.relativeWatchPath(t);!n||n===".."||n.startsWith("../")||n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||n.endsWith("index.db")||n.endsWith("index.scip")||n.endsWith("index.db.tmp")||Rn(n).startsWith(Ae)||(n===".codebaseiq.json"&&dt(this,this.projectRoot),lt(this,n)&&this.scheduleReindex({kind:"watch-source",detail:n}))}relativeWatchPath(t){let n=Cn(t)?t:V(this.projectRoot,t);return Sn(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=ct(this.pendingTrigger,t),this.changedFiles++,this.changeSequence+=1,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}if(this.status.state==="budget-paused"){this.dirty=!0,this.setStatus({...this.status,dirty:!0});return}this.clearDebounceTimer();let n=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=this.inspectBudget();if(t.state==="paused"){this.dirty=!0;let o=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:o,dirty:!0,reason:t.detail,rebuilt:t.rebuilt,estimatedWriteBytes:t.estimatedWriteBytes}),this.clearBudgetTimer(),this.budgetTimer=this.clock.setTimeout(()=>{this.budgetTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},Math.min(2147483647,Math.max(1,o-this.wallNow())));return}let n=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&n<this.watchConfig.cooldownMs){let o=this.watchConfig.cooldownMs-n;this.dirty=!0;let c=this.wallNow()+o;this.setStatus({state:"cooldown",until:c,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},o);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let i=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=this.wallNow();this.setStatus({state:"indexing",startedAt:r});let s=this.reindexRunner.start(this.reindexRequest(i));this.activeOperation=s,s.completion.then(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let c=!1;try{c=this.onReindexComplete(o,i)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(c){let d=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(d),this.setStatus({state:"idle"});return}let a=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let c=o instanceof Error?o:new Error(String(o));this.onReindexError(c,i),this.onError(c),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===s&&(this.activeOperation=null)})}async finishStop(t,n,i,r,s){let o=[],c=t.map(async f=>{try{await f.close()}catch(D){o.push(`watch subscription close failed: ${String(D)}`)}});c.push(...n),i&&c.push((async()=>{try{let f=await i.cancel();f.state==="degraded"&&o.push(f.reason)}catch(f){o.push(`reindex cancellation failed: ${f instanceof Error?f.message:String(f)}`)}})());let a=c.length,d=c.map(f=>f.finally(()=>{a-=1})),p=await En(d,r,this.clock),u=Y(this);return o.push(...u.errors),u.errors=[],p?this.stopInProgress=!1:(o.push(`watch shutdown exceeded the ${s}ms deadline with ${a} operation(s) still pending`),Promise.all(d).then(()=>{this.stopInProgress=!1})),o.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:o.join("; ")}),{state:"degraded",reasons:o}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}inspectBudget(){try{return this.budgetInspector(this.outputDb,this.watchConfig.resourceBudget,new Date(this.wallNow()))}catch(t){return{state:"paused",reason:"activity-evidence",until:this.wallNow()+this.watchConfig.resourceBudget.windowMs,rebuilt:0,estimatedWriteBytes:0,detail:`reindex activity evidence could not be read: ${t instanceof Error?t.message:String(t)}`}}}reindexRequest(t){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:t}}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}clearBudgetTimer(){this.budgetTimer&&(this.clock.clearTimeout(this.budgetTimer),this.budgetTimer=null)}startGitStatePolling(){if(this.lastGitState=this.readGitState(),!this.lastGitState)return;let t=b(this);t.gitSignalPaths=this.resolveGitSignalPaths(),t.lastGitSignal=this.gitActivitySignal(),t.stagedIndexEntries=ut(this.projectRoot,t.gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.()}resolveGitSignalPaths(){let t=b(this).gitReader,n=P(this.projectRoot,["rev-parse","--git-dir"],t),i=P(this.projectRoot,["rev-parse","--git-common-dir"],t);if(!n)return null;let r=L(this.projectRoot,n),s=i?L(this.projectRoot,i):r,o=this.lastGitState?.indexPath;return[V(r,"HEAD"),V(s,"packed-refs"),V(s,"refs","heads"),...o?[o]:[]]}gitActivitySignal(){let t=b(this).gitSignalPaths;if(!t)return null;let n="";for(let i of t)try{let r=ot(i);n+=`${i}:${r.mtimeMs}:${r.size};`}catch{n+=`${i}:absent;`}return n}pollGitState(){let t=this.gitActivitySignal();if(t!==null){if(t===b(this).lastGitSignal)return;b(this).lastGitSignal=t}let n=this.lastGitState,i=this.readGitState();if(!n||!i||this.stopped){this.lastGitState=i;return}this.lastGitState=i;let r=n.head!==i.head,s=n.indexPath!==i.indexPath||n.indexMtimeMs!==i.indexMtimeMs||n.indexSize!==i.indexSize;if(!r&&!s)return;let o=b(this),c=o.stagedIndexEntries,a=ut(this.projectRoot,o.gitReader);o.stagedIndexEntries=a;let d=Dn(this.projectRoot,o.gitReader,n,i,c,a,r,s),p=null;d!==null&&(d.includes(".codebaseiq.json")&&dt(this,this.projectRoot),p=d.filter(u=>lt(this,u)),p.length===0)||(r&&s?this.scheduleReindex({kind:"watch-git-state",detail:ce("HEAD and index changed",p)}):r?this.scheduleReindex({kind:"watch-git-head",detail:ce("HEAD changed",p)}):s&&this.scheduleReindex({kind:"watch-git-index",detail:ce(i.indexPath??"index changed",p)}))}readGitState(){let t=b(this).gitReader,n=P(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let i=L(this.projectRoot,n),r={head:P(this.projectRoot,["rev-parse","--verify","HEAD"],t),indexPath:i};try{let s=ot(i);r.indexMtimeMs=s.mtimeMs,r.indexSize=s.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function En(e,t,n){if(e.length===0)return!0;let i=Promise.all(e).then(()=>!0),r=Math.max(0,t-n.now()),s=null,o=new Promise(a=>{s=n.setTimeout(()=>a(!1),r)}),c=await Promise.race([i,o]);return c&&s&&n.clearTimeout(s),c}var st=new WeakMap,ft=new WeakMap,mt=new WeakMap;function Y(e){let t=st.get(e);if(t)return t;let n={closures:new Set,errors:[]};return st.set(e,n),n}function wn(e){return ft.get(e)??pt}function b(e){let t=mt.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function kn(e,t,n){let i=Promise.resolve().then(()=>t.close()).catch(r=>{let s=`watch subscription close failed during polling fallback: ${String(r)}`;e.errors.push(s),n(new Error(s))});e.closures.add(i),i.then(()=>e.closures.delete(i))}function ht(e,t=Se){let{projectRoot:n,config:i,languages:r,pnpmWorkspaces:s,typescriptProjectMode:o,typescriptProjects:c,clojureConfigPath:a,indexerConcurrency:d,trigger:p}=e,u=q(n),f=Object.keys(u).length>0?u:i,D=z(n,f),Q=f.indexer?.typescript,Vt=f.indexer?.clojure,ge=t(process.pid);if(!ge)throw new Error(`Could not establish watcher process identity for reindex worker ownership (pid ${process.pid}).`);return{workerPath:On(new URL("./reindex-worker.js",import.meta.url)),env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:n,SCIP_REINDEX_OUTPUT_SCIP:D.indexPath,SCIP_REINDEX_OUTPUT_DB:D.dbPath,SCIP_REINDEX_LANGUAGES:(f.languages??r)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(f.indexerConcurrency??d??""),SCIP_REINDEX_PNPM_WORKSPACES:Q?.pnpmWorkspaces??s?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:Q?.projectMode??o,projects:Q?.projects??c??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:Vt?.configPath??a??"",SCIP_REINDEX_TRIGGER_KIND:p.kind,SCIP_REINDEX_TRIGGER_DETAIL:p.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(ge)}}}var Tn={now:$,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},_n=(e,t)=>xn(e,t),Pn=15*6e4,An=1e3,Nn=64*1024;function jn(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function at(e,t){let n=e instanceof Error?e.message:String(e),i=t.stderrTail.trim()||t.stdoutTail.trim();return i?`${n}
3
- ${i}`:n}function gt(e={}){let t=e.timeoutMs??Pn,n=e.terminationGraceMs??An,i=e.maxOutputBytes??Nn,r=e.resolveLaunch??ht;return{start(s){let o=r(s),c=new AbortController,a=jn(),d=!1,p=Pe({command:process.execPath,args:[...process.execArgv,o.workerPath],label:"watch reindex worker",env:o.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:i,maxStderrBytes:i,outputLimitBehavior:"truncate-tail",signal:c.signal,detached:!0}).then(u=>{if(a={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0)throw new Error(at(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),a));return u.durationMs}).catch(u=>{throw u instanceof _e&&(a={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(at(u,a),{cause:u})}).finally(()=>{d=!0});return{completion:p,async cancel(){d||c.abort();try{await p}catch{}return{state:"exited",diagnostics:a}},diagnostics:()=>a}}}}function ct(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}function Vn(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function Mn(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function yt(e){return e&&e.length>0?[...e]:_}function dt(e,t){try{b(e).languages=yt(q(t).languages)}catch{b(e).languages=_}}function lt(e,t){return ye(t,b(e).languages)!=="other"}function Dn(e,t,n,i,r,s,o,c){let a=new Set;if(o){if(!n.head||!i.head)return null;let d=t.runResult(e,["diff","--name-only","-z","--no-renames","--relative",n.head,i.head,"--"]);if(d.kind!=="success")return null;for(let p of $n(d.output))a.add(p)}if(c){if(r===null||s===null)return null;for(let d of Fn(r,s))a.add(d)}return[...a].sort()}function ut(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?Ln(n.output):null}function $n(e){return e.split("\0").filter(t=>t.length>0)}function Ln(e){let t=e.split("\0");if(t.at(-1)===""&&t.pop(),t.length%2!==0)return null;let n=new Map;for(let i=0;i<t.length;i+=2){let r=t[i],s=t[i+1];if(!r.startsWith(":")||!s)return null;n.set(s,r)}return n}function Fn(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(i=>e.get(i)!==t.get(i))}function ce(e,t){return t===null?`${e}; changed paths unavailable`:t.length===0?e:t.length===1?t[0]:`${t.length} compiler inputs changed`}import{existsSync as le,mkdirSync as Wn,symlinkSync as Gn,readlinkSync as bt,unlinkSync as vt,readdirSync as Bn}from"fs";import{join as E,dirname as pe,resolve as w,relative as Jn,isAbsolute as Un}from"path";import{homedir as ue,platform as qn}from"os";import{fileURLToPath as Yn}from"url";var Hn=qn()==="win32",Rt=["codebaseiq","codebaseiq-explore","concrete-plan"];function Kn(e={}){let t=e.quiet?()=>{}:console.log,n=Yn(import.meta.url),i=w(pe(n),"..","skills"),r=[E(ue(),".claude","skills"),E(ue(),".codex","skills"),E(ue(),".agents","skills")],s={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let o of r){let c=pe(o);if(!le(c))continue;Wn(o,{recursive:!0});let a=Xn(o);Qn(o,i,a,s,t);for(let d of Rt){let p=E(i,d),u=E(o,d);if(!le(p)){s.skipped.push(`${a}/${d}`);continue}if(le(u)){try{let f=bt(u);if(w(f)===w(p)){s.alreadyLinked.push(`${a}/${d}`),t(` ok: ${d} \u2192 ${a} (already linked)`);continue}}catch{s.skipped.push(`${a}/${d}`),t(` skip: ${d} \u2192 ${a} (exists, not a symlink)`);continue}vt(u)}Gn(p,u,Hn?"junction":"dir"),s.installed.push(`${a}/${d}`),t(` done: ${d} \u2192 ${a}`)}}return s}function Qn(e,t,n,i,r){let s=new Set(Rt);for(let o of Bn(e)){if(s.has(o))continue;let c=E(e,o),a;try{a=w(pe(c),bt(c))}catch{continue}zn(a,t)&&(vt(c),i.pruned.push(`${n}/${o}`),r(` prune: ${o} \u2192 ${n} (removed stale codebaseiq skill link)`))}}function zn(e,t){let n=Jn(w(t),w(e));return n===""||!n.startsWith("..")&&!Un(n)}function Xn(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}var Ct=["repository-observation","repository-preview","mutation","composite","environment-observation","tool-information"];function Zn(e,t=[]){return{defaultRole:e,...t.length>0?{rules:t}:{}}}function ei(e,t){for(let n of e.rules??[]){if(n.when.kind==="option-present"){let r=t.options[n.when.name];if(r!==void 0&&r!==!1)return n.role;continue}if((n.when.kind==="argument"?t.args[n.when.index]:t.options[n.when.name])===n.when.equals)return n.role}return e.defaultRole}function ti(e){return[...new Set([e.defaultRole,...(e.rules??[]).map(t=>t.role)])]}function H(e){return Ct.includes(e)}function ni(e){return e==="repository-observation"||e==="repository-preview"||e==="composite"}var fe=1,me=1,K=["compiler-graph","semantic-analysis","repository-source","change-history","runtime-measurement","heuristic","mixed","unknown"],St=["complete","partial","unknown"],Ot=["validated","failed","not-evaluated","not-applicable"],xt=["observe","advise","require-adjudication","block","not-established"],It={policyId:"codebaseiq:unresolved-repository-policy",policyVersion:me,permission:"not-established",reasons:["No repository action policy was supplied for this claim."]};function ii(e){return{schemaVersion:fe,origin:e.contract.origin,coverage:Et(e.coverage),producerValidation:e.contract.producerValidation,stateAuthority:B(e.receipt,e.receipt),repositoryPolicy:e.repositoryPolicy??It,...e.contract.families?{families:e.contract.families}:{}}}function Et(e){return e?e.complete===!0?{state:"complete",returned:e.returned,totalKnown:!0,total:e.total??e.returned,omitted:0}:e.totalKnown?{state:"partial",returned:e.returned,totalKnown:!0,...e.total===void 0?{}:{total:e.total},...e.omitted===void 0?{}:{omitted:e.omitted}}:{state:"unknown",returned:e.returned,totalKnown:!1}:{state:"unknown",returned:0,totalKnown:!1}}function ri(e,t){let n=[];return M(n,"origin",t.origins,e.origin),M(n,"coverage",t.coverage,e.coverage.state),M(n,"producer-validation",t.producerValidation,e.producerValidation.status),M(n,"state-authority",t.stateAuthority,e.stateAuthority.authority),M(n,"action-permission",t.actionPermission,e.repositoryPolicy.permission),{satisfied:n.every(i=>i.satisfied),predicates:n}}function M(e,t,n,i){n&&e.push({predicate:t,satisfied:n.includes(i),required:n,actual:i})}function he(e){return!l(e)||e.schemaVersion!==fe||!k(e.origin,K)||!oi(e.coverage)||!si(e.producerValidation)||!ai(e.stateAuthority)||!ci(e.repositoryPolicy)?!1:e.families===void 0||di(e.families)}function oi(e){return!l(e)||!k(e.state,St)||!x(e.returned)||typeof e.totalKnown!="boolean"||e.total!==void 0&&!x(e.total)||e.omitted!==void 0&&!x(e.omitted)?!1:e.state==="complete"?e.totalKnown===!0&&e.total===e.returned&&e.omitted===0:e.state==="partial"?e.totalKnown===!0&&x(e.total)&&x(e.omitted)&&e.total===Number(e.returned)+Number(e.omitted):e.totalKnown===!1}function si(e){if(!l(e)||!k(e.status,Ot))return!1;let t=e.certification;return e.status==="validated"||e.status==="failed"?l(t)&&g(t.id)&&Number.isSafeInteger(t.version)&&Number(t.version)>0&&g(t.corpus):t===void 0}function ai(e){return l(e)&&Number.isSafeInteger(e.policyVersion)&&(e.authority==="completion"||e.authority==="advisory"||e.authority==="none")&&Array.isArray(e.requiredRelationships)&&e.requiredRelationships.every(g)&&Array.isArray(e.reasons)&&e.reasons.every(g)}function ci(e){return l(e)&&g(e.policyId)&&e.policyVersion===me&&k(e.permission,xt)&&Array.isArray(e.reasons)&&e.reasons.every(g)}function di(e){return Array.isArray(e)&&e.every(t=>l(t)&&g(t.id)&&g(t.selector)&&li(t.origin))}function li(e){return l(e)?e.kind==="fixed"?k(e.origin,K)&&e.origin!=="mixed":e.kind!=="result-field"||!g(e.field)||!l(e.values)?!1:Object.values(e.values).every(t=>k(t,K)&&t!=="mixed"):!1}function k(e,t){return typeof e=="string"&&t.includes(e)}var Tt="codebaseiq-result",_t=0,T=1,ui=1,Pt=1,At=1;function Nt(e){if(!l(e))return{kind:"malformed",reason:"CLI JSON output must be an object."};let t=Object.hasOwn(e,"kind"),n=Object.hasOwn(e,"schemaVersion");if(!t&&!n){let o=wt(e);return o?{kind:"malformed",reason:`Legacy CLI JSON envelope: ${o}`}:{kind:"legacy",schemaVersion:_t,envelope:e}}if(!t||!n)return{kind:"malformed",reason:"CLI JSON envelope must contain both kind and schemaVersion."};if(e.kind!==Tt)return{kind:"malformed",reason:`Unsupported CLI JSON envelope kind: ${gi(e.kind)}.`};let i=e.schemaVersion;if(!Number.isSafeInteger(i)||Number(i)<1)return{kind:"malformed",reason:"CLI JSON envelope schemaVersion must be a positive safe integer."};if(i!==T)return{kind:"unsupported",schemaVersion:Number(i),direction:Number(i)<T?"older":"future",...kt(e.producer)?{producer:e.producer}:{}};let r=wt(e);if(r)return{kind:"malformed",reason:`CLI JSON envelope v1: ${r}`};if(!kt(e.producer))return{kind:"malformed",reason:"CLI JSON envelope v1: producer must identify codebaseiq and its non-empty version."};if(!mi(e.resultSchemaVersion))return{kind:"malformed",reason:"CLI JSON envelope v1: resultSchemaVersion must be a positive safe integer."};let s=jt(e.command);return s.includes(e.resultSchemaVersion)?e.evidenceContext!==void 0&&!hi(e.evidenceContext)?{kind:"malformed",reason:"CLI JSON envelope v1: evidenceContext must contain a supported receipt and analysis manifest."}:e.operationRole!==void 0&&!H(e.operationRole)?{kind:"malformed",reason:"CLI JSON envelope v1: operationRole must be a supported command operation role."}:l(e.evidenceContext)&&e.operationRole!==void 0&&e.evidenceContext.operationRole!==void 0&&e.operationRole!==e.evidenceContext.operationRole?{kind:"malformed",reason:"CLI JSON envelope v1: top-level and evidence-context operation roles must agree."}:{kind:"supported",schemaVersion:T,envelope:e}:{kind:"unsupported-result",schemaVersion:T,command:e.command,resultSchemaVersion:e.resultSchemaVersion,supportedResultSchemaVersions:s}}function pi(e){let t=Nt(e);if(t.kind==="legacy"||t.kind==="supported")return t;if(t.kind==="unsupported"){let n=t.producer?` from ${t.producer.name}@${t.producer.version}`:"";throw new Error(`Unsupported codebaseiq CLI JSON schemaVersion ${t.schemaVersion}${n}; this consumer supports the legacy unversioned envelope and schemaVersion ${T}.`)}throw t.kind==="unsupported-result"?new Error(`Unsupported resultSchemaVersion ${t.resultSchemaVersion} for codebaseiq command ${JSON.stringify(t.command)}; this consumer supports ${t.supportedResultSchemaVersions.join(", ")}.`):new Error(`Malformed codebaseiq CLI JSON envelope: ${t.reason}`)}function jt(e){return fi[e]??[ui]}var fi={hotspots:[1,2],bottlenecks:[1,2],"complexity-hotspots":[1,2]};function wt(e){return typeof e.command!="string"||e.command.length===0?"command must be a non-empty string.":Array.isArray(e.args)?l(e.options)?Object.hasOwn(e,"result")?null:"result is required.":"options must be an object.":"args must be an array."}function kt(e){return l(e)&&e.name==="codebaseiq"&&typeof e.version=="string"&&e.version.length>0}function mi(e){return Number.isSafeInteger(e)&&Number(e)>0}function hi(e){if(!l(e)||e.schemaVersion!==Pt||e.operationRole!==void 0&&!H(e.operationRole)||!G(e.receipt))return!1;let t=e.analysisManifest;return l(t)&&t.schemaVersion===At&&(t.evidence===void 0||t.evidence==="graph-fact"||t.evidence==="heuristic"||t.evidence==="mixed")&&(t.claimQualification===void 0||he(t.claimQualification))}function gi(e){return typeof e=="string"?JSON.stringify(e):String(e)}export{xt as CLAIM_ACTION_PERMISSIONS,me as CLAIM_ACTION_POLICY_VERSION,St as CLAIM_COVERAGE_STATES,K as CLAIM_ORIGINS,fe as CLAIM_QUALIFICATION_SCHEMA_VERSION,At as CLI_ANALYSIS_MANIFEST_SCHEMA_VERSION,Pt as CLI_EVIDENCE_CONTEXT_SCHEMA_VERSION,Tt as CLI_JSON_ENVELOPE_KIND,Ct as COMMAND_OPERATION_ROLES,T as CURRENT_CLI_JSON_ENVELOPE_SCHEMA_VERSION,It as DEFAULT_REPOSITORY_POLICY_ACTION,_t as LEGACY_CLI_JSON_ENVELOPE_SCHEMA_VERSION,m as LEGACY_OBSERVATION_RECEIPT_SCHEMA_VERSION,N as OBSERVATION_IDENTITY_CANONICALIZATION_VERSION,A as OBSERVATION_IDENTITY_HASH_ALGORITHM,W as OBSERVATION_IDENTITY_SCHEMA_VERSION,C as OBSERVATION_RECEIPT_SCHEMA_VERSION,te as OBSERVATION_STATE_AUTHORITY_POLICY_VERSION,Ot as PRODUCER_VALIDATION_STATUSES,de as Watcher,Zn as commandOperation,ti as commandOperationRoles,ie as compareObservationReceipts,Le as createObservationIdentity,gt as createReindexRunner,Nt as decodeCliJsonEnvelope,ne as decodeObservationReceipt,Et as deriveClaimCoverage,ii as deriveClaimQualification,B as deriveObservationStateAuthority,ri as evaluateClaimQualification,Dt as getScipVersion,yn as initProjectConfig,Kn as installSkills,he as isClaimQualificationV1,H as isCommandOperationRole,G as isObservationReceipt,Mt as isScipInstalled,q as loadProjectConfig,Fe as observationReceiptGenerationIdentity,Ge as observationReceiptStabilityLabel,We as observationReceiptWorkspaceIdentity,ni as operationObservesRepository,$t as printScipInstallInstructions,pi as requireCompatibleCliJsonEnvelope,ei as resolveCommandOperationRole,z as resolveIndexStoragePaths,ht as resolveReindexWorkerLaunch,jt as supportedCliResultSchemaVersions};
1
+ import{b as _e,c as Pe,e as Vt,f as Dt,g as Ft,l as Ae,o as Ne}from"./chunk-7R64XY4Y.js";import{a as Te}from"./chunk-YIOQJ45A.js";import{c as Se,e as F,f as Oe,k as xe,l as Ee}from"./chunk-CANBLFVQ.js";import"./chunk-OANDYLJQ.js";import"./chunk-3LCDIREB.js";import{A as be,B as ve,G as Ce,I as Re,Q as Ie,T as we,Y as z,aa as ke,da as P,ea as L,i as ye,n as l,p as g,q as I,r as m,t as _}from"./chunk-327YK6TB.js";import{existsSync as fn,mkdirSync as Mi}from"fs";import{randomUUID as hn}from"crypto";import{dirname as Di,isAbsolute as Fi,join as et,relative as Li,resolve as $i}from"path";var S=1,x=2,Lt="./node_modules/codebaseiq/docs/schemas/project-config.schema.json";function X(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(c){return{kind:"malformed",reason:`invalid JSON: ${c instanceof Error?c.message:String(c)}`}}if(!l(t))return{kind:"malformed",reason:"project config must be a JSON object"};let n=t.schemaVersion;if(n!==void 0&&!Number.isInteger(n))return{kind:"malformed",reason:"schemaVersion must be an integer"};let i=n===void 0?S:n;if(i!==S&&i!==x)return{kind:"unsupported",schemaVersion:i,direction:i<S?"older":"future"};let r=t.$schema;if(r!==void 0&&(typeof r!="string"||r.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let s=$(t),o=i!==x||typeof t.$schema!="string";return i===S?{kind:"legacy",sourceVersion:S,config:s,needsMigration:o}:{kind:"supported",sourceVersion:x,config:s,needsMigration:o}}function $(e){let t=e,{$schema:n,schemaVersion:i,...r}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:Lt,schemaVersion:x,...r}}function Me(e){return`${JSON.stringify($(e),null,2)}
2
+ `}import{createHash as $t}from"crypto";var h=1,R=2,W=1,N=1,A="sha256",te=1;function Le(e,t,n){if(!m(e)||!qe(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:W,canonicalizationVersion:N,hashAlgorithm:A,projection:{name:e,version:t},digest:$t(A).update(Wt(e,t,n)).digest("hex")}}function Wt(e,t,n){return`{"canonicalizationVersion":${N},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function ne(e){if(!l(e))return{kind:"malformed",reason:"observation receipt must be an object"};let t=e.schemaVersion;if(!Number.isInteger(t))return{kind:"malformed",reason:"observation receipt schemaVersion must be an integer"};if(t===h)return Yt(e)?{kind:"legacy",schemaVersion:h,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===R)return Kt(e)?{kind:"supported",schemaVersion:R,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<h?"older":"future"}}function B(e){let t=ne(e);return t.kind==="legacy"||t.kind==="supported"}function ie(e,t){return{collaborationDomain:O(y(e,n=>n.facts.collaborationDomain),y(t,n=>n.facts.collaborationDomain)),repositoryLineage:O(y(e,n=>n.facts.repositoryLineage),y(t,n=>n.facts.repositoryLineage)),workspaceInstance:O(y(e,n=>n.facts.workspaceInstance),y(t,n=>n.facts.workspaceInstance)),wholeContent:O(y(e,n=>n.facts.wholeContent),y(t,n=>n.facts.wholeContent)),relevantInputs:Bt(e,t),indexInput:O(y(e,n=>n.facts.index?.inputs),y(t,n=>n.facts.index?.inputs)),indexGeneration:Gt(e,t),observationStability:Jt(e,t)}}function G(e,t,n=ie(e,t)){let i=[["collaborationDomain",n.collaborationDomain],["wholeContent",n.wholeContent],["observationStability",n.observationStability]],r=[];for(let[o,c]of i)c.state!=="established"&&r.push(`${o}:${c.state}`);for(let[o,c]of[["left",e],["right",t]]){let a=qt(c);a!=="not-applicable"&&a!=="established"&&r.push(`${o}IndexAlignment:${a}`)}let s=i.some(([,o])=>o.state==="disproven")||r.some(o=>o.endsWith(":disproven"));return{policyVersion:te,authority:r.length===0?"completion":s?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:r}}function $e(e){return e.schemaVersion===h?e.index?.generationIdentity:e.facts.index?.generation.digest}function We(e){return e.schemaVersion===h?void 0:e.facts.workspaceInstance?.digest}function Be(e){if(e.schemaVersion===h)return e.index?.alignment??"not-established";let t=e.stabilityProofs.filter(n=>n.source!=="process");return t.some(n=>n.kind==="invalidated")?"invalidated":t.length>0&&t.every(n=>n.kind==="immutable"||n.kind==="fixed-snapshot")?"fixed":t.some(n=>n.kind==="bracketed")?"bracketed":"not-established"}function Bt(e,t){let n=je(e),i=je(t);return[...new Set([...n.keys(),...i.keys()])].sort().map(s=>{let o=n.get(s),c=i.get(s),a=o?.subject??c?.subject??s,d=o?.identity.projection.name??c?.identity.projection.name??s;return{subject:a,projection:d,judgment:O(o?.identity,c?.identity)}})}function je(e){return e.schemaVersion!==R?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function Gt(e,t){return e.schemaVersion===h&&t.schemaVersion===h?Ut(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===h||t.schemaVersion===h?v("unknown",["legacy-fact-not-comparable"],De(e),De(t)):O(e.facts.index?.generation,t.facts.index?.generation)}function Ut(e,t){let n=e?[{kind:"legacy-index-generation",value:e}]:[],i=t?[{kind:"legacy-index-generation",value:t}]:[];return e===void 0||t===void 0?Ge(n,i):v(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,i)}function O(e,t){let n=e?[{kind:"identity",identity:e}]:[],i=t?[{kind:"identity",identity:t}]:[];return!e||!t?Ge(n,i):re(e,t)?v(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,i):v("unknown",["identity-projections-not-comparable"],n,i)}function Jt(e,t){if(e.schemaVersion===h||t.schemaVersion===h)return v("unknown",["legacy-fact-not-comparable"],[],[]);let n=Fe(e),i=Fe(t),r=Ve(e),s=Ve(t);return r==="invalidated"||s==="invalidated"?v("disproven",[...r==="invalidated"?["left-observation-invalidated"]:[],...s==="invalidated"?["right-observation-invalidated"]:[]],n,i):r!=="fixed"||s!=="fixed"?v("unknown",[...r==="no-repository-source"?["left-observation-has-no-repository-source"]:r!=="fixed"?["left-observation-not-fixed"]:[],...s==="no-repository-source"?["right-observation-has-no-repository-source"]:s!=="fixed"?["right-observation-not-fixed"]:[]],n,i):v("established",["all-observed-sources-fixed"],n,i)}function Ve(e){let t=e.observedSources.filter(i=>i.kind!=="process");if(t.length===0)return"no-repository-source";let n=new Map(e.stabilityProofs.map(i=>[i.source,i.kind]));return t.some(i=>n.get(i.kind)==="invalidated")?"invalidated":t.every(i=>{let r=n.get(i.kind);return r==="immutable"||r==="fixed-snapshot"})?"fixed":"unknown"}function qt(e){if(e.schemaVersion!==R)return e.index?"unknown":"not-applicable";if(!e.observedSources.some(i=>i.kind==="index-generation"))return"not-applicable";let t=e.facts.index?.inputs;if(!t)return"unknown";let n=(e.facts.relevantInputs??[]).find(i=>re(i.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function y(e,t){return e.schemaVersion===R?t(e):void 0}function De(e){return e.schemaVersion===h&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===R&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function Fe(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function Ge(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return v("unknown",[n],e,t)}function v(e,t,n,i){return{state:e,reasons:t,facts:{left:n,right:i}}}function re(e,t){return e.schemaVersion===t.schemaVersion&&e.canonicalizationVersion===t.canonicalizationVersion&&e.hashAlgorithm===t.hashAlgorithm&&e.projection.name===t.projection.name&&e.projection.version===t.projection.version}function Yt(e){if(!l(e))return!1;let t=e.index,n=e.worktree;return Je(e.observedAt)&&m(e.projectIdentity)&&tn(e.authorityKind)&&(t===void 0||l(t)&&m(t.generationIdentity)&&(t.source==="immutable"||t.source==="legacy")&&(t.alignment==="not-certified"||t.alignment==="leased"))&&(n===void 0||l(n)&&m(n.identity)&&typeof n.clean=="boolean"&&(n.headCommit===void 0||m(n.headCommit))&&(n.treeOid===void 0||m(n.treeOid)))&&en(e.authorityKind,t,n)}function Kt(e){if(!l(e))return!1;let t=e.facts,n=e.observedSources,i=e.stabilityProofs;if(!Je(e.observedAt)||!l(t)||!Array.isArray(n)||n.length===0||!n.every(Qt)||!ee(n,a=>a.kind)||!Array.isArray(i)||!i.every(zt)||!ee(i,a=>a.source)||i.some(a=>!n.some(d=>d.kind===a.source))||!i.every(a=>Zt(a,t))||["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(a=>t[a]!==void 0&&!C(t[a])))return!1;let s=t.relevantInputs;if(s!==void 0&&(!Array.isArray(s)||!s.every(Ht)||!ee(s,a=>`${a.subject}\0${a.identity.projection.name}`)))return!1;let o=t.index;if(o!==void 0&&(!l(o)||!C(o.generation)||o.inputs!==void 0&&!C(o.inputs)||o.source!=="immutable"&&o.source!=="legacy"))return!1;let c=e.diagnostics;return(c===void 0||l(c)&&(c.clean===void 0||typeof c.clean=="boolean")&&(c.headCommit===void 0||m(c.headCommit))&&(c.treeOid===void 0||m(c.treeOid)))&&Xt(t,n)}function C(e){return!l(e)||!l(e.projection)?!1:e.schemaVersion===W&&e.canonicalizationVersion===N&&e.hashAlgorithm===A&&m(e.projection.name)&&qe(e.projection.version)&&typeof e.digest=="string"&&/^[a-f0-9]{64}$/u.test(e.digest)}function Ht(e){return l(e)&&m(e.subject)&&C(e.identity)}function Qt(e){return l(e)&&Ue(e.kind)&&(e.identity===void 0||C(e.identity))}function zt(e){return l(e)&&Ue(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function Xt(e,t){let n=e.index,i=t.find(a=>a.kind==="index-generation");if(i){if(!l(n)||!C(n.generation)||i.identity&&!Z(i.identity,n.generation))return!1}else if(n!==void 0)return!1;let r=e.workspaceInstance,s=t.find(a=>a.kind==="live-workspace");if(s?.identity&&(!C(r)||!Z(s.identity,r)))return!1;let o=e.wholeContent,c=t.find(a=>a.kind==="repository-snapshot");return!(c?.identity&&(!C(o)||!Z(c.identity,o)))}function Zt(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&l(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function Z(e,t){return re(e,t)&&e.digest===t.digest}function en(e,t,n){return e==="index-worktree"?t!==void 0&&n!==void 0:e==="index-only"?t!==void 0&&n===void 0:e==="worktree-only"?t===void 0&&n!==void 0:e==="process-local"&&t===void 0&&n===void 0}function tn(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function Ue(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function Je(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function qe(e){return Number.isSafeInteger(e)&&e>0}function ee(e,t){return new Set(e.map(t)).size===e.length}import{createHash as Ye}from"crypto";import{closeSync as nn,fstatSync as Ke,openSync as rn,rmSync as on}from"fs";import{dirname as sn}from"path";var an=2e3,cn=10,dn=3,J=class extends Error{constructor(n,i,r){super(`Concurrent edit detected for ${n}; expected revision ${Qe(i)}, but found ${Qe(r)}. The latest file was left untouched.`);this.path=n;this.original=i;this.latest=r;this.name="FileRevisionConflictError"}path;original;latest};function ze(e,t,n={}){let i=ln(e,n.lockTimeoutMs??an,n.monotonicNow??F);try{let r=Math.max(0,Math.floor(n.maxRetries??dn));for(let s=0;;s+=1){let o=U(e),c=t(o,s);if(c.kind==="unchanged")return{changed:!1,attempts:s+1,previous:o,current:o};n.onBeforeCommit?.({attempt:s,snapshot:o,mutation:c});let a=U(e);if(!pn(o.revision,a.revision)){if(s<r)continue;throw new J(e,o.revision,a.revision)}try{un(e,c,o.revision)}catch(d){if(d.code==="EEXIST"){let p=U(e);if(s<r)continue;throw new J(e,o.revision,p.revision)}throw d}return{changed:!0,attempts:s+1,previous:o,current:U(e)}}}finally{i.release()}}function U(e){for(let t=0;t<4;t+=1){let n;try{n=rn(e,"r");let i=He(Ke(n)),r=Re(n,{maxBytes:ve,inputKind:"revisioned text file"}),s=He(Ke(n));if(!Xe(i,s))continue;return{path:e,text:r,revision:{exists:!0,hash:Ye("sha256").update(r).digest("hex"),identity:s}}}catch(i){if(i.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:Ye("sha256").update("").digest("hex")}};throw i}finally{n!==void 0&&nn(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function ln(e,t,n){let i=`${e}.codebaseiq-write.lock`,r=n()+Math.max(0,t);for(;;){let s=Oe(i,{kind:"revisioned-file-mutation",detail:{target:e}});if(s.kind==="acquired")return s.lock;if(n()>=r)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,cn)}}function un(e,t,n){if(t.kind==="delete"){if(!n.exists)return;on(e),Ie(sn(e));return}let i=t.mode??n.identity?.mode;n.exists?xe(e,t.text,{durability:"durable",mode:i}):Ee(e,t.text,{durability:"durable",mode:i})}function pn(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&Xe(e.identity,t.identity))}function He(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function Xe(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function Qe(e){return e.exists?e.hash.slice(0,12):"<absent>"}var M=".codebaseiq.json";var tt=2e3,nt=5e3,oe=nt,se=3*6e4,mn=60*6e4,ae={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},gn={enabled:!1,debounceMs:tt,cooldownMs:oe,gitPollMs:2e3,idleTimeoutMs:se,autoRefresh:!0,ignore:[],resourceBudget:ae};var Ji=new Set(_);function q(e){let t=et(e,M);if(!fn(t))return{};let n;try{n=Ce(t,{maxBytes:be,inputKind:"codebaseiq project config"})}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(`unable to read ${M} at ${t}: ${r}`,{cause:i})}return rt(X(n),t,"read").config}function it(e){return{...gn,...e.watch,idleTimeoutMs:e.watch?.idleTimeoutMs??(e.daemon?.enabled===!0?mn:se),cooldownMs:Math.max(nt,e.watch?.cooldownMs??oe),resourceBudget:{...ae,...e.watch?.resourceBudget}}}function yn(e,t){return bn(e,t).configPath}function bn(e,t){let n=et(e,M),i=hn(),r={collaborationDomainId:i,languages:t,watch:{enabled:!0,debounceMs:tt,cooldownMs:oe,gitPollMs:2e3,idleTimeoutMs:se,autoRefresh:!0,resourceBudget:{...ae}}},s=ze(n,o=>{if(!o.revision.exists)return{kind:"write",text:Ze(r)};let c=vn(o,r);return c.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:Ze({...c.config,collaborationDomainId:i})}});return{configPath:n,changed:s.changed}}function vn(e,t){if(!e.revision.exists)return{config:$(t),needsMigration:!0};let n=rt(X(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function Ze(e){return Me(e)}function rt(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let r=n==="read"?`invalid ${M} at ${t}: ${e.reason}`:`Cannot update ${t}: the latest project config is ${e.reason}.`;throw new Error(`${r} The file was left untouched.`)}let i=n==="read"?`invalid ${M} at ${t}`:`Cannot update ${t}: the latest project config is invalid`;throw new Error(`${i} (unsupported ${e.direction} schemaVersion ${e.schemaVersion}; this codebaseiq reads legacy v${S} and current v${x}). Upgrade codebaseiq before retrying; the file was left untouched.`)}import{statSync as ot}from"fs";import{basename as Cn,isAbsolute as Rn,join as j,relative as Sn}from"path";import{fileURLToPath as On}from"url";import{watch as In}from"chokidar";import xn from"ignore";var pt=5e3,de=class{projectRoot;config;watchConfig;outputDb;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onFileChanged;onBulkChange;onError;reindexRunner;subscriptionFactory;budgetInspector;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;budgetTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fileChangeTimer=null;pendingFileChanges=new Set;bulkChangePending=!1;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;observationEpoch=0;changeSequence=0;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=it(t.config),this.outputDb=t.outputDb??j(we(this.projectRoot,t.config),"index.db"),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onReindexError=t.onReindexError??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onFileChanged=t.onFileChanged,this.onBulkChange=t.onBulkChange;let n=t.onError??(i=>console.error(i.message));this.onError=i=>{this.observationEpoch+=1,n(i)},this.clock=t.clock??Tn,ft.set(this,Fn(t.stopTimeoutMs??pt,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??gt(),this.subscriptionFactory=t.subscriptionFactory??_n,this.budgetInspector=t.budgetInspector??Ne,ht.set(this,{gitReader:t.gitReader??ke,languages:yt(t.languages??t.config.languages),stagedIndexEntries:null,gitSignalPaths:null,lastGitSignal:null}),this.gitignoreFilter=Te(t.projectRoot),this.extraIgnore=xn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,Y(this).errors=[],this.sourcePollingFallbackStarted=!1,this.observationEpoch+=1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let t=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.clearGitPollTimer(),this.clearFileChangeWindow();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...Y(this).closures],r=wn(this),s=this.clock.now()+r;return this.stopPromise=this.finishStop(t,i,n,s,r).catch(o=>{throw this.stopInProgress=!1,o}),this.stopPromise}observation(){return{epoch:this.observationEpoch,changeSequence:this.changeSequence}}requestRefresh(t,n={}){if(!this.stopped){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"||this.status.state==="budget-paused"){this.scheduleReindex(t);return}this.pendingTrigger=ct(this.pendingTrigger,t),this.changedFiles+=1,this.changeSequence+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(i,r)=>this.isIgnoredWatchPath(i,r?.isDirectory()??!1),usePolling:t,...t?{interval:500,binaryInterval:1e3}:{}});n.on("all",(i,r)=>{!this.stopped&&i!=="addDir"&&i!=="unlinkDir"&&this.handleFileChange(r)}),n.on("error",i=>this.handleSourceWatcherError(n,i,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,i){if(i||this.sourcePollingFallbackStarted||!Dn(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.observationEpoch+=1,this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(r=>r!==t),kn(Y(this),t,r=>this.onError(r));try{this.startSourceWatcher(!0)}catch(r){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(r)}`))}}isIgnoredWatchPath(t,n){let i=this.relativeWatchPath(t);if(!i)return!1;let r=n?`${i}/`:i;return r===".git/"||r.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)}handleFileChange(t){let n=this.relativeWatchPath(t);!n||n===".."||n.startsWith("../")||n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||n.endsWith("index.db")||n.endsWith("index.scip")||n.endsWith("index.db.tmp")||Cn(n).startsWith(Ae)||(n===".codebaseiq.json"&&dt(this,this.projectRoot),lt(this,n)&&(this.noteFileChange(n),this.scheduleReindex({kind:"watch-source",detail:n})))}noteFileChange(t){!this.onFileChanged&&!this.onBulkChange||(this.bulkChangePending||(this.pendingFileChanges.add(t),this.pendingFileChanges.size>An&&(this.pendingFileChanges.clear(),this.bulkChangePending=!0)),this.fileChangeTimer??=this.clock.setTimeout(()=>this.flushFileChangeWindow(),Pn))}flushFileChangeWindow(){if(this.fileChangeTimer=null,this.stopped)return;let t=[...this.pendingFileChanges],n=this.bulkChangePending;this.pendingFileChanges.clear(),this.bulkChangePending=!1;try{n?this.onBulkChange?.():this.onFileChanged?.(t)}catch{}}clearFileChangeWindow(){this.fileChangeTimer&&(this.clock.clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingFileChanges.clear(),this.bulkChangePending=!1}relativeWatchPath(t){let n=Rn(t)?t:j(this.projectRoot,t);return Sn(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=ct(this.pendingTrigger,t),this.changedFiles++,this.changeSequence+=1,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}if(this.status.state==="budget-paused"){this.dirty=!0,this.setStatus({...this.status,dirty:!0});return}this.clearDebounceTimer();let n=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=this.inspectBudget();if(t.state==="paused"){this.dirty=!0;let o=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:o,dirty:!0,reason:t.detail,rebuilt:t.rebuilt,estimatedWriteBytes:t.estimatedWriteBytes}),this.clearBudgetTimer(),this.budgetTimer=this.clock.setTimeout(()=>{this.budgetTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},Math.min(2147483647,Math.max(1,o-this.wallNow())));return}let n=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&n<this.watchConfig.cooldownMs){let o=this.watchConfig.cooldownMs-n;this.dirty=!0;let c=this.wallNow()+o;this.setStatus({state:"cooldown",until:c,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},o);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let i=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=this.wallNow();this.setStatus({state:"indexing",startedAt:r});let s=this.reindexRunner.start(this.reindexRequest(i));this.activeOperation=s,s.completion.then(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let c=!1;try{c=this.onReindexComplete(o,i)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(c){let d=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(d),this.setStatus({state:"idle"});return}let a=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let c=o instanceof Error?o:new Error(String(o));this.onReindexError(c,i),this.onError(c),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===s&&(this.activeOperation=null)})}async finishStop(t,n,i,r,s){let o=[],c=t.map(async f=>{try{await f.close()}catch(D){o.push(`watch subscription close failed: ${String(D)}`)}});c.push(...n),i&&c.push((async()=>{try{let f=await i.cancel();f.state==="degraded"&&o.push(f.reason)}catch(f){o.push(`reindex cancellation failed: ${f instanceof Error?f.message:String(f)}`)}})());let a=c.length,d=c.map(f=>f.finally(()=>{a-=1})),p=await En(d,r,this.clock),u=Y(this);return o.push(...u.errors),u.errors=[],p?this.stopInProgress=!1:(o.push(`watch shutdown exceeded the ${s}ms deadline with ${a} operation(s) still pending`),Promise.all(d).then(()=>{this.stopInProgress=!1})),o.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:o.join("; ")}),{state:"degraded",reasons:o}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}inspectBudget(){try{return this.budgetInspector(this.outputDb,this.watchConfig.resourceBudget,new Date(this.wallNow()))}catch(t){return{state:"paused",reason:"activity-evidence",until:this.wallNow()+this.watchConfig.resourceBudget.windowMs,rebuilt:0,estimatedWriteBytes:0,detail:`reindex activity evidence could not be read: ${t instanceof Error?t.message:String(t)}`}}}reindexRequest(t){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:t}}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}clearBudgetTimer(){this.budgetTimer&&(this.clock.clearTimeout(this.budgetTimer),this.budgetTimer=null)}startGitStatePolling(){if(this.lastGitState=this.readGitState(),!this.lastGitState)return;let t=b(this);t.gitSignalPaths=this.resolveGitSignalPaths(),t.lastGitSignal=this.gitActivitySignal(),t.stagedIndexEntries=ut(this.projectRoot,t.gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.()}resolveGitSignalPaths(){let t=b(this).gitReader,n=P(this.projectRoot,["rev-parse","--git-dir"],t),i=P(this.projectRoot,["rev-parse","--git-common-dir"],t);if(!n)return null;let r=L(this.projectRoot,n),s=i?L(this.projectRoot,i):r,o=this.lastGitState?.indexPath;return[j(r,"HEAD"),j(s,"packed-refs"),j(s,"refs","heads"),...o?[o]:[]]}gitActivitySignal(){let t=b(this).gitSignalPaths;if(!t)return null;let n="";for(let i of t)try{let r=ot(i);n+=`${i}:${r.mtimeMs}:${r.size};`}catch{n+=`${i}:absent;`}return n}pollGitState(){let t=this.gitActivitySignal();if(t!==null){if(t===b(this).lastGitSignal)return;b(this).lastGitSignal=t}let n=this.lastGitState,i=this.readGitState();if(!n||!i||this.stopped){this.lastGitState=i;return}this.lastGitState=i;let r=n.head!==i.head,s=n.indexPath!==i.indexPath||n.indexMtimeMs!==i.indexMtimeMs||n.indexSize!==i.indexSize;if(!r&&!s)return;let o=b(this),c=o.stagedIndexEntries,a=ut(this.projectRoot,o.gitReader);o.stagedIndexEntries=a;let d=Ln(this.projectRoot,o.gitReader,n,i,c,a,r,s),p=null;d!==null&&(d.includes(".codebaseiq.json")&&dt(this,this.projectRoot),p=d.filter(u=>lt(this,u)),p.length===0)||(r&&s?this.scheduleReindex({kind:"watch-git-state",detail:ce("HEAD and index changed",p)}):r?this.scheduleReindex({kind:"watch-git-head",detail:ce("HEAD changed",p)}):s&&this.scheduleReindex({kind:"watch-git-index",detail:ce(i.indexPath??"index changed",p)}))}readGitState(){let t=b(this).gitReader,n=P(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let i=L(this.projectRoot,n),r={head:P(this.projectRoot,["rev-parse","--verify","HEAD"],t),indexPath:i};try{let s=ot(i);r.indexMtimeMs=s.mtimeMs,r.indexSize=s.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function En(e,t,n){if(e.length===0)return!0;let i=Promise.all(e).then(()=>!0),r=Math.max(0,t-n.now()),s=null,o=new Promise(a=>{s=n.setTimeout(()=>a(!1),r)}),c=await Promise.race([i,o]);return c&&s&&n.clearTimeout(s),c}var st=new WeakMap,ft=new WeakMap,ht=new WeakMap;function Y(e){let t=st.get(e);if(t)return t;let n={closures:new Set,errors:[]};return st.set(e,n),n}function wn(e){return ft.get(e)??pt}function b(e){let t=ht.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function kn(e,t,n){let i=Promise.resolve().then(()=>t.close()).catch(r=>{let s=`watch subscription close failed during polling fallback: ${String(r)}`;e.errors.push(s),n(new Error(s))});e.closures.add(i),i.then(()=>e.closures.delete(i))}function mt(e,t=Se){let{projectRoot:n,config:i,languages:r,pnpmWorkspaces:s,typescriptProjectMode:o,typescriptProjects:c,clojureConfigPath:a,indexerConcurrency:d,trigger:p}=e,u=q(n),f=Object.keys(u).length>0?u:i,D=z(n,f),Q=f.indexer?.typescript,jt=f.indexer?.clojure,ge=t(process.pid);if(!ge)throw new Error(`Could not establish watcher process identity for reindex worker ownership (pid ${process.pid}).`);return{workerPath:On(new URL("./reindex-worker.js",import.meta.url)),env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:n,SCIP_REINDEX_OUTPUT_SCIP:D.indexPath,SCIP_REINDEX_OUTPUT_DB:D.dbPath,SCIP_REINDEX_LANGUAGES:(f.languages??r)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(f.indexerConcurrency??d??""),SCIP_REINDEX_PNPM_WORKSPACES:Q?.pnpmWorkspaces??s?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:Q?.projectMode??o,projects:Q?.projects??c??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:jt?.configPath??a??"",SCIP_REINDEX_TRIGGER_KIND:p.kind,SCIP_REINDEX_TRIGGER_DETAIL:p.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(ge)}}}var Tn={now:F,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},_n=(e,t)=>In(e,t),Pn=120,An=200,Nn=15*6e4,Mn=1e3,jn=64*1024;function Vn(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function at(e,t){let n=e instanceof Error?e.message:String(e),i=t.stderrTail.trim()||t.stdoutTail.trim();return i?`${n}
3
+ ${i}`:n}function gt(e={}){let t=e.timeoutMs??Nn,n=e.terminationGraceMs??Mn,i=e.maxOutputBytes??jn,r=e.resolveLaunch??mt;return{start(s){let o=r(s),c=new AbortController,a=Vn(),d=!1,p=Pe({command:process.execPath,args:[...process.execArgv,o.workerPath],label:"watch reindex worker",env:o.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:i,maxStderrBytes:i,outputLimitBehavior:"truncate-tail",signal:c.signal,detached:!0}).then(u=>{if(a={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0)throw new Error(at(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),a));return u.durationMs}).catch(u=>{throw u instanceof _e&&(a={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(at(u,a),{cause:u})}).finally(()=>{d=!0});return{completion:p,async cancel(){d||c.abort();try{await p}catch{}return{state:"exited",diagnostics:a}},diagnostics:()=>a}}}}function ct(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}function Dn(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function Fn(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function yt(e){return e&&e.length>0?[...e]:_}function dt(e,t){try{b(e).languages=yt(q(t).languages)}catch{b(e).languages=_}}function lt(e,t){return ye(t,b(e).languages)!=="other"}function Ln(e,t,n,i,r,s,o,c){let a=new Set;if(o){if(!n.head||!i.head)return null;let d=t.runResult(e,["diff","--name-only","-z","--no-renames","--relative",n.head,i.head,"--"]);if(d.kind!=="success")return null;for(let p of $n(d.output))a.add(p)}if(c){if(r===null||s===null)return null;for(let d of Bn(r,s))a.add(d)}return[...a].sort()}function ut(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?Wn(n.output):null}function $n(e){return e.split("\0").filter(t=>t.length>0)}function Wn(e){let t=e.split("\0");if(t.at(-1)===""&&t.pop(),t.length%2!==0)return null;let n=new Map;for(let i=0;i<t.length;i+=2){let r=t[i],s=t[i+1];if(!r.startsWith(":")||!s)return null;n.set(s,r)}return n}function Bn(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(i=>e.get(i)!==t.get(i))}function ce(e,t){return t===null?`${e}; changed paths unavailable`:t.length===0?e:t.length===1?t[0]:`${t.length} compiler inputs changed`}import{existsSync as le,mkdirSync as Gn,symlinkSync as Un,readlinkSync as bt,unlinkSync as vt,readdirSync as Jn}from"fs";import{join as E,dirname as pe,resolve as w,relative as qn,isAbsolute as Yn}from"path";import{homedir as ue,platform as Kn}from"os";import{fileURLToPath as Hn}from"url";var Qn=Kn()==="win32",Ct=["codebaseiq","codebaseiq-explore","concrete-plan"];function zn(e={}){let t=e.quiet?()=>{}:console.log,n=Hn(import.meta.url),i=w(pe(n),"..","skills"),r=[E(ue(),".claude","skills"),E(ue(),".codex","skills"),E(ue(),".agents","skills")],s={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let o of r){let c=pe(o);if(!le(c))continue;Gn(o,{recursive:!0});let a=ei(o);Xn(o,i,a,s,t);for(let d of Ct){let p=E(i,d),u=E(o,d);if(!le(p)){s.skipped.push(`${a}/${d}`);continue}if(le(u)){try{let f=bt(u);if(w(f)===w(p)){s.alreadyLinked.push(`${a}/${d}`),t(` ok: ${d} \u2192 ${a} (already linked)`);continue}}catch{s.skipped.push(`${a}/${d}`),t(` skip: ${d} \u2192 ${a} (exists, not a symlink)`);continue}vt(u)}Un(p,u,Qn?"junction":"dir"),s.installed.push(`${a}/${d}`),t(` done: ${d} \u2192 ${a}`)}}return s}function Xn(e,t,n,i,r){let s=new Set(Ct);for(let o of Jn(e)){if(s.has(o))continue;let c=E(e,o),a;try{a=w(pe(c),bt(c))}catch{continue}Zn(a,t)&&(vt(c),i.pruned.push(`${n}/${o}`),r(` prune: ${o} \u2192 ${n} (removed stale codebaseiq skill link)`))}}function Zn(e,t){let n=qn(w(t),w(e));return n===""||!n.startsWith("..")&&!Yn(n)}function ei(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}var Rt=["repository-observation","repository-preview","mutation","composite","environment-observation","tool-information"];function ti(e,t=[]){return{defaultRole:e,...t.length>0?{rules:t}:{}}}function ni(e,t){for(let n of e.rules??[]){if(n.when.kind==="option-present"){let r=t.options[n.when.name];if(r!==void 0&&r!==!1)return n.role;continue}if((n.when.kind==="argument"?t.args[n.when.index]:t.options[n.when.name])===n.when.equals)return n.role}return e.defaultRole}function ii(e){return[...new Set([e.defaultRole,...(e.rules??[]).map(t=>t.role)])]}function K(e){return Rt.includes(e)}function ri(e){return e==="repository-observation"||e==="repository-preview"||e==="composite"}var fe=1,he=1,H=["compiler-graph","semantic-analysis","repository-source","change-history","runtime-measurement","heuristic","mixed","unknown"],St=["complete","partial","unknown"],Ot=["validated","failed","not-evaluated","not-applicable"],It=["observe","advise","require-adjudication","block","not-established"],xt={policyId:"codebaseiq:unresolved-repository-policy",policyVersion:he,permission:"not-established",reasons:["No repository action policy was supplied for this claim."]};function oi(e){return{schemaVersion:fe,origin:e.contract.origin,coverage:Et(e.coverage),producerValidation:e.contract.producerValidation,stateAuthority:G(e.receipt,e.receipt),repositoryPolicy:e.repositoryPolicy??xt,...e.contract.families?{families:e.contract.families}:{}}}function Et(e){return e?e.complete===!0?{state:"complete",returned:e.returned,totalKnown:!0,total:e.total??e.returned,omitted:0}:e.totalKnown?{state:"partial",returned:e.returned,totalKnown:!0,...e.total===void 0?{}:{total:e.total},...e.omitted===void 0?{}:{omitted:e.omitted}}:{state:"unknown",returned:e.returned,totalKnown:!1}:{state:"unknown",returned:0,totalKnown:!1}}function si(e,t){let n=[];return V(n,"origin",t.origins,e.origin),V(n,"coverage",t.coverage,e.coverage.state),V(n,"producer-validation",t.producerValidation,e.producerValidation.status),V(n,"state-authority",t.stateAuthority,e.stateAuthority.authority),V(n,"action-permission",t.actionPermission,e.repositoryPolicy.permission),{satisfied:n.every(i=>i.satisfied),predicates:n}}function V(e,t,n,i){n&&e.push({predicate:t,satisfied:n.includes(i),required:n,actual:i})}function me(e){return!l(e)||e.schemaVersion!==fe||!k(e.origin,H)||!ai(e.coverage)||!ci(e.producerValidation)||!di(e.stateAuthority)||!li(e.repositoryPolicy)?!1:e.families===void 0||ui(e.families)}function ai(e){return!l(e)||!k(e.state,St)||!I(e.returned)||typeof e.totalKnown!="boolean"||e.total!==void 0&&!I(e.total)||e.omitted!==void 0&&!I(e.omitted)?!1:e.state==="complete"?e.totalKnown===!0&&e.total===e.returned&&e.omitted===0:e.state==="partial"?e.totalKnown===!0&&I(e.total)&&I(e.omitted)&&e.total===Number(e.returned)+Number(e.omitted):e.totalKnown===!1}function ci(e){if(!l(e)||!k(e.status,Ot))return!1;let t=e.certification;return e.status==="validated"||e.status==="failed"?l(t)&&g(t.id)&&Number.isSafeInteger(t.version)&&Number(t.version)>0&&g(t.corpus):t===void 0}function di(e){return l(e)&&Number.isSafeInteger(e.policyVersion)&&(e.authority==="completion"||e.authority==="advisory"||e.authority==="none")&&Array.isArray(e.requiredRelationships)&&e.requiredRelationships.every(g)&&Array.isArray(e.reasons)&&e.reasons.every(g)}function li(e){return l(e)&&g(e.policyId)&&e.policyVersion===he&&k(e.permission,It)&&Array.isArray(e.reasons)&&e.reasons.every(g)}function ui(e){return Array.isArray(e)&&e.every(t=>l(t)&&g(t.id)&&g(t.selector)&&pi(t.origin))}function pi(e){return l(e)?e.kind==="fixed"?k(e.origin,H)&&e.origin!=="mixed":e.kind!=="result-field"||!g(e.field)||!l(e.values)?!1:Object.values(e.values).every(t=>k(t,H)&&t!=="mixed"):!1}function k(e,t){return typeof e=="string"&&t.includes(e)}var Tt="codebaseiq-result",_t=0,T=1,fi=1,Pt=1,At=1;function Nt(e){if(!l(e))return{kind:"malformed",reason:"CLI JSON output must be an object."};let t=Object.hasOwn(e,"kind"),n=Object.hasOwn(e,"schemaVersion");if(!t&&!n){let o=wt(e);return o?{kind:"malformed",reason:`Legacy CLI JSON envelope: ${o}`}:{kind:"legacy",schemaVersion:_t,envelope:e}}if(!t||!n)return{kind:"malformed",reason:"CLI JSON envelope must contain both kind and schemaVersion."};if(e.kind!==Tt)return{kind:"malformed",reason:`Unsupported CLI JSON envelope kind: ${bi(e.kind)}.`};let i=e.schemaVersion;if(!Number.isSafeInteger(i)||Number(i)<1)return{kind:"malformed",reason:"CLI JSON envelope schemaVersion must be a positive safe integer."};if(i!==T)return{kind:"unsupported",schemaVersion:Number(i),direction:Number(i)<T?"older":"future",...kt(e.producer)?{producer:e.producer}:{}};let r=wt(e);if(r)return{kind:"malformed",reason:`CLI JSON envelope v1: ${r}`};if(!kt(e.producer))return{kind:"malformed",reason:"CLI JSON envelope v1: producer must identify codebaseiq and its non-empty version."};if(!gi(e.resultSchemaVersion))return{kind:"malformed",reason:"CLI JSON envelope v1: resultSchemaVersion must be a positive safe integer."};let s=Mt(e.command);return s.includes(e.resultSchemaVersion)?e.evidenceContext!==void 0&&!yi(e.evidenceContext)?{kind:"malformed",reason:"CLI JSON envelope v1: evidenceContext must contain a supported receipt and analysis manifest."}:e.operationRole!==void 0&&!K(e.operationRole)?{kind:"malformed",reason:"CLI JSON envelope v1: operationRole must be a supported command operation role."}:l(e.evidenceContext)&&e.operationRole!==void 0&&e.evidenceContext.operationRole!==void 0&&e.operationRole!==e.evidenceContext.operationRole?{kind:"malformed",reason:"CLI JSON envelope v1: top-level and evidence-context operation roles must agree."}:{kind:"supported",schemaVersion:T,envelope:e}:{kind:"unsupported-result",schemaVersion:T,command:e.command,resultSchemaVersion:e.resultSchemaVersion,supportedResultSchemaVersions:s}}function hi(e){let t=Nt(e);if(t.kind==="legacy"||t.kind==="supported")return t;if(t.kind==="unsupported"){let n=t.producer?` from ${t.producer.name}@${t.producer.version}`:"";throw new Error(`Unsupported codebaseiq CLI JSON schemaVersion ${t.schemaVersion}${n}; this consumer supports the legacy unversioned envelope and schemaVersion ${T}.`)}throw t.kind==="unsupported-result"?new Error(`Unsupported resultSchemaVersion ${t.resultSchemaVersion} for codebaseiq command ${JSON.stringify(t.command)}; this consumer supports ${t.supportedResultSchemaVersions.join(", ")}.`):new Error(`Malformed codebaseiq CLI JSON envelope: ${t.reason}`)}function Mt(e){return mi[e]??[fi]}var mi={hotspots:[1,2],bottlenecks:[1,2],"complexity-hotspots":[1,2]};function wt(e){return typeof e.command!="string"||e.command.length===0?"command must be a non-empty string.":Array.isArray(e.args)?l(e.options)?Object.hasOwn(e,"result")?null:"result is required.":"options must be an object.":"args must be an array."}function kt(e){return l(e)&&e.name==="codebaseiq"&&typeof e.version=="string"&&e.version.length>0}function gi(e){return Number.isSafeInteger(e)&&Number(e)>0}function yi(e){if(!l(e)||e.schemaVersion!==Pt||e.operationRole!==void 0&&!K(e.operationRole)||!B(e.receipt))return!1;let t=e.analysisManifest;return l(t)&&t.schemaVersion===At&&(t.evidence===void 0||t.evidence==="graph-fact"||t.evidence==="heuristic"||t.evidence==="mixed")&&(t.claimQualification===void 0||me(t.claimQualification))}function bi(e){return typeof e=="string"?JSON.stringify(e):String(e)}export{It as CLAIM_ACTION_PERMISSIONS,he as CLAIM_ACTION_POLICY_VERSION,St as CLAIM_COVERAGE_STATES,H as CLAIM_ORIGINS,fe as CLAIM_QUALIFICATION_SCHEMA_VERSION,At as CLI_ANALYSIS_MANIFEST_SCHEMA_VERSION,Pt as CLI_EVIDENCE_CONTEXT_SCHEMA_VERSION,Tt as CLI_JSON_ENVELOPE_KIND,Rt as COMMAND_OPERATION_ROLES,T as CURRENT_CLI_JSON_ENVELOPE_SCHEMA_VERSION,xt as DEFAULT_REPOSITORY_POLICY_ACTION,_t as LEGACY_CLI_JSON_ENVELOPE_SCHEMA_VERSION,h as LEGACY_OBSERVATION_RECEIPT_SCHEMA_VERSION,N as OBSERVATION_IDENTITY_CANONICALIZATION_VERSION,A as OBSERVATION_IDENTITY_HASH_ALGORITHM,W as OBSERVATION_IDENTITY_SCHEMA_VERSION,R as OBSERVATION_RECEIPT_SCHEMA_VERSION,te as OBSERVATION_STATE_AUTHORITY_POLICY_VERSION,Ot as PRODUCER_VALIDATION_STATUSES,de as Watcher,ti as commandOperation,ii as commandOperationRoles,ie as compareObservationReceipts,Le as createObservationIdentity,gt as createReindexRunner,Nt as decodeCliJsonEnvelope,ne as decodeObservationReceipt,Et as deriveClaimCoverage,oi as deriveClaimQualification,G as deriveObservationStateAuthority,si as evaluateClaimQualification,Dt as getScipVersion,yn as initProjectConfig,zn as installSkills,me as isClaimQualificationV1,K as isCommandOperationRole,B as isObservationReceipt,Vt as isScipInstalled,q as loadProjectConfig,$e as observationReceiptGenerationIdentity,Be as observationReceiptStabilityLabel,We as observationReceiptWorkspaceIdentity,ri as operationObservesRepository,Ft as printScipInstallInstructions,hi as requireCompatibleCliJsonEnvelope,ni as resolveCommandOperationRole,z as resolveIndexStoragePaths,mt as resolveReindexWorkerLaunch,Mt as supportedCliResultSchemaVersions};
4
4
  //# sourceMappingURL=runtime.js.map
@@ -1,2 +1,2 @@
1
- import{a as V}from"./chunk-AAQQPKCU.js";import{e as E,f as A,g as U,h as O,n as C}from"./chunk-NNO6A2PO.js";import"./chunk-P5XHIJHI.js";import"./chunk-KUW32IRO.js";import"./chunk-5VKBFZZU.js";import"./chunk-7MGU3HPH.js";import"./chunk-DRENNWRG.js";import{A as N,B as P,C as g,D as k,F as B,j as D,l as h,r as x,s as T,v as _,w as q}from"./chunk-RDBI2RXU.js";import"./chunk-R2NOK63J.js";import{c as L,d as b}from"./chunk-EF2R3WNQ.js";import"./chunk-WE5RZHZ7.js";import"./chunk-2Q2LW5JW.js";import n from"process";import{randomUUID as H}from"crypto";import{rmSync as J}from"fs";import{resolve as f}from"path";import{pathToFileURL as W}from"url";var X=10*6e4,F=10,G=250,z=1e3;function Y(e,t,s={}){let M=_(e),d=s.now??(s.nowMs===void 0?Date.now:()=>s.nowMs),S=d(),y=A(e),w=N(M,{ownerId:s.ownerId??re,nowMs:S,limits:s.limits,owner:ne,liveness:ie}),p=0;for(let i of w){let o=null,c,m="handler-error";try{let a=P(i,s.limits),u;try{u=JSON.parse(a)}catch{throw m="malformed-request",new Error("Durable Rust semantic helper received malformed request JSON.")}let r=U(u,{claimRequestId:i.requestId,sessionIdentity:y,nowMs:d()});if(!r.ok)throw m=r.code,c=r.responseIdentity,new Error(r.error);o=r.value,c={id:o.id,sessionIdentity:o.sessionIdentity,deadlineAtMs:o.deadlineAtMs};let l=$(o.request,s.monotonicNowMs??b());s.beforeRequest?.(l);let R=t.handle(l),I=d();if(o.deadlineAtMs<I)throw m="expired-request",new Error("Durable Rust semantic request expired while the helper was processing it.");g(M,i,{ok:!0,protocolVersion:E,id:o.id,sessionIdentity:o.sessionIdentity,deadlineAtMs:o.deadlineAtMs,...R},{nowMs:I,limits:s.limits})}catch(a){let u=d(),r=c??(o?{id:o.id,sessionIdentity:o.sessionIdentity,deadlineAtMs:o.deadlineAtMs}:void 0),l=a instanceof Error?a.message:String(a);k(M,i,{ok:!1,protocolVersion:E,id:r?.id??i.requestId,...r?{sessionIdentity:r.sessionIdentity,deadlineAtMs:r.deadlineAtMs}:{},errorCode:m,error:l},l,{nowMs:u,limits:s.limits})}p+=1}return p}function $(e,t){let s=t+Math.max(1,e.timeoutMs-1e3);return{...e,request:{...e.request,readinessDeadlineMs:s}}}async function K(e,t){let s=_(e);q(s);let M=f(e,"server.lock"),d=ee(M);if(!d)return;let S=new O(()=>C({semanticWorkerPath:t,shareEnvironment:!0})),y=!1,w=b(),p=Number.NEGATIVE_INFINITY,i,o=0,c=L(n.pid),m=A(e),a=()=>{y=!0};n.once("SIGINT",a),n.once("SIGTERM",a);let u=(r=!1,l=r?"durable":"visibility")=>{let R=Date.now(),I=b();if(!r&&I-p<z)return;p=I;let v={protocolVersion:E,sessionIdentity:m,pid:n.pid,...c?{processIdentity:c}:{},heartbeatAtMs:R,...i===void 0?{}:{busyUntilMs:i},mailbox:B(s)};l==="durable"?T(f(e,"server.json"),v):x(f(e,"server.json"),v)};try{u(!0);let r=te();for(;!y&&b()-w<r;){let l=Y(e,S,{beforeRequest(R){i=Date.now()+R.timeoutMs+5e3,u(!0,"visibility")}});l>0?(o=0,w=b(),i=void 0,u(!0,"visibility")):(o+=1,u()),await se(Q(l,o))}}finally{S.shutdown(),J(f(e,"server.json"),{force:!0}),d.release()}}function Q(e,t=1){if(e>0)return F;let s=Math.max(0,Math.min(5,t-1));return Math.min(G,F*2**s)}var Z=e=>{let t=Number(e);return Number.isInteger(t)&&t>0?{pid:t}:null};function ee(e){let t=h(e,{kind:"rust-durable-session-server",parseLegacy:Z});return t.kind==="acquired"?t.lock:null}function te(){let e=Number(n.env.SCIP_RUST_SEMANTIC_DURABLE_IDLE_MS);return Number.isInteger(e)&&e>=0?e:X}function se(e){return new Promise(t=>setTimeout(t,e))}var oe=n.argv[1]?W(f(n.argv[1])).href:null;if(oe===import.meta.url){V();let e=n.argv[2],t=n.argv[3];!e||!t?(console.error("durable-rust-session: expected <session-dir> <semantic-worker-path>"),n.exitCode=1):await K(e,t)}var re=`rust-semantic-${n.pid}-${H()}`,j=L(n.pid),ne={pid:n.pid,...j?{processIdentity:j}:{}},ie={isProcessAlive:D,readProcessIdentity:L};export{ee as acquireDurableRustSessionServerLock,Q as durableSessionLoopDelayMs,Y as processDurableRustSessionRequests};
1
+ import{a as V}from"./chunk-AAQQPKCU.js";import{e as E,f as A,g as U,h as O,n as C}from"./chunk-HCMQZPEO.js";import"./chunk-P5XHIJHI.js";import"./chunk-H5QXP63L.js";import"./chunk-2Q2LW5JW.js";import"./chunk-EXMVF3JR.js";import"./chunk-5IO2APSS.js";import"./chunk-DRENNWRG.js";import{A as N,B as P,C as g,D as k,F as B,j as D,l as h,r as x,s as T,v as _,w as q}from"./chunk-ACZDU5GK.js";import"./chunk-R2NOK63J.js";import{c as L,d as b}from"./chunk-6URCE5QY.js";import"./chunk-4O52YNKL.js";import n from"process";import{randomUUID as H}from"crypto";import{rmSync as J}from"fs";import{resolve as f}from"path";import{pathToFileURL as W}from"url";var X=10*6e4,F=10,G=250,z=1e3;function Y(e,t,s={}){let M=_(e),d=s.now??(s.nowMs===void 0?Date.now:()=>s.nowMs),S=d(),y=A(e),w=N(M,{ownerId:s.ownerId??re,nowMs:S,limits:s.limits,owner:ne,liveness:ie}),p=0;for(let i of w){let o=null,c,m="handler-error";try{let a=P(i,s.limits),u;try{u=JSON.parse(a)}catch{throw m="malformed-request",new Error("Durable Rust semantic helper received malformed request JSON.")}let r=U(u,{claimRequestId:i.requestId,sessionIdentity:y,nowMs:d()});if(!r.ok)throw m=r.code,c=r.responseIdentity,new Error(r.error);o=r.value,c={id:o.id,sessionIdentity:o.sessionIdentity,deadlineAtMs:o.deadlineAtMs};let l=$(o.request,s.monotonicNowMs??b());s.beforeRequest?.(l);let R=t.handle(l),I=d();if(o.deadlineAtMs<I)throw m="expired-request",new Error("Durable Rust semantic request expired while the helper was processing it.");g(M,i,{ok:!0,protocolVersion:E,id:o.id,sessionIdentity:o.sessionIdentity,deadlineAtMs:o.deadlineAtMs,...R},{nowMs:I,limits:s.limits})}catch(a){let u=d(),r=c??(o?{id:o.id,sessionIdentity:o.sessionIdentity,deadlineAtMs:o.deadlineAtMs}:void 0),l=a instanceof Error?a.message:String(a);k(M,i,{ok:!1,protocolVersion:E,id:r?.id??i.requestId,...r?{sessionIdentity:r.sessionIdentity,deadlineAtMs:r.deadlineAtMs}:{},errorCode:m,error:l},l,{nowMs:u,limits:s.limits})}p+=1}return p}function $(e,t){let s=t+Math.max(1,e.timeoutMs-1e3);return{...e,request:{...e.request,readinessDeadlineMs:s}}}async function K(e,t){let s=_(e);q(s);let M=f(e,"server.lock"),d=ee(M);if(!d)return;let S=new O(()=>C({semanticWorkerPath:t,shareEnvironment:!0})),y=!1,w=b(),p=Number.NEGATIVE_INFINITY,i,o=0,c=L(n.pid),m=A(e),a=()=>{y=!0};n.once("SIGINT",a),n.once("SIGTERM",a);let u=(r=!1,l=r?"durable":"visibility")=>{let R=Date.now(),I=b();if(!r&&I-p<z)return;p=I;let v={protocolVersion:E,sessionIdentity:m,pid:n.pid,...c?{processIdentity:c}:{},heartbeatAtMs:R,...i===void 0?{}:{busyUntilMs:i},mailbox:B(s)};l==="durable"?T(f(e,"server.json"),v):x(f(e,"server.json"),v)};try{u(!0);let r=te();for(;!y&&b()-w<r;){let l=Y(e,S,{beforeRequest(R){i=Date.now()+R.timeoutMs+5e3,u(!0,"visibility")}});l>0?(o=0,w=b(),i=void 0,u(!0,"visibility")):(o+=1,u()),await se(Q(l,o))}}finally{S.shutdown(),J(f(e,"server.json"),{force:!0}),d.release()}}function Q(e,t=1){if(e>0)return F;let s=Math.max(0,Math.min(5,t-1));return Math.min(G,F*2**s)}var Z=e=>{let t=Number(e);return Number.isInteger(t)&&t>0?{pid:t}:null};function ee(e){let t=h(e,{kind:"rust-durable-session-server",parseLegacy:Z});return t.kind==="acquired"?t.lock:null}function te(){let e=Number(n.env.SCIP_RUST_SEMANTIC_DURABLE_IDLE_MS);return Number.isInteger(e)&&e>=0?e:X}function se(e){return new Promise(t=>setTimeout(t,e))}var oe=n.argv[1]?W(f(n.argv[1])).href:null;if(oe===import.meta.url){V();let e=n.argv[2],t=n.argv[3];!e||!t?(console.error("durable-rust-session: expected <session-dir> <semantic-worker-path>"),n.exitCode=1):await K(e,t)}var re=`rust-semantic-${n.pid}-${H()}`,j=L(n.pid),ne={pid:n.pid,...j?{processIdentity:j}:{}},ie={isProcessAlive:D,readProcessIdentity:L};export{ee as acquireDurableRustSessionServerLock,Q as durableSessionLoopDelayMs,Y as processDurableRustSessionRequests};
2
2
  //# sourceMappingURL=rust-semantic-session-server.js.map
@@ -1,2 +1,2 @@
1
- import{a as te,b as ie,c as C,d as N,e as G,f as E,g as B,i as H,j as U,k as K,l as W,m as le,p as ce,q as ue,r as de,s as fe,t as S,v as me,w as pe,x as D}from"./chunk-OLF4MA5W.js";import{a as P,b as ne}from"./chunk-ILMHV3KM.js";import{d as F,e as se,f as re,g as oe,h as ae}from"./chunk-5VKBFZZU.js";import"./chunk-7MGU3HPH.js";import{a as j,j as d,k as M}from"./chunk-R2NOK63J.js";import"./chunk-EF2R3WNQ.js";import{ba as q,ca as ee}from"./chunk-WE5RZHZ7.js";import k from"process";import{existsSync as Te,writeFileSync as ve}from"fs";import{dirname as Ae,isAbsolute as Ie,resolve as Ce}from"path";import{performance as L}from"perf_hooks";import{parentPort as Ee}from"worker_threads";import{resolve as he}from"path";var ze=4,x=class{constructor(n=ze){this.capacity=n;if(!Number.isSafeInteger(n)||n<=0)throw new Error("Rust analyzer session capacity must be a positive safe integer.")}capacity;entries=new Map;get(n){let i=this.entries.get(n);if(i)return this.entries.delete(n),this.entries.set(n,i),i}async acquire(n,i,t){let s=this.get(n);if(s)return s;if(this.entries.size>=this.capacity){let o=this.entries.entries().next().value;if(!o)throw new Error("Rust analyzer session registry capacity accounting is inconsistent.");this.entries.delete(o[0]);try{await t(o[1])}catch(l){throw this.restoreOldest(o),l}}let r=await i();if(r.key!==n){try{await t(r)}catch(o){throw new AggregateError([o],`Rust analyzer session factory returned '${r.key}' for reserved key '${n}', and the mismatched session could not be reaped.`,{cause:o})}throw new Error(`Rust analyzer session factory returned '${r.key}' for reserved key '${n}'.`)}return this.entries.set(n,r),r}deleteIfSame(n){return this.entries.get(n.key)!==n?!1:this.entries.delete(n.key)}async shutdownAll(n){let i=[...this.entries.values()];this.entries.clear();let t=await Promise.allSettled(i.map(n)),s=[];for(let r=0;r<t.length;r+=1){let o=t[r];if(o.status==="fulfilled")continue;let l=i[r];s.push({session:l,reason:o.reason}),this.entries.set(l.key,l)}if(s.length>0)throw new AggregateError(s.map(r=>r.reason),`Failed to shut down ${s.length} retained rust-analyzer session(s).`)}get size(){return this.entries.size}restoreOldest(n){let i=[...this.entries.entries()];this.entries.clear(),this.entries.set(n[0],n[1]);for(let[t,s]of i)this.entries.set(t,s)}};function Re(e,n){let i=he(e);return[...new Set(n.map(t=>he(i,t)))].sort((t,s)=>t<s?-1:t>s?1:0)}function ye(e,n,i){return JSON.stringify({binary:e,sessionRoot:n,linkedProjects:i})}var Fe="SCIP_RUST_SEMANTIC_REFERENCE_TASK_PROFILE_MS",We="SCIP_RUST_SEMANTIC_CALLEE_TASK_PROFILE_MS",_=new x,ge=Promise.resolve(),Me;Ee?.on("message",e=>{ge=ge.then(()=>xe(e)).catch(()=>{})});async function xe(e){if(Me??=Ae(e.responsePath),e.kind==="shutdown"){await He(),g(e.responsePath,{ok:!0},e.sharedBuffer);return}if(e.kind==="import-definitions"){try{let n=await Le(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t={available:!1,reason:n instanceof Error?n.message:String(n),sourcePaths:e.request.positions.map(s=>[s.id,null])};g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}return}try{let n=await _e(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t=De(e.request,n instanceof Error?n.message:String(n));g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}}async function Le(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=await d("rust.semantic.worker.session",()=>Pe(e.projectRoot,e.rustAnalyzerBinary,[e.file],{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs}),()=>({kind:"import-definitions",files:1,positions:e.positions.length}));if(!i.capabilities.definitionProvider)return{available:!1,reason:"rust-analyzer initialized without textDocument/definition support.",sourcePaths:e.positions.map(o=>[o.id,null])};let t=0;await E(()=>d("rust.semantic.worker.open-source-documents",async()=>{t=await Ne(i,e.projectRoot,[e.file],{diagnosticsTimeoutMs:e.diagnosticsTimeoutMs,settleDelayMs:e.settleDelayMs,readinessDeadlineMs:e.readinessDeadlineMs})},()=>({files:1,openedDocuments:t,positions:e.positions.length})),()=>ke(_,i,e.readinessDeadlineMs));let s=0;return{available:!0,sourcePaths:await d("rust.semantic.worker.import-definitions",()=>P(e.positions,e.concurrency??8,async o=>{let l=await i.client.definition({textDocument:{uri:F(e.projectRoot,o.file)},position:{line:o.line,character:o.column}},n),u=Ge(e.projectRoot,l);return u&&(s+=1),[o.id,u]}),()=>({positions:e.positions.length,resolvedPositions:s,concurrency:e.concurrency??8}))}}async function _e(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=e.includeReferences!==!1,t=e.includeCallees===!0,s=e.includeSignatures===!0,r=H(e),o=U(e),l=K(e),u=W(e),c=await d("rust.semantic.worker.session",()=>Oe(e),()=>({kind:"semantic",definitions:u.length,referenceDefinitions:r.length,calleeDefinitions:o.length,signatureDefinitions:l.length,references:i,callees:t,signatures:s})),p=Be(c.capabilities,{references:i,callees:t,signatures:s});if(p)return De(e,p);let f=0;await E(()=>d("rust.semantic.worker.open-definition-documents",async()=>{f=await je(c,e)},()=>({definitions:u.length,openedDocuments:f})),()=>ke(_,c,e.readinessDeadlineMs));let m=0,b=0,y=j(),$=y?new Map:null,z=y?we(k.env[Fe]):null,J=()=>i?d("rust.semantic.worker.references",()=>P(r,e.concurrency??8,async a=>{let w=y?L.now():0,R=await me(c.client,re(e.projectRoot,a,!1),{requestTimeoutMs:e.requestTimeoutMs,retryTimeoutMs:e.referenceRetryTimeoutMs,deadlineMs:e.readinessDeadlineMs}),h=ae(oe(e.projectRoot,R.locations)),I=y?Math.round(L.now()-w):0;return Ue($,a.relativePath,{durationMs:I,references:h.length,hasReferences:h.length>0,slow:z!==null&&I>=z}),z!==null&&I>=z&&M({type:"span",name:"rust.semantic.worker.reference-task",durationMs:I,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,references:h.length,complete:R.complete}),h.length>0&&(b+=1),m+=h.length,{symbolId:a.symbolId,references:h,complete:R.complete}}),()=>({definitions:r.length,concurrency:e.concurrency??8,definitionsWithReferences:b,references:m})):Promise.resolve(r.map(a=>({symbolId:a.symbolId,references:[],complete:!0}))),V=0,Y=0,T=j(),Z=T?new Map:null,v=T?we(k.env[We]):null,Q=()=>t?d("rust.semantic.worker.callees",()=>P(o,e.concurrency??8,async a=>{let w=T?L.now():0,R=await pe(c.client,e.projectRoot,a,n),h=T?Math.round(L.now()-w):0;return Je(Z,a.relativePath,{durationMs:h,callees:R.length,hasCallees:R.length>0,slow:v!==null&&h>=v}),v!==null&&h>=v&&M({type:"span",name:"rust.semantic.worker.callee-task",durationMs:h,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,callees:R.length}),R.length>0&&(Y+=1),V+=R.length,{symbolId:a.symbolId,callees:R}}),()=>({definitions:o.length,concurrency:e.concurrency??8,definitionsWithCallees:Y,callees:V})):Promise.resolve([]),A,O;i&&t&&r.length>0&&o.length>0&&Ze()?[A,O]=await ne([J(),Q()]):(A=await J(),O=await Q()),Ke($),Ve(Z);let X=0,be=s?await d("rust.semantic.worker.signatures",()=>P(l,e.concurrency??8,async a=>{let w=await le(c.client,e.projectRoot,a,n);return w&&(X+=1),{symbolId:a.symbolId,signature:w}}),()=>({definitions:l.length,concurrency:e.concurrency??8,signaturesFound:X})):[];return{available:!0,references:A.filter(a=>a.complete).map(a=>[a.symbolId,a.references]),incompleteReferenceSymbolIds:A.filter(a=>!a.complete).map(a=>a.symbolId),...t?{callees:O.map(a=>[a.symbolId,a.callees])}:{},...s?{signatures:be.map(a=>[a.symbolId,a.signature])}:{}}}async function Oe(e){return Pe(e.projectRoot,e.rustAnalyzerBinary,W(e).map(n=>n.relativePath),{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs})}async function Pe(e,n,i,t){let s=Re(e,de(e,i.map(l=>({relativePath:l})))),r=ue(e,s),o=ye(n,r,s);return _.acquire(o,async()=>{let l=ce(s),u=new te(ie(n,r,k.env,Me),{requestTimeoutMs:t.requestTimeoutMs,configuration:l}),c=t.readinessDeadlineMs===void 0?null:{afterGeneration:u.serverStatusGeneration(),deadlineMs:t.readinessDeadlineMs},p=await E(()=>d("rust.semantic.worker.initialize",()=>u.initialize({processId:k.pid,rootUri:F(r,"."),capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1},callHierarchy:{dynamicRegistration:!1},hover:{dynamicRegistration:!1}}},initializationOptions:l},{timeoutMs:t.requestTimeoutMs,deadlineMs:t.readinessDeadlineMs}),()=>({linkedProjects:s.length,relativePaths:i.length})),()=>u.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}));return{key:o,client:u,capabilities:p.capabilities,openedPaths:new Set,initializationReadiness:c}},l=>l.client.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}))}async function je(e,n){let i=W(n).filter(c=>e.openedPaths.has(c.relativePath)?!1:Te(Ce(n.projectRoot,c.relativePath)));if(i.length===0)return await Se(e),0;let t=e.initializationReadiness,s=n.readinessDeadlineMs===void 0?null:{statusSnapshot:t?null:e.client.serverStatusSnapshot(),initializationGeneration:t?.afterGeneration,deadlineMs:n.readinessDeadlineMs},r=fe(e.client,n.projectRoot,i);for(let c of i)e.openedPaths.add(c.relativePath);let o=n.diagnosticsTimeoutMs??1e4,l=o;await d("rust.semantic.worker.diagnostics",()=>s?G(c=>(l=c,S(e.client,r,c)),o,s.deadlineMs):S(e.client,r,o),()=>({openedDocuments:r.length,timeoutMs:l}));let u=n.settleDelayMs??5e3;if(!s)await d("rust.semantic.worker.settle",()=>D(u),()=>({openedDocuments:r.length,settleDelayMs:u}));else{let c;await d("rust.semantic.worker.readiness",async()=>{let p=m=>d("rust.semantic.worker.settle",()=>D(m),()=>({openedDocuments:r.length,settleDelayMs:m})),f=s.initializationGeneration===void 0?await N(e.client,s.statusSnapshot,r.length,s.deadlineMs,u,Date.now,p):await C(e.client,s.initializationGeneration,r.length,s.deadlineMs,u,Date.now,p);s.initializationGeneration!==void 0&&(e.initializationReadiness=null),c=f?.health},()=>({phase:s.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:r.length,health:c}))}return r.length}async function Ne(e,n,i,t){let s=i.filter(f=>!e.openedPaths.has(f));if(s.length===0)return await Se(e),0;let r=e.initializationReadiness,o=t.readinessDeadlineMs===void 0?null:{statusSnapshot:r?null:e.client.serverStatusSnapshot(),initializationGeneration:r?.afterGeneration,deadlineMs:t.readinessDeadlineMs},l=[];for(let f of s)try{let m=F(n,f);e.client.didOpenTextDocument({uri:m,languageId:"rust",version:1,text:q(n,f,{inputKind:"indexed Rust source file"})}),e.openedPaths.add(f),l.push(m)}catch(m){if(!ee(m))throw m}let u=t.diagnosticsTimeoutMs??1e4,c=u;await d("rust.semantic.worker.diagnostics",()=>o?G(f=>(c=f,S(e.client,l,f)),u,o.deadlineMs):S(e.client,l,u),()=>({openedDocuments:l.length,timeoutMs:c}));let p=t.settleDelayMs??5e3;if(!o)await d("rust.semantic.worker.settle",()=>D(p),()=>({openedDocuments:l.length,settleDelayMs:p}));else{let f;await d("rust.semantic.worker.readiness",async()=>{let m=y=>d("rust.semantic.worker.settle",()=>D(y),()=>({openedDocuments:l.length,settleDelayMs:y})),b=o.initializationGeneration===void 0?await N(e.client,o.statusSnapshot,l.length,o.deadlineMs,p,Date.now,m):await C(e.client,o.initializationGeneration,l.length,o.deadlineMs,p,Date.now,m);o.initializationGeneration!==void 0&&(e.initializationReadiness=null),f=b?.health},()=>({phase:o.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:l.length,health:f}))}return l.length}async function Se(e){let n=e.initializationReadiness;if(!n)return;let i;await d("rust.semantic.worker.readiness",async()=>{i=(await C(e.client,n.afterGeneration,0,n.deadlineMs,0)).health,e.initializationReadiness=null},()=>({phase:"initialize",openedDocuments:0,health:i}))}function Ge(e,n){for(let i of n){let t=se(e,i.uri);if(!(!t||t===".."||t.startsWith("../")||Ie(t)))return t}return null}function Be(e,n){return n.references&&!e.referencesProvider?"rust-analyzer initialized without textDocument/references support.":n.callees&&!e.callHierarchyProvider?"rust-analyzer initialized without call hierarchy support.":n.signatures&&!e.hoverProvider?"rust-analyzer initialized without hover support.":null}function De(e,n){let i=H(e),t=U(e),s=K(e);return{available:!1,reason:n,references:i.map(r=>[r.symbolId,[]]),...e.includeCallees?{callees:t.map(r=>[r.symbolId,[]])}:{},...e.includeSignatures?{signatures:s.map(r=>[r.symbolId,null])}:{}}}async function He(){await _.shutdownAll(e=>e.client.shutdownAndReap())}async function ke(e,n,i){e.deleteIfSame(n),await n.client.shutdownAndReap({deadlineMs:i})}function Ue(e,n,i){if(!e)return;let t=$e(e,n);t.definitions+=1,i.hasReferences&&(t.definitionsWithReferences+=1),t.references+=i.references,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ke(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.references.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithReferences:t.definitionsWithReferences,references:t.references,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function $e(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithReferences:0,references:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function Je(e,n,i){if(!e)return;let t=Ye(e,n);t.definitions+=1,i.hasCallees&&(t.definitionsWithCallees+=1),t.callees+=i.callees,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ve(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.callees.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithCallees:t.definitionsWithCallees,callees:t.callees,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function Ye(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithCallees:0,callees:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function we(e){if(e===void 0||e==="")return null;let n=Number(e);return Number.isInteger(n)&&n>=0?n:null}function Ze(){let e=k.env.SCIP_RUST_SEMANTIC_PARALLEL_OPERATIONS;return e!=="0"&&e!=="false"}function g(e,n,i){ve(e,JSON.stringify(n));let t=new Int32Array(i);Atomics.store(t,0,1),Atomics.notify(t,0)}export{ke as discardRustAnalyzerSession};
1
+ import{a as te,b as ie,c as C,d as N,e as G,f as E,g as B,i as H,j as U,k as K,l as W,m as le,p as ce,q as ue,r as de,s as fe,t as S,v as me,w as pe,x as D}from"./chunk-K5G7SPAG.js";import{a as P,b as ne}from"./chunk-ILMHV3KM.js";import{d as F,e as se,f as re,g as oe,h as ae}from"./chunk-EXMVF3JR.js";import"./chunk-5IO2APSS.js";import{a as j,j as d,k as M}from"./chunk-R2NOK63J.js";import"./chunk-6URCE5QY.js";import{ca as q,da as ee}from"./chunk-4O52YNKL.js";import k from"process";import{existsSync as Te,writeFileSync as ve}from"fs";import{dirname as Ae,isAbsolute as Ie,resolve as Ce}from"path";import{performance as L}from"perf_hooks";import{parentPort as Ee}from"worker_threads";import{resolve as he}from"path";var ze=4,x=class{constructor(n=ze){this.capacity=n;if(!Number.isSafeInteger(n)||n<=0)throw new Error("Rust analyzer session capacity must be a positive safe integer.")}capacity;entries=new Map;get(n){let i=this.entries.get(n);if(i)return this.entries.delete(n),this.entries.set(n,i),i}async acquire(n,i,t){let s=this.get(n);if(s)return s;if(this.entries.size>=this.capacity){let o=this.entries.entries().next().value;if(!o)throw new Error("Rust analyzer session registry capacity accounting is inconsistent.");this.entries.delete(o[0]);try{await t(o[1])}catch(l){throw this.restoreOldest(o),l}}let r=await i();if(r.key!==n){try{await t(r)}catch(o){throw new AggregateError([o],`Rust analyzer session factory returned '${r.key}' for reserved key '${n}', and the mismatched session could not be reaped.`,{cause:o})}throw new Error(`Rust analyzer session factory returned '${r.key}' for reserved key '${n}'.`)}return this.entries.set(n,r),r}deleteIfSame(n){return this.entries.get(n.key)!==n?!1:this.entries.delete(n.key)}async shutdownAll(n){let i=[...this.entries.values()];this.entries.clear();let t=await Promise.allSettled(i.map(n)),s=[];for(let r=0;r<t.length;r+=1){let o=t[r];if(o.status==="fulfilled")continue;let l=i[r];s.push({session:l,reason:o.reason}),this.entries.set(l.key,l)}if(s.length>0)throw new AggregateError(s.map(r=>r.reason),`Failed to shut down ${s.length} retained rust-analyzer session(s).`)}get size(){return this.entries.size}restoreOldest(n){let i=[...this.entries.entries()];this.entries.clear(),this.entries.set(n[0],n[1]);for(let[t,s]of i)this.entries.set(t,s)}};function Re(e,n){let i=he(e);return[...new Set(n.map(t=>he(i,t)))].sort((t,s)=>t<s?-1:t>s?1:0)}function ye(e,n,i){return JSON.stringify({binary:e,sessionRoot:n,linkedProjects:i})}var Fe="SCIP_RUST_SEMANTIC_REFERENCE_TASK_PROFILE_MS",We="SCIP_RUST_SEMANTIC_CALLEE_TASK_PROFILE_MS",_=new x,ge=Promise.resolve(),Me;Ee?.on("message",e=>{ge=ge.then(()=>xe(e)).catch(()=>{})});async function xe(e){if(Me??=Ae(e.responsePath),e.kind==="shutdown"){await He(),g(e.responsePath,{ok:!0},e.sharedBuffer);return}if(e.kind==="import-definitions"){try{let n=await Le(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t={available:!1,reason:n instanceof Error?n.message:String(n),sourcePaths:e.request.positions.map(s=>[s.id,null])};g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}return}try{let n=await _e(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t=De(e.request,n instanceof Error?n.message:String(n));g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}}async function Le(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=await d("rust.semantic.worker.session",()=>Pe(e.projectRoot,e.rustAnalyzerBinary,[e.file],{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs}),()=>({kind:"import-definitions",files:1,positions:e.positions.length}));if(!i.capabilities.definitionProvider)return{available:!1,reason:"rust-analyzer initialized without textDocument/definition support.",sourcePaths:e.positions.map(o=>[o.id,null])};let t=0;await E(()=>d("rust.semantic.worker.open-source-documents",async()=>{t=await Ne(i,e.projectRoot,[e.file],{diagnosticsTimeoutMs:e.diagnosticsTimeoutMs,settleDelayMs:e.settleDelayMs,readinessDeadlineMs:e.readinessDeadlineMs})},()=>({files:1,openedDocuments:t,positions:e.positions.length})),()=>ke(_,i,e.readinessDeadlineMs));let s=0;return{available:!0,sourcePaths:await d("rust.semantic.worker.import-definitions",()=>P(e.positions,e.concurrency??8,async o=>{let l=await i.client.definition({textDocument:{uri:F(e.projectRoot,o.file)},position:{line:o.line,character:o.column}},n),u=Ge(e.projectRoot,l);return u&&(s+=1),[o.id,u]}),()=>({positions:e.positions.length,resolvedPositions:s,concurrency:e.concurrency??8}))}}async function _e(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=e.includeReferences!==!1,t=e.includeCallees===!0,s=e.includeSignatures===!0,r=H(e),o=U(e),l=K(e),u=W(e),c=await d("rust.semantic.worker.session",()=>Oe(e),()=>({kind:"semantic",definitions:u.length,referenceDefinitions:r.length,calleeDefinitions:o.length,signatureDefinitions:l.length,references:i,callees:t,signatures:s})),p=Be(c.capabilities,{references:i,callees:t,signatures:s});if(p)return De(e,p);let f=0;await E(()=>d("rust.semantic.worker.open-definition-documents",async()=>{f=await je(c,e)},()=>({definitions:u.length,openedDocuments:f})),()=>ke(_,c,e.readinessDeadlineMs));let m=0,b=0,y=j(),$=y?new Map:null,z=y?we(k.env[Fe]):null,J=()=>i?d("rust.semantic.worker.references",()=>P(r,e.concurrency??8,async a=>{let w=y?L.now():0,R=await me(c.client,re(e.projectRoot,a,!1),{requestTimeoutMs:e.requestTimeoutMs,retryTimeoutMs:e.referenceRetryTimeoutMs,deadlineMs:e.readinessDeadlineMs}),h=ae(oe(e.projectRoot,R.locations)),I=y?Math.round(L.now()-w):0;return Ue($,a.relativePath,{durationMs:I,references:h.length,hasReferences:h.length>0,slow:z!==null&&I>=z}),z!==null&&I>=z&&M({type:"span",name:"rust.semantic.worker.reference-task",durationMs:I,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,references:h.length,complete:R.complete}),h.length>0&&(b+=1),m+=h.length,{symbolId:a.symbolId,references:h,complete:R.complete}}),()=>({definitions:r.length,concurrency:e.concurrency??8,definitionsWithReferences:b,references:m})):Promise.resolve(r.map(a=>({symbolId:a.symbolId,references:[],complete:!0}))),V=0,Y=0,T=j(),Z=T?new Map:null,v=T?we(k.env[We]):null,Q=()=>t?d("rust.semantic.worker.callees",()=>P(o,e.concurrency??8,async a=>{let w=T?L.now():0,R=await pe(c.client,e.projectRoot,a,n),h=T?Math.round(L.now()-w):0;return Je(Z,a.relativePath,{durationMs:h,callees:R.length,hasCallees:R.length>0,slow:v!==null&&h>=v}),v!==null&&h>=v&&M({type:"span",name:"rust.semantic.worker.callee-task",durationMs:h,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,callees:R.length}),R.length>0&&(Y+=1),V+=R.length,{symbolId:a.symbolId,callees:R}}),()=>({definitions:o.length,concurrency:e.concurrency??8,definitionsWithCallees:Y,callees:V})):Promise.resolve([]),A,O;i&&t&&r.length>0&&o.length>0&&Ze()?[A,O]=await ne([J(),Q()]):(A=await J(),O=await Q()),Ke($),Ve(Z);let X=0,be=s?await d("rust.semantic.worker.signatures",()=>P(l,e.concurrency??8,async a=>{let w=await le(c.client,e.projectRoot,a,n);return w&&(X+=1),{symbolId:a.symbolId,signature:w}}),()=>({definitions:l.length,concurrency:e.concurrency??8,signaturesFound:X})):[];return{available:!0,references:A.filter(a=>a.complete).map(a=>[a.symbolId,a.references]),incompleteReferenceSymbolIds:A.filter(a=>!a.complete).map(a=>a.symbolId),...t?{callees:O.map(a=>[a.symbolId,a.callees])}:{},...s?{signatures:be.map(a=>[a.symbolId,a.signature])}:{}}}async function Oe(e){return Pe(e.projectRoot,e.rustAnalyzerBinary,W(e).map(n=>n.relativePath),{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs})}async function Pe(e,n,i,t){let s=Re(e,de(e,i.map(l=>({relativePath:l})))),r=ue(e,s),o=ye(n,r,s);return _.acquire(o,async()=>{let l=ce(s),u=new te(ie(n,r,k.env,Me),{requestTimeoutMs:t.requestTimeoutMs,configuration:l}),c=t.readinessDeadlineMs===void 0?null:{afterGeneration:u.serverStatusGeneration(),deadlineMs:t.readinessDeadlineMs},p=await E(()=>d("rust.semantic.worker.initialize",()=>u.initialize({processId:k.pid,rootUri:F(r,"."),capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1},callHierarchy:{dynamicRegistration:!1},hover:{dynamicRegistration:!1}}},initializationOptions:l},{timeoutMs:t.requestTimeoutMs,deadlineMs:t.readinessDeadlineMs}),()=>({linkedProjects:s.length,relativePaths:i.length})),()=>u.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}));return{key:o,client:u,capabilities:p.capabilities,openedPaths:new Set,initializationReadiness:c}},l=>l.client.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}))}async function je(e,n){let i=W(n).filter(c=>e.openedPaths.has(c.relativePath)?!1:Te(Ce(n.projectRoot,c.relativePath)));if(i.length===0)return await Se(e),0;let t=e.initializationReadiness,s=n.readinessDeadlineMs===void 0?null:{statusSnapshot:t?null:e.client.serverStatusSnapshot(),initializationGeneration:t?.afterGeneration,deadlineMs:n.readinessDeadlineMs},r=fe(e.client,n.projectRoot,i);for(let c of i)e.openedPaths.add(c.relativePath);let o=n.diagnosticsTimeoutMs??1e4,l=o;await d("rust.semantic.worker.diagnostics",()=>s?G(c=>(l=c,S(e.client,r,c)),o,s.deadlineMs):S(e.client,r,o),()=>({openedDocuments:r.length,timeoutMs:l}));let u=n.settleDelayMs??5e3;if(!s)await d("rust.semantic.worker.settle",()=>D(u),()=>({openedDocuments:r.length,settleDelayMs:u}));else{let c;await d("rust.semantic.worker.readiness",async()=>{let p=m=>d("rust.semantic.worker.settle",()=>D(m),()=>({openedDocuments:r.length,settleDelayMs:m})),f=s.initializationGeneration===void 0?await N(e.client,s.statusSnapshot,r.length,s.deadlineMs,u,Date.now,p):await C(e.client,s.initializationGeneration,r.length,s.deadlineMs,u,Date.now,p);s.initializationGeneration!==void 0&&(e.initializationReadiness=null),c=f?.health},()=>({phase:s.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:r.length,health:c}))}return r.length}async function Ne(e,n,i,t){let s=i.filter(f=>!e.openedPaths.has(f));if(s.length===0)return await Se(e),0;let r=e.initializationReadiness,o=t.readinessDeadlineMs===void 0?null:{statusSnapshot:r?null:e.client.serverStatusSnapshot(),initializationGeneration:r?.afterGeneration,deadlineMs:t.readinessDeadlineMs},l=[];for(let f of s)try{let m=F(n,f);e.client.didOpenTextDocument({uri:m,languageId:"rust",version:1,text:q(n,f,{inputKind:"indexed Rust source file"})}),e.openedPaths.add(f),l.push(m)}catch(m){if(!ee(m))throw m}let u=t.diagnosticsTimeoutMs??1e4,c=u;await d("rust.semantic.worker.diagnostics",()=>o?G(f=>(c=f,S(e.client,l,f)),u,o.deadlineMs):S(e.client,l,u),()=>({openedDocuments:l.length,timeoutMs:c}));let p=t.settleDelayMs??5e3;if(!o)await d("rust.semantic.worker.settle",()=>D(p),()=>({openedDocuments:l.length,settleDelayMs:p}));else{let f;await d("rust.semantic.worker.readiness",async()=>{let m=y=>d("rust.semantic.worker.settle",()=>D(y),()=>({openedDocuments:l.length,settleDelayMs:y})),b=o.initializationGeneration===void 0?await N(e.client,o.statusSnapshot,l.length,o.deadlineMs,p,Date.now,m):await C(e.client,o.initializationGeneration,l.length,o.deadlineMs,p,Date.now,m);o.initializationGeneration!==void 0&&(e.initializationReadiness=null),f=b?.health},()=>({phase:o.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:l.length,health:f}))}return l.length}async function Se(e){let n=e.initializationReadiness;if(!n)return;let i;await d("rust.semantic.worker.readiness",async()=>{i=(await C(e.client,n.afterGeneration,0,n.deadlineMs,0)).health,e.initializationReadiness=null},()=>({phase:"initialize",openedDocuments:0,health:i}))}function Ge(e,n){for(let i of n){let t=se(e,i.uri);if(!(!t||t===".."||t.startsWith("../")||Ie(t)))return t}return null}function Be(e,n){return n.references&&!e.referencesProvider?"rust-analyzer initialized without textDocument/references support.":n.callees&&!e.callHierarchyProvider?"rust-analyzer initialized without call hierarchy support.":n.signatures&&!e.hoverProvider?"rust-analyzer initialized without hover support.":null}function De(e,n){let i=H(e),t=U(e),s=K(e);return{available:!1,reason:n,references:i.map(r=>[r.symbolId,[]]),...e.includeCallees?{callees:t.map(r=>[r.symbolId,[]])}:{},...e.includeSignatures?{signatures:s.map(r=>[r.symbolId,null])}:{}}}async function He(){await _.shutdownAll(e=>e.client.shutdownAndReap())}async function ke(e,n,i){e.deleteIfSame(n),await n.client.shutdownAndReap({deadlineMs:i})}function Ue(e,n,i){if(!e)return;let t=$e(e,n);t.definitions+=1,i.hasReferences&&(t.definitionsWithReferences+=1),t.references+=i.references,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ke(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.references.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithReferences:t.definitionsWithReferences,references:t.references,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function $e(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithReferences:0,references:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function Je(e,n,i){if(!e)return;let t=Ye(e,n);t.definitions+=1,i.hasCallees&&(t.definitionsWithCallees+=1),t.callees+=i.callees,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ve(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.callees.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithCallees:t.definitionsWithCallees,callees:t.callees,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function Ye(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithCallees:0,callees:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function we(e){if(e===void 0||e==="")return null;let n=Number(e);return Number.isInteger(n)&&n>=0?n:null}function Ze(){let e=k.env.SCIP_RUST_SEMANTIC_PARALLEL_OPERATIONS;return e!=="0"&&e!=="false"}function g(e,n,i){ve(e,JSON.stringify(n));let t=new Int32Array(i);Atomics.store(t,0,1),Atomics.notify(t,0)}export{ke as discardRustAnalyzerSession};
2
2
  //# sourceMappingURL=rust-semantic-session-worker.js.map
@@ -1,2 +1,2 @@
1
- import{h as b,i as c,j as d,k as e,l as f,m as g,n as h,o as i,p as j,q as k,r as l,s as m,t as n,u as o,v as p,w as q,x as r}from"./chunk-OLF4MA5W.js";import{a}from"./chunk-ILMHV3KM.js";import"./chunk-5VKBFZZU.js";import"./chunk-7MGU3HPH.js";import"./chunk-EF2R3WNQ.js";import"./chunk-WE5RZHZ7.js";export{q as calleesForDefinition,l as cargoManifestsForDefinitions,i as hoverToRustSignature,h as hoverWithRetry,m as openDefinitionDocuments,p as referencesWithCompletion,o as referencesWithRetry,b as runRustAnalyzerReferenceBatch,a as runWithConcurrency,j as rustAnalyzerInitializationOptions,k as rustAnalyzerSessionRoot,d as rustRequestCalleeDefinitions,c as rustRequestReferenceDefinitions,f as rustRequestSessionDefinitions,e as rustRequestSignatureDefinitions,g as signatureForDefinition,r as sleep,n as waitForOpenedDocuments};
1
+ import{h as b,i as c,j as d,k as e,l as f,m as g,n as h,o as i,p as j,q as k,r as l,s as m,t as n,u as o,v as p,w as q,x as r}from"./chunk-K5G7SPAG.js";import{a}from"./chunk-ILMHV3KM.js";import"./chunk-EXMVF3JR.js";import"./chunk-5IO2APSS.js";import"./chunk-6URCE5QY.js";import"./chunk-4O52YNKL.js";export{q as calleesForDefinition,l as cargoManifestsForDefinitions,i as hoverToRustSignature,h as hoverWithRetry,m as openDefinitionDocuments,p as referencesWithCompletion,o as referencesWithRetry,b as runRustAnalyzerReferenceBatch,a as runWithConcurrency,j as rustAnalyzerInitializationOptions,k as rustAnalyzerSessionRoot,d as rustRequestCalleeDefinitions,c as rustRequestReferenceDefinitions,f as rustRequestSessionDefinitions,e as rustRequestSignatureDefinitions,g as signatureForDefinition,r as sleep,n as waitForOpenedDocuments};
2
2
  //# sourceMappingURL=rust-semantic-worker.js.map
@@ -1,4 +1,4 @@
1
- import { S as SupportedLanguage } from './config-types-BNoC96J3.js';
1
+ import { S as SupportedLanguage } from './config-types-D6X5S68_.js';
2
2
 
3
3
  type WatcherStatus = {
4
4
  state: 'idle';
@@ -0,0 +1,2 @@
1
+ import{a,b}from"./chunk-I5FCDTK2.js";import"./chunk-TAJ6UGCO.js";import"./chunk-BLKYYQ7C.js";import"./chunk-ZZ3MWF33.js";import"./chunk-IGQQUENU.js";import"./chunk-YUKYB54I.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"./chunk-3AC56WAR.js";import"./chunk-M7LAIM77.js";import"./chunk-FWY2PRIF.js";import"./chunk-DRENNWRG.js";import"./chunk-5XEVXVTK.js";import"./chunk-SV2LEFVM.js";import"./chunk-WJOQC4P7.js";import"./chunk-IYBIBMPF.js";import"./chunk-XYLV727H.js";import"./chunk-4NHWNAWQ.js";import"./chunk-2VKB5CMA.js";import"./chunk-ACZDU5GK.js";import"./chunk-R2NOK63J.js";import"./chunk-6URCE5QY.js";import"./chunk-4O52YNKL.js";export{a as ensureSentinelService,b as sentinelEnsureCommandDescriptor};
2
+ //# sourceMappingURL=sentinel-ensure-command-KYYULCFU.js.map
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{d as a,e as b}from"./chunk-WO47BIPY.js";import"./chunk-CIVYHK7U.js";import"./chunk-N3Q3AWGW.js";import"./chunk-B2OB55RR.js";import"./chunk-XZEE23VG.js";import"./chunk-W3FK73MD.js";import"./chunk-RJWAB4VR.js";import"./chunk-D62CTZX6.js";import"./chunk-G2XUZCF2.js";import"./chunk-DUKHVPU5.js";export{a as ensureSentinelService,b as sentinelEnsureCommandDescriptor};
3
+ //# sourceMappingURL=sentinel-ensure-command-RIZA3RY7.js.map
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ import{spawn as Me}from"child_process";import{appendFileSync as Fe,existsSync as x,mkdirSync as Z,realpathSync as w,statSync as ee,unlinkSync as De,utimesSync as $e,writeFileSync as Ue}from"fs";import{createConnection as je}from"net";import{dirname as y,isAbsolute as qe,join as b,resolve as We}from"path";import{fileURLToPath as te}from"url";var T="codebaseiq-sentinel";var O=/^[A-Za-z0-9_.:-]{1,128}$/;var d={connect:250,editSync:300,editAsync:1e4,prompt:2e3,sessionStart:2e3,stopService:2e4,stopSocket:25e3,stopHost:3e4,sessionEnd:1e3},yt={delivery:{"reuse-match":"shadow",unwired:"shadow"},blockOnUnwired:!0,leaseIdleMs:30*6e4,maxPerDelivery:3};import{spawnSync as re}from"child_process";import{win32 as oe}from"path";var ie=3e3,v="CODEBASEIQ_BREAKAWAY_COMMAND_LINE",se=`$ErrorActionPreference = 'Stop'
3
+ $commandLine = $env:${v}
4
+ Remove-Item Env:${v}
5
+ Add-Type -TypeDefinition @'
6
+ using System;
7
+ using System.ComponentModel;
8
+ using System.Runtime.InteropServices;
9
+ public static class CodeBaseIQBreakaway {
10
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
11
+ struct StartupInfo { public int cb; public string reserved, desktop, title; public int x, y, width, height, columns, rows, fill, flags; public short show, reserved2; public IntPtr reserved3, input, output, error; }
12
+ [StructLayout(LayoutKind.Sequential)]
13
+ struct ProcessInformation { public IntPtr process, thread; public int processId, threadId; }
14
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
15
+ static extern bool CreateProcessW(string application, string commandLine, IntPtr processAttributes, IntPtr threadAttributes, bool inheritHandles, uint flags, IntPtr environment, string directory, ref StartupInfo startup, out ProcessInformation info);
16
+ [DllImport("kernel32.dll")]
17
+ static extern bool CloseHandle(IntPtr handle);
18
+ public static void Start(string commandLine) {
19
+ const uint detached = 0x00000008 | 0x00000200;
20
+ const uint breakaway = 0x01000000;
21
+ foreach (uint flags in new uint[] { detached | breakaway, detached }) {
22
+ StartupInfo startup = new StartupInfo();
23
+ startup.cb = Marshal.SizeOf(startup);
24
+ ProcessInformation info;
25
+ if (CreateProcessW(null, commandLine, IntPtr.Zero, IntPtr.Zero, false, flags, IntPtr.Zero, null, ref startup, out info)) {
26
+ CloseHandle(info.thread);
27
+ CloseHandle(info.process);
28
+ return;
29
+ }
30
+ if (Marshal.GetLastWin32Error() != 5) break;
31
+ }
32
+ throw new Win32Exception(Marshal.GetLastWin32Error());
33
+ }
34
+ }
35
+ '@
36
+ [CodeBaseIQBreakaway]::Start($commandLine)
37
+ `,ae=Buffer.from(se,"utf16le").toString("base64");function ce(e){if(e!==""&&!/[\s"]/u.test(e))return e;let t='"',n=0;for(let r of e){if(r==="\\"){n+=1;continue}t+=r==='"'?`${"\\".repeat(n*2+1)}"`:`${"\\".repeat(n)}${r}`,n=0}return`${t}${"\\".repeat(n*2)}"`}function I(e,t,n=process.env){let r=oe.join(n.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe"),o=[e,...t].map(ce).join(" ");return re(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",ae],{env:{...n,[v]:o},stdio:"ignore",timeout:ie,windowsHide:!0}).status===0}import{realpathSync as ge,statSync as he}from"fs";import{posix as ye,win32 as Ee}from"path";import{closeSync as L,fstatSync as E,openSync as N,readFileSync as ue,readSync as le}from"fs";import{createHash as de}from"crypto";var fe=8*1024*1024,_t=64*1024*1024,kt=512*1024*1024,Tt=256*1024*1024,p=class extends Error{constructor(n,r,o,i,s){let a=o==="too-large"?`is ${i} bytes; the safety limit is ${s} bytes`:o==="not-regular"?"is not a regular file":"changed while it was being read";super(`${n} ${JSON.stringify(r)} ${a}`);this.inputKind=n;this.inputPath=r;this.reason=o;this.observedBytes=i;this.limitBytes=s;this.name="BoundedFileReadError"}inputKind;inputPath;reason;observedBytes;limitBytes;code="CODEBASEIQ_BOUNDED_FILE_READ"};function pe(e,t){C(t.maxBytes);let n=String(e),r=N(e,"r");try{let o=E(r);A(o,t,n);let i=ue(r),s=E(r);if(s.dev!==o.dev||s.ino!==o.ino||s.size!==o.size||i.byteLength!==o.size)throw new p(t.inputKind,n,"changed-during-read",s.size,t.maxBytes);return i}finally{L(r)}}function me(e,t,n="utf8"){return pe(e,t).toString(n)}function m(e,t){return me(e,{maxBytes:fe,inputKind:t})}function Se(e,t,n){C(t.maxBytes);let r=String(e),o=N(e,"r");try{let i=E(o);A(i,t,r);let s=Buffer.allocUnsafe(Math.min(1024*1024,Math.max(1,i.size))),a=0;for(;a<i.size;){let u=le(o,s,0,Math.min(s.length,i.size-a),a);if(u===0)break;n(s.subarray(0,u)),a+=u}let c=E(o);if(c.dev!==i.dev||c.ino!==i.ino||c.size!==i.size||a!==i.size)throw new p(t.inputKind,r,"changed-during-read",c.size,t.maxBytes);return a}finally{L(o)}}function P(e,t){let n=de("sha256");return Se(e,t,r=>n.update(r)),n.digest("hex")}function A(e,t,n){if(!e.isFile())throw new p(t.inputKind,n,"not-regular",Number(e.size),t.maxBytes);if(e.size>t.maxBytes)throw new p(t.inputKind,n,"too-large",Number(e.size),t.maxBytes)}function C(e){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`maxBytes must be a non-negative safe integer; received ${e}`)}var B=2*1024*1024,be=new Set(["startup","resume","clear","compact"]),ve=new Set(["Write","Edit","MultiEdit","NotebookEdit"]),Re=new Map([["SessionStart","session-start"],["PostToolUse","edit"],["UserPromptSubmit","prompt"],["Stop","stop"],["SessionEnd","session-end"]]),xe=/^\*\*\* (Add|Update|Delete) File: (.+?)\s*$/,we=/^\*\*\* Move to: (.+?)\s*$/;function F(e,t,n){let r;try{r=JSON.parse(t)}catch{return null}if(!R(r))return null;let o=r.hook_event_name,i=typeof o=="string"?Re.get(o):void 0,s=r.session_id;if(!i||typeof s!="string"||!O.test(s))return null;let a={event:i,session:s,files:[]};if(i==="edit"){let c=r.cwd,u=e==="claude"?_e(r):ke(r);if(a.files=Te(u,n,typeof c=="string"&&c?c:n),a.files.length===0)return null}else if(i==="session-start"){let c=r.source;typeof c=="string"&&be.has(c)&&(a.source=c)}else i==="stop"&&(a.stopHookActive=r.stop_hook_active===!0);return a}function _e(e){let t=e.tool_name,n=e.tool_input;if(typeof t!="string"||!ve.has(t)||!R(n))return[];let r=typeof n.file_path=="string"?n.file_path:n.notebook_path;return typeof r=="string"&&r?[{path:r,change:"write"}]:[]}function ke(e){let t=e.tool_input;if(e.tool_name!=="apply_patch"||!R(t)||typeof t.command!="string")return[];let n=[],r;for(let o of t.command.split(/\r?\n/)){let i=xe.exec(o);if(i){let a={path:i[2],change:i[1]==="Delete"?"delete":"write"};n.push(a),r=i[1]==="Update"?a:void 0;continue}let s=we.exec(o);s&&r&&(r.change="move-from",n.push({path:s[1],change:"move-to"}),r=void 0)}return n}function Te(e,t,n){let r=Ie(t),o=D(t),i=[],s=new Set;for(let a of e){let c=r.resolve(n,a.path),u=r.relative(t,c);if(!u||u===".."||u.startsWith(`..${r.sep}`)||r.isAbsolute(u))continue;let f=Oe(u.split(r.sep).join("/"),c,o,r),l=`${a.change}\0${f}`;if(s.has(l))continue;s.add(l);let k=a.change==="write"||a.change==="move-to"?Le(c):void 0;i.push({path:f,change:a.change,...k?{sha256:k}:{}})}return i}function Oe(e,t,n,r){let o=D(t);if(!n||!o)return e;let i=r.relative(n,o);if(!i||i===".."||i.startsWith(`..${r.sep}`)||r.isAbsolute(i))return e;let s=i.split(r.sep).join("/");return s.toLowerCase()===e.toLowerCase()?s:e}function D(e){try{return ge.native(e)}catch{return}}function Ie(e){return/^[A-Za-z]:[\\/]|^\\\\/.test(e)?Ee:ye}function Le(e){try{let t=he(e);return!t.isFile()||t.size>B?void 0:P(e,{maxBytes:B,inputKind:"edited file"})}catch{return}}function R(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $(e,t,n,r){if("unavailable"in n)return H(t,n.unavailable);if(!n.ok)return H(t,n.reason);let{modelText:o,userText:i,block:s}=n.delivery;switch(t){case"edit":return o?e==="claude"&&r.async?{stdout:"",stderr:o,exitCode:2}:g({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:o}}):S();case"session-start":return M("SessionStart",o,i);case"prompt":return M("UserPromptSubmit",o,i);case"stop":return s&&o?g({decision:"block",reason:o}):i?g({systemMessage:i}):S();case"session-end":return S()}}function H(e,t){return e==="stop"?g({systemMessage:`codebaseiq sentinel unverified: ${t}`}):S()}function M(e,t,n){return!t&&!n?S():g({...t?{hookSpecificOutput:{hookEventName:e,additionalContext:t}}:{},...n?{systemMessage:n}:{}})}function S(){return{stdout:"",stderr:"",exitCode:0}}function g(e){return{stdout:JSON.stringify(e),stderr:"",exitCode:0}}import{createHash as Ne,randomUUID as Bt}from"crypto";import{mkdirSync as Mt,realpathSync as Pe,renameSync as Ft,unlinkSync as Dt,writeFileSync as $t}from"fs";import{homedir as Ae,tmpdir as jt,userInfo as qt}from"os";import{dirname as Kt,join as h}from"path";var U=1*1024*1024,j=4*1024*1024;function q(e=process.env){return h(e.XDG_CACHE_HOME||h(Ae(),".cache"),"codebaseiq")}function W(e){let t=Pe.native(e).replaceAll("\\","/");return process.platform==="win32"&&(t=t.toLowerCase()),Ne("sha256").update(t).digest("hex").slice(0,16)}var Ce=16,Jt=Ce+5;function Be(e,t){return h(e,"sentinel","registry",`${t}.json`)}function K(e,t){return h(e,"sentinel","inbox",`${t}.jsonl`)}function z(e,t){return h(e,"sentinel","ensure",`${t}.stamp`)}function J(e,t){try{let n=JSON.parse(m(Be(e,t),"sentinel registry record")),{pid:r,socketPath:o,serviceVersion:i,projectRoot:s,startedAt:a,token:c}=n;if(typeof r=="number"&&Number.isInteger(r)&&r>0&&typeof o=="string"&&o.length>0&&typeof i=="string"&&typeof s=="string"&&typeof a=="string"&&typeof c=="string"&&c.length>0)return{pid:r,socketPath:o,serviceVersion:i,projectRoot:s,startedAt:a,token:c}}catch{}}function V(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Y(e,t){let n=Buffer.from(JSON.stringify(e),"utf8");if(n.byteLength>t)throw new Error(`sentinel frame of ${n.byteLength} bytes exceeds the ${t}-byte limit`);let r=Buffer.allocUnsafe(4+n.byteLength);return r.writeUInt32LE(n.byteLength,0),n.copy(r,4),r}function X(e,t,n){let r=Buffer.alloc(0),o=!1,i=s=>{o||(o=!0,n(new Error(s)))};return{push(s){if(!o)for(r=r.byteLength===0?s:Buffer.concat([r,s]);r.byteLength>=4;){let a=r.readUInt32LE(0);if(a>e){i(`sentinel frame of ${a} bytes exceeds the ${e}-byte limit`);return}if(r.byteLength<4+a)return;let c=r.subarray(4,4+a);r=r.subarray(4+a);let u;try{u=JSON.parse(c.toString("utf8"))}catch{i("sentinel frame carried invalid JSON");return}if(t(u),o)return}}}}var Ke=".codebaseiq.json",ze="cli-path",Je=500,Ve=3e4,Ye=1024*1024,Xe=500,Ge="unknown",_={stdout:"",stderr:"",exitCode:0};async function Qe(e){try{return await Ze(e)}catch{return _}}async function Ze(e){let t=et(e.argv),n=tt(e.env.CLAUDE_PROJECT_DIR||e.cwd);if(!t||!n)return _;let r=F(t.host,e.stdin,n);if(!r)return _;let o=w.native(n),i=W(o),s=(e.readClientVersion??pt)(),a={protocol:T,version:1,clientVersion:s??Ge,host:t.host,event:r.event,session:r.session,projectRoot:o,...r.files.length>0?{files:r.files}:{},...r.source?{source:r.source}:{},...r.stopHookActive!==void 0?{stopHookActive:r.stopHookActive}:{},wait:t.async&&r.event==="edit"},c=q(e.env),u=nt(r.event,t.async),f=J(c,i),l=await it(rt(f,a,s,u,e.transport??st),u+Je);return"unavailable"in l&&((r.event==="edit"||r.event==="session-start")&&at(c,i,a),r.event!=="session-end"&&ut(z(c,i),e.now())&&(e.spawnEnsure??dt)(o,t.host)),$(t.host,r.event,l,{async:t.async})}function et(e){let t;for(let n=0;n<e.length;n+=1){let r=e[n];r==="--host"?t=e[n+1]:r.startsWith("--host=")&&(t=r.slice(7))}if(!(t!=="claude"&&t!=="codex"))return{host:t,async:e.includes("--async")}}function tt(e){let t=We(e);for(;;){if(x(b(t,Ke)))return t;let n=y(t);if(n===t)return;t=n}}function nt(e,t){switch(e){case"edit":return t?d.editAsync:d.editSync;case"session-start":return d.sessionStart;case"stop":return d.stopSocket;case"prompt":return d.prompt;case"session-end":return d.sessionEnd}}async function rt(e,t,n,r,o){if(!e)return{unavailable:"service not running"};if(!V(e.pid))return{unavailable:`service process ${e.pid} is not running`};let i=await o(e.socketPath,t,{connectMs:d.connect,totalMs:r});return i.ok?ot(i.response,e.token,n):{unavailable:i.reason}}function ot(e,t,n){if(typeof e!="object"||e===null)return{unavailable:"malformed service response"};let{ok:r,serviceVersion:o,reason:i,delivery:s,token:a}=e;return a!==t?{unavailable:"token mismatch"}:n!==void 0&&typeof o=="string"&&o!==n?{unavailable:`service version ${o} != hook ${n}`}:r===!1?{unavailable:typeof i=="string"?i:"service declined the request"}:r!==!0||typeof o!="string"||typeof s!="object"||s===null?{unavailable:"malformed service response"}:e}function it(e,t){return new Promise(n=>{let r=setTimeout(()=>n({unavailable:`hook deadline of ${t}ms exceeded`}),t);e.then(n,o=>n({unavailable:`hook error: ${o instanceof Error?o.message:String(o)}`})).finally(()=>clearTimeout(r))})}var st=(e,t,n)=>new Promise(r=>{let o;try{o=Y(t,U)}catch(l){r({ok:!1,reason:l instanceof Error?l.message:String(l)});return}let i=!1,s=je(e),a=l=>{i||(i=!0,clearTimeout(c),clearTimeout(u),s.destroy(),r(l))},c=setTimeout(()=>a({ok:!1,reason:`connect timed out after ${n.connectMs}ms`}),n.connectMs),u=setTimeout(()=>a({ok:!1,reason:`no response within ${n.totalMs}ms`}),n.totalMs),f=X(j,l=>a({ok:!0,response:l}),l=>a({ok:!1,reason:l.message}));s.on("connect",()=>{clearTimeout(c),s.write(o)}),s.on("data",l=>f.push(l)),s.on("error",l=>a({ok:!1,reason:`service unreachable: ${l.message}`})),s.on("close",()=>a({ok:!1,reason:"service closed the connection without answering"}))});function at(e,t,n){try{let r=K(e,t);if(Z(y(r),{recursive:!0}),ct(r)>=Ye)return;Fe(r,`${JSON.stringify(n)}
38
+ `)}catch{}}function ct(e){try{return ee(e).size}catch{return 0}}function ut(e,t){try{return Z(y(e),{recursive:!0}),G(e,t)?!0:Math.abs(t-ee(e).mtimeMs)<Ve?!1:(De(e),G(e,t))}catch{return!1}}function G(e,t){try{Ue(e,"",{flag:"wx"})}catch(n){if(n.code==="EEXIST")return!1;throw n}return $e(e,new Date(t),new Date(t)),!0}function lt(e,t=ne()){let n=ft(t);return n?{command:process.execPath,args:[n,"__sentinel-ensure-service",e]}:void 0}function dt(e,t){let n=lt(e);if(!n||process.platform==="win32"&&t==="codex"&&I(n.command,n.args))return;let r=Me(n.command,n.args,{stdio:"ignore",detached:!0,windowsHide:!0});r.on("error",()=>{}),r.unref()}function ft(e){try{let n=m(b(e,ze),"sentinel hook CLI path").trim();if(qe(n)&&x(n))return n}catch{}let t=b(e,"cli.js");return x(t)?t:void 0}function ne(){return y(te(import.meta.url))}function pt(){return mt(ne())}function mt(e){let t=e;for(;;){try{let r=JSON.parse(m(b(t,"package.json"),"package manifest"));if(r.name==="codebaseiq"&&typeof r.version=="string")return r.version}catch{}let n=y(t);if(n===t)return;t=n}}async function St(){let e=await Qe({argv:process.argv.slice(2),stdin:await gt(),env:process.env,cwd:process.cwd(),now:()=>Date.now()});await Q(process.stdout,e.stdout),await Q(process.stderr,e.stderr),process.exit(e.exitCode)}function gt(){return new Promise(e=>{let t=[],n=()=>{clearTimeout(r),e(Buffer.concat(t).toString("utf8"))},r=setTimeout(n,Xe);process.stdin.on("data",o=>t.push(o)),process.stdin.on("end",n),process.stdin.on("error",n)})}function Q(e,t){return new Promise(n=>{t?e.write(t,()=>n()):n()})}function ht(){if(!process.argv[1])return!1;let e=te(import.meta.url);try{return w(e)===w(process.argv[1])}catch{return e===process.argv[1]}}ht()&&await St();export{lt as ensureServiceCommand,mt as readPackageVersion,ft as resolveCliEntry,Qe as runHook};
39
+ //# sourceMappingURL=sentinel-hook.js.map