codebaseiq 0.3.0 → 0.4.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.
- package/CHANGELOG.md +80 -0
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-7GAK2F3H.js → chunk-23AD24QZ.js} +12 -12
- package/dist/chunk-24TEZJST.js +2 -0
- package/dist/{chunk-356EZBIP.js → chunk-26EDDGAX.js} +2 -2
- package/dist/{chunk-O2M3VNDY.js → chunk-26EZWQ24.js} +2 -2
- package/dist/{chunk-U33PMPNW.js → chunk-2L3NCI52.js} +2 -2
- package/dist/{chunk-MSI3K7PJ.js → chunk-2QJAVISG.js} +2 -2
- package/dist/{chunk-4LK5OIPW.js → chunk-2ZBZRYX4.js} +2 -2
- package/dist/chunk-33AXWMO2.js +2 -0
- package/dist/{chunk-EQNMD62X.js → chunk-37K55EG3.js} +2 -2
- package/dist/{chunk-ITSJMNUD.js → chunk-3EFZ5KQ4.js} +2 -2
- package/dist/{chunk-D7DOB27N.js → chunk-3F23W57G.js} +2 -2
- package/dist/{chunk-BGGB5N53.js → chunk-3GKKCVKK.js} +2 -2
- package/dist/{chunk-MQW6SJ4P.js → chunk-3SYRGMCL.js} +2 -2
- package/dist/{chunk-PFC44E6D.js → chunk-3VDL7GTY.js} +2 -2
- package/dist/{chunk-7JELP5YE.js → chunk-3XBZ5PKL.js} +2 -2
- package/dist/{chunk-75KJGYX7.js → chunk-42PXSE74.js} +2 -2
- package/dist/{chunk-FEIZXBLH.js → chunk-4GIERC2P.js} +2 -2
- package/dist/{chunk-W7YLRXZE.js → chunk-4UXDBRIF.js} +2 -2
- package/dist/chunk-4XMZYLW5.js +2 -0
- package/dist/{chunk-6BF3VYEF.js → chunk-55NUXP2V.js} +2 -2
- package/dist/chunk-5AJQCOZZ.js +21 -0
- package/dist/{chunk-5DSL3NT2.js → chunk-5NUPFZFA.js} +2 -2
- package/dist/{chunk-RJVAPMHF.js → chunk-65QIFIF6.js} +2 -2
- package/dist/{chunk-36JC5BG2.js → chunk-66Q5VLH6.js} +2 -2
- package/dist/{chunk-D7AZAOZX.js → chunk-6CQPIIS7.js} +2 -2
- package/dist/{chunk-GV2CEZCW.js → chunk-6CTSFS7R.js} +2 -2
- package/dist/{chunk-Q4XEU3UH.js → chunk-6EBUAKJT.js} +2 -2
- package/dist/chunk-6I55VYFG.js +4 -0
- package/dist/chunk-6NUURWPF.js +3 -0
- package/dist/{chunk-MHWMEZDA.js → chunk-6P5QMOM7.js} +2 -2
- package/dist/{chunk-LZSQ6X7E.js → chunk-6S5FE4ZF.js} +2 -2
- package/dist/chunk-74LRKLNC.js +22 -0
- package/dist/chunk-75A23IID.js +3 -0
- package/dist/chunk-75VNTSO6.js +7 -0
- package/dist/chunk-7HBBVZJ6.js +3 -0
- package/dist/{chunk-VWYGCMV5.js → chunk-7PPBMBH6.js} +2 -2
- package/dist/{chunk-3RSBGWGL.js → chunk-7WG57A5X.js} +2 -2
- package/dist/{chunk-FWQGH2N2.js → chunk-7XHZX6FX.js} +2 -2
- package/dist/{chunk-RIYJ4L33.js → chunk-A5HJ3CJW.js} +2 -2
- package/dist/{chunk-LONKINMJ.js → chunk-AJ5HVC5Z.js} +2 -2
- package/dist/{chunk-ZAFGY22Q.js → chunk-AYRHOFLV.js} +2 -2
- package/dist/chunk-AZDY3EKD.js +93 -0
- package/dist/{chunk-CW6AXOLR.js → chunk-AZZNG5Z2.js} +2 -2
- package/dist/chunk-BEKCTUPY.js +3 -0
- package/dist/{chunk-CR3OG6SQ.js → chunk-BKKX2OU5.js} +2 -2
- package/dist/{chunk-5LL4KEHO.js → chunk-BQKRYKDD.js} +2 -2
- package/dist/{chunk-FOZ74V56.js → chunk-BVDQU2XJ.js} +2 -2
- package/dist/chunk-C3PPB2T5.js +5 -0
- package/dist/chunk-CABIZQXQ.js +21 -0
- package/dist/{chunk-M2Y6PCFE.js → chunk-CAH322MC.js} +2 -2
- package/dist/{chunk-EIBGSU2R.js → chunk-CBOOHUK4.js} +2 -2
- package/dist/chunk-CFIICAOM.js +2 -0
- package/dist/{chunk-XMJ53WG4.js → chunk-CPWYEPWQ.js} +2 -2
- package/dist/{chunk-LQHYYIOB.js → chunk-CRT7I7RJ.js} +2 -2
- package/dist/{chunk-IZDPGOZR.js → chunk-CZVSQQDU.js} +2 -2
- package/dist/{chunk-TNJGTQWO.js → chunk-D3KE26FS.js} +2 -2
- package/dist/{chunk-GP7C5VAE.js → chunk-DNRHRVKS.js} +2 -2
- package/dist/{chunk-SGMNWYTH.js → chunk-DOQLO74K.js} +2 -2
- package/dist/{chunk-AURCQHSG.js → chunk-DP3EJ6XL.js} +2 -2
- package/dist/{chunk-C7QWUBR2.js → chunk-DQZF7MP6.js} +2 -2
- package/dist/{chunk-E52K4L2W.js → chunk-DTM4EHD2.js} +2 -2
- package/dist/{chunk-YRKP7PM7.js → chunk-DUM7GR6B.js} +2 -2
- package/dist/{chunk-I22IZYDI.js → chunk-DZ4QOIRY.js} +2 -2
- package/dist/{chunk-EXZ7VLRY.js → chunk-E3R6TJ5T.js} +2 -2
- package/dist/chunk-E4DP45YU.js +3 -0
- package/dist/{chunk-PUVNH4PO.js → chunk-E5U6N5WI.js} +2 -2
- package/dist/chunk-E7T22WET.js +21 -0
- package/dist/{chunk-QEOWONKY.js → chunk-ED7ZAZ5V.js} +2 -2
- package/dist/{chunk-RCIGX23V.js → chunk-EDMG5CSO.js} +2 -2
- package/dist/{chunk-IHSLIIL3.js → chunk-EOSUV7H5.js} +2 -2
- package/dist/{chunk-FQTIFWLR.js → chunk-ESWVTSHU.js} +2 -2
- package/dist/{chunk-6VREELBC.js → chunk-ETZBIG6K.js} +2 -2
- package/dist/chunk-EYSJHKX6.js +3 -0
- package/dist/{chunk-Q23IMHXS.js → chunk-F4AGM7ZE.js} +37 -37
- package/dist/{chunk-FTTV7IRX.js → chunk-FPUJRBHL.js} +50 -50
- package/dist/{chunk-CCIYWXX6.js → chunk-G2UU6PQP.js} +2 -2
- package/dist/{chunk-C6WKPKCF.js → chunk-G3KRXNNT.js} +2 -2
- package/dist/{chunk-TEANKHUU.js → chunk-G3ZBP72R.js} +2 -2
- package/dist/{chunk-NBCQZSGR.js → chunk-GC4I33OD.js} +2 -2
- package/dist/{chunk-NDKOVQFG.js → chunk-GLXEWYQY.js} +2 -2
- package/dist/{chunk-AEXQYQD7.js → chunk-GRHNPFHT.js} +2 -2
- package/dist/{chunk-NBZKSTXP.js → chunk-GWESWURK.js} +2 -2
- package/dist/{chunk-Q3ZCQY2Y.js → chunk-GXOFPAIR.js} +2 -2
- package/dist/{chunk-USOAJHY7.js → chunk-H4FGIFEU.js} +2 -2
- package/dist/{chunk-LKUTSP4G.js → chunk-HOGS6JFP.js} +2 -2
- package/dist/{chunk-UQE4XFSA.js → chunk-HSJLK5MC.js} +2 -2
- package/dist/{chunk-BWL3PMPT.js → chunk-HTPEUJ42.js} +2 -2
- package/dist/{chunk-3RR2K7EZ.js → chunk-IBPXUGJV.js} +2 -2
- package/dist/{chunk-BFBIMTCJ.js → chunk-ITA3N7G6.js} +2 -2
- package/dist/chunk-JG5OWAEB.js +22 -0
- package/dist/{chunk-2PRONPAS.js → chunk-JGJKRTTB.js} +2 -2
- package/dist/{chunk-TJWVT4DO.js → chunk-JGXLB7PR.js} +2 -2
- package/dist/{chunk-K7JLSGCJ.js → chunk-JKUF2UG6.js} +3 -3
- package/dist/{chunk-CIYA2KZN.js → chunk-JOYASZRF.js} +2 -2
- package/dist/{chunk-U7NUXDQO.js → chunk-K3PFL5QQ.js} +2 -2
- package/dist/{chunk-WK2IQJPK.js → chunk-KAXBWTSX.js} +2 -2
- package/dist/{chunk-5ZI2PPI7.js → chunk-KHHAGHAW.js} +2 -2
- package/dist/{chunk-UW6KD57C.js → chunk-KJLUQVBG.js} +2 -2
- package/dist/{chunk-WWCV4E6J.js → chunk-KOVUXHIZ.js} +2 -2
- package/dist/chunk-KPMMOAV5.js +4 -0
- package/dist/{chunk-GDHWOA57.js → chunk-LKJZNGMA.js} +2 -2
- package/dist/{chunk-3VJ3OCRE.js → chunk-LMPOC372.js} +2 -2
- package/dist/{chunk-F3QSL4W2.js → chunk-LTPNP6D5.js} +2 -2
- package/dist/{chunk-MVRGB4KJ.js → chunk-M3IBH6C3.js} +9 -9
- package/dist/{chunk-PHNCEUXX.js → chunk-MAGBSB6E.js} +2 -2
- package/dist/{chunk-QMOZZ2VX.js → chunk-MFMHD36E.js} +2 -2
- package/dist/{chunk-LMTSB3TB.js → chunk-MJX2J5QE.js} +2 -2
- package/dist/{chunk-PTQPPPG2.js → chunk-N26LGGSF.js} +2 -2
- package/dist/{chunk-J7AMBVWF.js → chunk-NB2DAVPP.js} +2 -2
- package/dist/{chunk-JYI7CV25.js → chunk-NJDXNYLG.js} +2 -2
- package/dist/{chunk-BRQL7AFJ.js → chunk-NMKQOIYZ.js} +2 -2
- package/dist/{chunk-ICUL7XRT.js → chunk-NRNVMB2R.js} +2 -2
- package/dist/{chunk-DDN2F6GB.js → chunk-O5BWFNIH.js} +2 -2
- package/dist/{chunk-HVFB3PME.js → chunk-O7PCDZ5B.js} +2 -2
- package/dist/{chunk-KPZGTB2O.js → chunk-OAJYNPRU.js} +2 -2
- package/dist/{chunk-2EDX3JT5.js → chunk-OFUC6R46.js} +2 -2
- package/dist/chunk-OSZ7PW5K.js +5 -0
- package/dist/{chunk-B3UYV66Z.js → chunk-OZ2M2X7A.js} +2 -2
- package/dist/{chunk-6O3KXIDL.js → chunk-OZI44VCR.js} +2 -2
- package/dist/{chunk-XN3EKMLI.js → chunk-PCKIKOUA.js} +2 -2
- package/dist/{chunk-NCJILOAK.js → chunk-PFMQRHC6.js} +2 -2
- package/dist/chunk-PVKSZBX5.js +82 -0
- package/dist/{chunk-NEWHKGVD.js → chunk-QANCT4MO.js} +2 -2
- package/dist/{chunk-ZNH33XIB.js → chunk-QEWN7BLP.js} +2 -2
- package/dist/{chunk-OQUCBKOI.js → chunk-QFJ46F6F.js} +2 -2
- package/dist/{chunk-2E6OUPCF.js → chunk-QPQWR6CW.js} +2 -2
- package/dist/{chunk-YTJHCGYB.js → chunk-QX4HDF2I.js} +2 -2
- package/dist/{chunk-J3GLP7Q5.js → chunk-R2F2CTBA.js} +2 -2
- package/dist/{chunk-2OMXFE64.js → chunk-R7PXHYMY.js} +2 -2
- package/dist/{chunk-F74LZWCE.js → chunk-RGBZDOUO.js} +2 -2
- package/dist/{chunk-362QOSFD.js → chunk-RNPG5P4P.js} +2 -2
- package/dist/{chunk-D62CTZX6.js → chunk-RS6UYNEP.js} +2 -2
- package/dist/{chunk-VGWZ4MOY.js → chunk-RVBRPBLQ.js} +2 -2
- package/dist/{chunk-5IZRKWTZ.js → chunk-RWAZCEJD.js} +2 -2
- package/dist/{chunk-ZQ62NNKN.js → chunk-RWDIONS7.js} +2 -2
- package/dist/{chunk-HQA7EBSK.js → chunk-S3CJYDXP.js} +2 -2
- package/dist/{chunk-GL6UTNUB.js → chunk-S6UTKCBT.js} +2 -2
- package/dist/chunk-SLLFJXTW.js +27 -0
- package/dist/{chunk-TOTWJZIX.js → chunk-T3KTMLQT.js} +2 -2
- package/dist/{chunk-67VJAYVR.js → chunk-TB575ZGO.js} +2 -2
- package/dist/{chunk-YHPG3S2U.js → chunk-TG4GMU73.js} +2 -2
- package/dist/{chunk-CVHOQONG.js → chunk-THKM7OXM.js} +2 -2
- package/dist/{chunk-GVAF222T.js → chunk-TNLOX4TN.js} +2 -2
- package/dist/{chunk-HENP2O4A.js → chunk-UHFZDQZJ.js} +2 -2
- package/dist/{chunk-YT4DVWUV.js → chunk-UUMAM5LM.js} +2 -2
- package/dist/{chunk-JX6ZWDOS.js → chunk-UUT5P3V7.js} +2 -2
- package/dist/{chunk-Z6RL7XOE.js → chunk-VEPK6M5C.js} +2 -2
- package/dist/{chunk-C7OUW52M.js → chunk-VPCHKZ3I.js} +2 -2
- package/dist/{chunk-GIDCP7KV.js → chunk-VZY3XOBU.js} +2 -2
- package/dist/{chunk-XQAVQVIL.js → chunk-W6E6ME7G.js} +2 -2
- package/dist/{chunk-XQPPURLQ.js → chunk-WGYZBS5S.js} +2 -2
- package/dist/{chunk-GUFPEFBG.js → chunk-WUP24Q4U.js} +2 -2
- package/dist/chunk-WXUHXSLN.js +2 -0
- package/dist/{chunk-HINZQKSY.js → chunk-X4YZD2MP.js} +2 -2
- package/dist/chunk-XARPGCTL.js +2 -0
- package/dist/{chunk-5FWR5HLG.js → chunk-XDQ6QJF5.js} +20 -20
- package/dist/{chunk-JCMFBF4Z.js → chunk-XRH7R5SX.js} +2 -2
- package/dist/{chunk-BBP7HVBJ.js → chunk-XVJ2E7W7.js} +2 -2
- package/dist/{chunk-D53LWANR.js → chunk-Y7GFAU5N.js} +2 -2
- package/dist/{chunk-T6MQNNAC.js → chunk-YBDLHFZZ.js} +2 -2
- package/dist/{chunk-ZB4C5TTR.js → chunk-YI3CJPOY.js} +2 -2
- package/dist/chunk-YMAGXBLT.js +3 -0
- package/dist/{chunk-MZNMASFM.js → chunk-YRAGNEBZ.js} +2 -2
- package/dist/chunk-YXZAAQHZ.js +3 -0
- package/dist/chunk-Z2L5H2HF.js +3 -0
- package/dist/{chunk-JSNTHRLQ.js → chunk-ZHK7TVAJ.js} +2 -2
- package/dist/chunk-ZJNV27DZ.js +4 -0
- package/dist/{chunk-GQLDYCWS.js → chunk-ZQ6GAIUV.js} +2 -2
- package/dist/{chunk-TPO7XC5Z.js → chunk-ZQE2QYAC.js} +2 -2
- package/dist/chunk-ZUQ2MDFT.js +2 -0
- package/dist/cli-context-4R2LREXQ.js +3 -0
- package/dist/cli-context-6X7JYARX.js +2 -0
- package/dist/cli-failure-RECEHOM2.js +3 -0
- package/dist/cli-program-MXA3WTAO.js +7 -0
- package/dist/cli.js +1 -1
- package/dist/{code-viewer-VHLBLIUM.js → code-viewer-C6HE4DFC.js} +2 -2
- package/dist/{code-viewer-KIXEYQNJ.js → code-viewer-XHSSAMBX.js} +2 -2
- package/dist/{command-descriptors-YCLATF5I.js → command-descriptors-NWW34Z54.js} +171 -171
- package/dist/{command-descriptors-F5P2V3NW.js → command-descriptors-XHK3PK2I.js} +116 -116
- package/dist/{command-panels-SZONPMLJ.js → command-panels-OXMCJ2QZ.js} +2 -2
- package/dist/direct-navigation-236VXYBZ.js +3 -0
- package/dist/direct-navigation-36YSILY6.js +2 -0
- package/dist/index.js +1 -1
- package/dist/invocation-command-descriptors-35JULLNR.js +3 -0
- package/dist/invocation-command-descriptors-FEWSFUO2.js +2 -0
- package/dist/output-continuation-command-MJBVH3A5.js +2 -0
- package/dist/output-continuation-command-TBXIOPHQ.js +3 -0
- package/dist/project-reindex-5TCGOVSK.js +2 -0
- package/dist/project-reindex-BUNTSYKM.js +3 -0
- package/dist/queries/affected.js +1 -1
- package/dist/queries/anchors.js +1 -1
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/context.js +1 -1
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/dependence-slice.js +1 -1
- package/dist/queries/dependency-depth.js +1 -1
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/entry-map.js +1 -1
- package/dist/queries/evidence.js +1 -1
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.js +1 -1
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/reference-neighborhood.js +1 -1
- package/dist/queries/reference-reachability.js +1 -1
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.js +1 -1
- package/dist/queries/source-inspection.js +1 -1
- package/dist/queries/source-search.js +1 -1
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system-map.js +1 -1
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/value-flow.js +1 -1
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +1 -1
- package/dist/reindex.js +30 -30
- package/dist/runtime.js +1 -1
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/sentinel-ensure-command-3MZCLPQY.js +2 -0
- package/dist/sentinel-ensure-command-LEWHIRLL.js +3 -0
- package/dist/sentinel-worker.js +1 -1
- package/dist/typescript-mailbox-worker.js +1 -1
- package/dist/watch-server.js +6 -6
- package/docs/COMMAND_REFERENCE.md +2 -2
- package/docs/SECURITY_MODEL.md +3 -0
- package/package.json +1 -1
- package/skills/codebaseiq/SKILL.md +15 -3
- package/dist/chunk-23C5AD3B.js +0 -2
- package/dist/chunk-2I2UHZET.js +0 -2
- package/dist/chunk-5IC2WZAL.js +0 -22
- package/dist/chunk-5T44HG5Y.js +0 -88
- package/dist/chunk-6JMAVFL4.js +0 -3
- package/dist/chunk-6WAPPQ5F.js +0 -82
- package/dist/chunk-7UCDGXRW.js +0 -8
- package/dist/chunk-AQI4N64O.js +0 -22
- package/dist/chunk-DAKIGMIK.js +0 -21
- package/dist/chunk-DUKHVPU5.js +0 -4
- package/dist/chunk-DVWO7RBC.js +0 -2
- package/dist/chunk-FH5WG4LE.js +0 -2
- package/dist/chunk-GQXXOS55.js +0 -2
- package/dist/chunk-GWYZVVKY.js +0 -21
- package/dist/chunk-JFIA2JI3.js +0 -3
- package/dist/chunk-JLZLLLW5.js +0 -3
- package/dist/chunk-MEUHIDI3.js +0 -7
- package/dist/chunk-OFGOOL6U.js +0 -3
- package/dist/chunk-P4NVCOM7.js +0 -2
- package/dist/chunk-SMDIEDM4.js +0 -27
- package/dist/chunk-SX72EVMY.js +0 -3
- package/dist/chunk-T5X7DK6C.js +0 -3
- package/dist/chunk-T75DS2E6.js +0 -21
- package/dist/chunk-TJBOJUVN.js +0 -3
- package/dist/chunk-UC2FD2PS.js +0 -4
- package/dist/chunk-UQYQBLJX.js +0 -5
- package/dist/chunk-Z35GOVEH.js +0 -2
- package/dist/cli-context-FJL2JHOE.js +0 -3
- package/dist/cli-context-PQNWHMCQ.js +0 -2
- package/dist/cli-program-UO7PZD6V.js +0 -7
- package/dist/direct-navigation-4XJTXIDT.js +0 -2
- package/dist/direct-navigation-J5MVYYAD.js +0 -3
- package/dist/invocation-command-descriptors-RWV4VAI4.js +0 -2
- package/dist/invocation-command-descriptors-U76PN7IY.js +0 -3
- package/dist/output-continuation-command-BL25S26S.js +0 -3
- package/dist/output-continuation-command-BTETTXEC.js +0 -2
- package/dist/project-reindex-CRJU3IFG.js +0 -2
- package/dist/project-reindex-TQFCOA2O.js +0 -3
- package/dist/sentinel-ensure-command-OSWGCFFL.js +0 -3
- package/dist/sentinel-ensure-command-SPW7XQLB.js +0 -2
|
@@ -8,8 +8,8 @@ commands:
|
|
|
8
8
|
when: 'Locate compiler-owned constructs in a known file.'
|
|
9
9
|
- template: 'codebaseiq entrypoints <text>'
|
|
10
10
|
when: 'Locate an external callable root when its entry surface is known.'
|
|
11
|
-
- template: 'codebaseiq evidence --symbol <symbol> --edge <family> --direction <direction>
|
|
12
|
-
when: 'Project explicitly selected typed relationships from one exact root.'
|
|
11
|
+
- template: 'codebaseiq evidence --symbol <symbol> --edge <family> --direction <direction>'
|
|
12
|
+
when: 'Project explicitly selected typed relationships from one exact root; add --depth <n> or --max-edges <n> only to change the 2/32 defaults.'
|
|
13
13
|
- template: 'codebaseiq inspect --at <file:line> --view behavior'
|
|
14
14
|
when: 'Read connected behavior for a named implementation gap.'
|
|
15
15
|
- template: 'codebaseiq code <selector>'
|
|
@@ -32,7 +32,7 @@ commands:
|
|
|
32
32
|
| `codebaseiq search <text>` | Locate exact repository text, a runtime key, or a compiler symbol; use \`codebaseiq search -- <text>\` when the literal starts with a dash. |
|
|
33
33
|
| `codebaseiq outline <file>` | Locate compiler-owned constructs in a known file. |
|
|
34
34
|
| `codebaseiq entrypoints <text>` | Locate an external callable root when its entry surface is known. |
|
|
35
|
-
| `codebaseiq evidence --symbol <symbol> --edge <family> --direction <direction
|
|
35
|
+
| `codebaseiq evidence --symbol <symbol> --edge <family> --direction <direction>` | Project explicitly selected typed relationships from one exact root; add --depth <n> or --max-edges <n> only to change the 2/32 defaults. |
|
|
36
36
|
| `codebaseiq inspect --at <file:line> --view behavior` | Read connected behavior for a named implementation gap. |
|
|
37
37
|
| `codebaseiq code <selector>` | Read exact source only when syntax itself can change the decision. |
|
|
38
38
|
| `codebaseiq diff-impact` | Map changed symbols and downstream consumers after an edit. |
|
|
@@ -72,4 +72,16 @@ Read request, observed facts, calibration, coverage, and recovery together. A co
|
|
|
72
72
|
|
|
73
73
|
Before answering, compare the draft to the selected statement-complete behavior—not merely to a remembered narrative. Preserve every observed behavior-changing predicate, returned default, separately merged field, cache invalidation, and cleanup effect that is material to the question. When two named fields use different merge or lifecycle operations, do not collapse them into a generic word such as “properties.” If the evidence already contains a missing detail, repair the answer; do not reopen exploration.
|
|
74
74
|
|
|
75
|
+
Choose `evidence` controls deliberately. Any exact symbol or `file:line` returned by a locator is immediately usable as a graph root, and for an end-to-end question include the initiating owner as a root or request incoming execution capable of exposing it; do not assume a core type is the ingress. Use `--subtype <subtype>` and `--connecting` only when the selected roots themselves must be connected, and `--inventory-only` only when counts must decide whether a predictably large projection is worth materializing. Never request every family merely to discover what exists. Execution calls and exact runtime handoffs establish executable reachability; dataflow, state, temporal, contract, identity, ownership, and dependency edges say what a path carries, changes, orders, constrains, identifies, contains, or relies on, and they do not become call claims. Exact edges are facts only within their stated coverage; candidate edges are leads that need source confirmation.
|
|
76
|
+
|
|
77
|
+
Read every packet as a coverage contract. `accounted` means the bounded projection reports every omission; `bounded` means eligible edges were placed in stable recoverable folds by the output budget; `incomplete` means a selector or provider could not be resolved. None of them proves the user task complete, and missing output is not evidence of absence. Before claiming a complete relationship set or an absence, inspect coverage and use `--full` only when complete coverage can change the decision. Before claiming what every callsite passes, read the `trace` or `evidence` claim-support section: only an eligible callsite-argument claim is backed by complete syntactic invocations.
|
|
78
|
+
|
|
79
|
+
Preserve what the evidence shows about state. For a multi-step mutation, keep later compaction, rollback, and cleanup; for every event, log, or outbox write, keep its operation and record identity; for coordination, state the lock scope and which checks and writes occur inside it, and whether interruption is prevented, atomic, rolled back, or repaired later. For a tiered policy or dispatcher, keep the precedence of its tiers and the exact scope of every bypass; never imply that a later bypass can skip an earlier hard rejection unless the rendered condition proves it. For a stateful owner, keep its lifetime and sharing scope: singleton, shared registry, per-session instance, or per-invocation value. Resolve exact constant values when they can change the answer.
|
|
80
|
+
|
|
81
|
+
Prefer human output for agent reading; use `--json --result-only` only for a programmatic consumer, and never rerun a successful human command as JSON. With an explicit `CODEBASEIQ_SESSION`, a complete source unit, a byte-identical subset of a prior exact source read, or a graph unit or edge may be replaced by a visible receipt from the same index generation; changed bytes, changed graph content, a new generation, or `--reemit` force full evidence again.
|
|
82
|
+
|
|
75
83
|
Use codebaseiq rather than a parallel grep/read workflow for tracked text. Native tools are for edits, checks, binary content, or an explicitly reported unsupported gap. After edits, use `diff-impact` when consumers matter, `architecture` for declared boundaries, and `health` for quality or cleanup analysis. Before adding a new helper, run `codebaseiq reuse` with `--term`, `--name`, and `--calls` probes you choose; its results are heuristic candidates to confirm with `code` or `evidence`, not exact facts.
|
|
84
|
+
|
|
85
|
+
In a sandbox that can read but not write the codebaseiq cache (an `EPERM` or `EACCES` naming `~/.cache/codebaseiq`), set `CODEBASEIQ_READ_ONLY=1` instead of falling back to grep. Read-only mode answers from the existing index, never reindexes or starts services, and appends a `STALE OVERLAY` section when the index is older than the working tree. If the checkout has no index of its own, set `CODEBASEIQ_CACHE_DIR` to the cache directory of a checkout that has one (for a worktree, the main checkout's). The session ledger still writes under `CODEBASEIQ_SESSION_DIR` (default: the OS temp directory); point it at a writable directory or pass `--no-session`.
|
|
86
|
+
|
|
87
|
+
During a refactor every edit makes the index stale, and a stale index otherwise waits for a reindex before answering (minutes on a large Rust crate). Set `CODEBASEIQ_ALLOW_STALE=1` to answer from the last good index instead; read-only mode implies it. The `STALE OVERLAY` section then lists the files changed since that index was built: results that cite one of them are stale, and changed files the result does not cite may hold callers or references the index cannot show. Re-read changed files with `code`, which always reads current bytes, and run `codebaseiq reindex` when exact graph evidence for them decides the answer. A new or dirty worktree with no index of its own forks the shared baseline of HEAD or its nearest first-parent ancestor instead of indexing from scratch; when a repository has no such baseline because no checkout is ever clean, publish one with `codebaseiq reindex --base origin/main` (any ref) outside the sandbox.
|
package/dist/chunk-23C5AD3B.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{e as n}from"./chunk-MVRGB4KJ.js";function s(o,r,t,e){return n({projectRoot:o,languages:e.languages?.length?e.languages:r.languages,outputScip:t.indexPath,outputDb:t.dbPath,pnpmWorkspaces:r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,clojureConfigPath:r.indexer?.clojure?.configPath,skipIfUnchanged:e.force!==!0,allowPartial:e.allowPartial===!0,skipAutoInstall:e.skipAutoInstall===!0,installMissing:e.installMissing===!0,trustProjectTools:e.trustProjectTools===!0,indexerConcurrency:e.indexerConcurrency??r.indexerConcurrency,trigger:e.trigger,...e.onStatus?{onStatus:e.onStatus}:{}})}export{s as a};
|
|
2
|
-
//# sourceMappingURL=chunk-23C5AD3B.js.map
|
package/dist/chunk-2I2UHZET.js
DELETED
package/dist/chunk-5IC2WZAL.js
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{Z as Ne,_ as Le}from"./chunk-C7QWUBR2.js";import{H as O,M as De,ha as Me,l as ne,m as qe,n as R,o as Oe,p as Pe,w as A,x as He,y as _e}from"./chunk-7UCDGXRW.js";import{a as Q,b as X,d as w,e as T,f as we}from"./chunk-D62CTZX6.js";import{J as q,N as Z,O as Ce,P as ee,Q as Ie,V as We,X as Te,Y as te,c as Y,d as Re,e as Ae,o as g,r as Ee}from"./chunk-5T44HG5Y.js";import{C as x,e as ke,g as B,h as Se,i as k,j as V,k as be,p as K,r as f,w as xe,x as J,y as z}from"./chunk-DUKHVPU5.js";import{existsSync as h,mkdirSync as Rt,rmdirSync as At,unlinkSync as Et}from"fs";import{homedir as Ct}from"os";import{basename as Ke,dirname as D,isAbsolute as It,join as l,resolve as oe}from"path";import{fileURLToPath as Wt}from"url";var $e=["- `codebaseiq search <exact-text>` \u2014 Where does this exact text occur in current project text, and which aligned compiler symbol owns each line? Requires: One exact text literal or deliberately bounded regular expression; insert `--` before a literal that starts with a dash.","- `codebaseiq outline <file>` \u2014 What symbols and nesting exist in this file? Requires: One exact current project file path.","- `codebaseiq entrypoints [text]` \u2014 Which detected external roots or entry-surface candidates match this text? Requires: Optional exact text to filter candidates; otherwise the current indexed repository.","- `codebaseiq evidence` \u2014 Which exact execution, runtime, data, state, temporal, contract, identity, ownership, or dependency relationships surround these referents? Which related source must be read only when graph evidence leaves a named implementation gap? Requires: One or more exact symbol, file:line, or literal roots plus explicit family, direction, depth, and output bound.","- `codebaseiq inspect` \u2014 Which related source units across several known text, symbol, or location anchors should be read together? Requires: One or more exact text, symbol, or file:line selectors naming the unresolved behavior.","- `codebaseiq code <selectors...>` \u2014 What exact source defines these symbols, ranges, or file surfaces? Requires: One or more exact symbols, file:line ranges, or file paths.","- Choose graph controls explicitly: `execution incoming` \u2014 Who can call or reach this?; `execution outgoing` \u2014 What can this call or reach?; `dataflow incoming` \u2014 Where can this value come from?; `dataflow outgoing` \u2014 Where can this value go?; `runtime both` \u2014 Which producer and consumer rendezvous?; `state both` \u2014 What resource is observed or changed?; `temporal both` \u2014 What occurs before or after this?; `contract both` \u2014 What interface constrains this?; `identity both` \u2014 Are these observations the same entity?; `ownership both` \u2014 What contains or owns this?; `dependencies outgoing` \u2014 What does this statically rely on?. The CLI does not infer them from English intent.","- Calibration: exact is directly observed; derived is deterministically computed; candidate needs confirmation; mixed discloses its constituents; unknown cannot support a stronger claim. Read coverage and recovery before making absence claims.","- The controls above are complete for ordinary exploration. Run `codebaseiq capabilities --matrix` only when a named claim depends on uncertain provider support; do not run it for routine orientation."],Nn=[{stage:"locate",id:"search",command:"search <exact-text>",question:"Where does this exact text occur in current project text, and which aligned compiler symbol owns each line?",requiredInput:"One exact text literal or deliberately bounded regular expression; insert `--` before a literal that starts with a dash.",returnedFact:"exact cardinality, bounded identities and source, and scope commands that recover withheld matches",evidenceCeiling:"Exact current-text cardinality and locations within reported text coverage; compiler ownership only where aligned.",nonClaim:"Structural source ranking orders exact matches but does not establish task relevance. A literal co-occurrence does not establish a graph relationship.",outputCost:"small",contrasts:["outline: search locates exact text across files; outline enumerates compiler-owned constructs in one known file."],gapClosingCommands:["evidence","inspect","code"]},{stage:"locate",id:"outline",command:"outline <file>",question:"What symbols and nesting exist in this file?",requiredInput:"One exact current project file path.",returnedFact:"symbol names, nesting, and line ranges",evidenceCeiling:"Exact compiler-owned constructs and ranges when the file is indexed; no invented semantic overlay.",nonClaim:"File ownership and nesting do not establish execution or task relevance.",outputCost:"small",contrasts:["search: outline enumerates constructs in one known file; search locates exact text across current project text.","code: outline returns identities and ranges; code materializes exact source for selected identities."],gapClosingCommands:["evidence","inspect","code"]},{stage:"locate",id:"entrypoints",command:"entrypoints [text]",question:"Which detected external roots or entry-surface candidates match this text?",requiredInput:"Optional exact text to filter candidates; otherwise the current indexed repository.",returnedFact:"entry symbols with files, confidence, evidence, and indexed caller counts",evidenceCeiling:"Source/compiler-grounded entry evidence and indexed caller counts; exported-only candidates remain candidates.",nonClaim:"A package-public export or zero indexed callers is an entry candidate, not proof of runtime ingress. Entry classification does not establish that the callable executes.",outputCost:"bounded",contrasts:["entry-map: entrypoints locates possible external roots; entry-map traverses static calls from one selected root.","search: entrypoints classifies callable roots; search only locates exact text and ownership."],gapClosingCommands:["evidence","inspect","code"]},{stage:"project",id:"evidence",command:"evidence",question:"Which exact execution, runtime, data, state, temporal, contract, identity, ownership, or dependency relationships surround these referents? Which related source must be read only when graph evidence leaves a named implementation gap?",requiredInput:"One or more exact symbol, file:line, or literal roots plus explicit family, direction, depth, and output bound.",returnedFact:"batched exact selectors and typed graph relationships; compact endpoints with exact locations and follow-up commands; coverage and recoverable omissions; exact source-recovery command when source was requested with a graph projection; explicit ambiguity failure with exact rerun commands",evidenceCeiling:"Typed edges only to each registered provider ceiling within the explicitly selected projection and reported coverage.",nonClaim:"The projection does not infer which relationships are relevant to the user task. Reference, dependency, data, state, temporal, contract, and identity edges do not become execution claims.",outputCost:"bounded",contrasts:["refs: refs enumerates direct reference sites; evidence traverses explicitly selected typed relationships.","call-graph: call-graph specializes in static calls; evidence can combine execution with other selected families.","value-flow: value-flow specializes in proved transfers; evidence projects bounded dataflow alongside other families.","dependence-slice: dependence-slice computes a program-dependence slice; evidence performs bounded graph projection."],gapClosingCommands:["inspect","code"]},{stage:"read",id:"inspect",command:"inspect",question:"Which related source units across several known text, symbol, or location anchors should be read together?",requiredInput:"One or more exact text, symbol, or file:line selectors naming the unresolved behavior.",returnedFact:"one ranked, deduplicated semantic packet plus exact selector cardinality and explicit expansion coverage",evidenceCeiling:"Complete current source for every materialized syntax unit; bounded selector and packet coverage remain explicit.",nonClaim:"A source packet does not choose which implementation details are relevant to the user task. A reference mention does not establish executable reachability.",outputCost:"potentially-large",contrasts:["code: inspect batches bounded behavior or source gaps; code materializes complete exact source.","evidence: inspect reads implementation units; evidence projects typed relationships without source."],gapClosingCommands:[]},{stage:"read",id:"code",command:"code <selectors...>",question:"What exact source defines these symbols, ranges, or file surfaces?",requiredInput:"One or more exact symbols, file:line ranges, or file paths.",returnedFact:"per-selector resolution, complete definition source, exact ranges with statically attributed same-file call closure, file export surfaces, omitted-local ledgers, and line ranges",evidenceCeiling:"Exact current source bytes for every resolved selector, with omitted file-local constructs disclosed.",nonClaim:"Source materialization does not establish callers, runtime reachability, or task relevance by itself.",outputCost:"potentially-large",contrasts:["inspect: code materializes complete exact source; inspect batches bounded behavior or source gaps.","outline: code reads selected implementations; outline enumerates file structure without reading every body."],gapClosingCommands:[]}];var m="<!-- codebaseiq:agent-setup:begin -->",S="<!-- codebaseiq:agent-setup:end -->",Tt="# codebaseiq:agent-setup",M=[".codex/hooks.json",".claude/settings.local.json"],je="# codebaseiq:local-agent-hooks:begin",Fe="# codebaseiq:local-agent-hooks:end",ie="hook-architecture-stop",Je=["claude","codex"],E={claude:".claude/settings.local.json",codex:".codex/hooks.json"},ze="sentinel-hook.mjs",qt=l("dist","sentinel-hook.js"),Ot=l("dist","cli.js"),Pt="cli-path",Ht="installed-projects.json";function tr(e){let t=e.written.length+e.unchanged.length,n=e.skipped.length;return{verdict:n===0?"ready":t===0?"blocked":"partial",ready:t,skipped:n}}function nr(e,t={}){let n={written:[],unchanged:[],skipped:[]};return _t(e,n),t.architectureHook!==!1&&Nt(e,n,t.architectureHook),n}function rr(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Ue(e,"AGENTS.md",t,n),Ue(e,"CLAUDE.md",t,n),Xe(e,t,n,r=>at(jt(r))),st(e,t,n),Mt(e,t,n),n}function _t(e,t){let n=[m,"## codebaseiq","","This repository uses codebaseiq as its primary code exploration surface.","","codebaseiq separates two responsibilities: the agent decides what repository fact it needs, while the tool locates exact referents and reports compiler, runtime, data, state, temporal, contract, identity, ownership, and dependency evidence without guessing task relevance. The ordinary loop is locate an exact root, project explicitly chosen relationships, read behavior only for a named remaining gap, then stop when the requested claims are established.","","- Use codebaseiq for repository exploration, including literal search and exact source reads. Native tools are for applying edits, running checks, binary content, or a specific unsupported gap that codebaseiq has explicitly reported\u2014not a parallel exploration workflow.","- Before exploring, state the few material repository facts the answer depends on. Include behavior-changing predicates, authorization checks, data reshaping, hard bounds, runtime crossings, durable state changes, emitted notifications, returned values, relevant sibling outcomes, and externally visible ordering only when the request depends on them.","- For end-to-end explanations, use the installed codebaseiq-explore guidance to maintain the evidence ledger and audit the final answer; codebaseiq supplies the repository observations.",...$e,"- Any exact symbol or `file:line` returned by a locator is immediately usable as a graph root. There is no required anchor-discovery phase and locator ordering never proves task relevance. For an end-to-end question, include the initiating owner as a root or request incoming execution capable of exposing it; do not assume a core type is the ingress. Locate independent roots together when the question already implies several participants.","- A materialized evidence projection requires repeated `--symbol`, `--at`, or `--search` selectors plus one or more repeated `--edge <family>` flags, explicit `--direction incoming|outgoing|both`, `--depth <n>`, and `--max-edges <n>`. The agent chooses the relationships capable of establishing its claim; the CLI resolves identity, direction, evidence strength, provider support, and coverage. Use optional exact `--subtype <subtype>` and `--connecting` only when the selected roots themselves must be connected. Never request `complete`, `all`, or every family merely to discover what exists; use `--inventory-only` when only counts can determine the next bounded projection.","- Treat execution calls and exact runtime handoffs as executable reachability. Dataflow, state, temporal, contract, identity, ownership, and dependency edges say what a path carries, changes, orders, constrains, identifies, contains, or relies on; they do not become call claims. Treat exact edges as facts only within their stated coverage and candidate edges as leads requiring source confirmation.","- Read every packet as a coverage contract. `accounted` means the requested bounded projection reports every omission; `bounded` means requested edges were placed in stable recoverable folds by the output budget; `incomplete` means a selector or provider could not be resolved. None proves the user task complete, and missing output is no evidence of absence.","- Prefer batched locators, projections, and gap reads. Query count measures exploration efficiency; it never makes a known recoverable material fact optional. Before drilling down, name the still-missing fact. Expand only a printed fold or exact adjacent identity that can establish it; batch independent roots and gaps instead of shuttling between abstraction levels, and repeat only while a named fact remains unresolved.","- Use `codebaseiq inspect --symbol <symbol> --symbol <symbol> --at <file:line> --view behavior` for several named behavioral gaps. Connected behavior is already source evidence; do not reread lines it rendered. Use `codebaseiq code <symbol-or-range>` only when exact implementation syntax can change the decision. Do not replace these reads with `rg`, `grep`, `sed`, or `nl`.","- For a multi-step mutation, preserve later compaction, rollback, and cleanup. For every event, log, or outbox write, preserve its operation and record identity. For coordination, state the lock scope and which checks and writes occur inside it. State whether interruption is prevented, atomic, rolled back, or repaired later. Resolve exact constant values when they can change the answer.","- For a tiered policy or dispatcher, preserve the precedence of its tiers and the exact scope of every bypass; never imply that a later bypass can skip an earlier hard rejection unless the rendered condition proves it.","- For a stateful owner, preserve its lifetime and sharing scope, including whether it is a singleton, shared registry, per-session instance, or per-invocation value.","- Use `codebaseiq diff-impact` to map changed symbols and downstream consumers after a nontrivial edit.","- Use `codebaseiq architecture` to inspect explicit structural rules.","- Use `codebaseiq health` to find React, Vue, duplication, complexity, drift, and cleanup candidates.","- Before claiming a complete relationship set or an absence, inspect coverage and use `--full` only when complete coverage can change the decision. A bounded or unsupported result cannot establish that no caller, route, branch, poller, or consumer exists.","- Before claiming what every callsite passes, read the `trace` or `evidence` claim-support section. Only an eligible callsite-argument claim is backed by complete syntactic invocations; bounded context is not proof.","- Prefer human output for agent reading. Use `--json --result-only` only for a programmatic consumer.","- Never rerun a successful human command as JSON. Before each drilldown, name the still-unanswered fact and check whether an earlier packet already establishes it; if so, update the ledger or draft without another query. Stop when no unanswered fact remains because every additional reasoning step pays again for the accumulated context.","- Before answering, compare the draft to selected statement-complete behavior. Preserve every material behavior-changing predicate, returned default, separately merged field, cache invalidation, and cleanup effect. Do not collapse fields with different operations into a generic summary, and do not re-query evidence already in context.","- With an explicit CODEBASEIQ_SESSION, a complete source unit, a byte-identical exact subset of a prior exact source read, or a graph unit/edge may be replaced by a visible receipt from the same index generation. Preview coverage never suppresses an exact unit; changed bytes, changed graph content, a new generation, or --reemit force full evidence.","- If output emits `Continue exactly:`, run that command unchanged until transport is complete.","- When architecture rules are configured and clean, setup installs one checkout-local Stop hook. It checks architecture only after indexed source changes.","- Commit relevant `.codebaseiq/suppressions/*.json` records with the change. Do not commit local agent-tool settings.",S].join(`
|
|
3
|
-
`);Ge(e,"AGENTS.md",n,t);let r=[m,"@AGENTS.md",S].join(`
|
|
4
|
-
`);Ge(e,"CLAUDE.md",r,t,o=>o.includes("@AGENTS.md")&&!o.includes(m))}function Ge(e,t,n,r,o){let i=l(e,t),s=!1,c=se(i,t,r,a=>{if(o?.(a.text))return s=!0,{kind:"unchanged"};let d=Dt(a.text,n);return d===a.text?{kind:"unchanged"}:{kind:"write",text:d,...a.revision.exists?{}:{mode:420}}});c&&(!c.changed||s?r.unchanged.push(t):r.written.push(t))}function Ue(e,t,n,r){let o=l(e,t);if(n.dryRun){if(!h(o)){r.unchanged.push(t);return}try{let s=f(o,"agent instruction file");s.includes(m)?(Be(s),r.removed.push(t)):r.unchanged.push(t)}catch(s){r.skipped.push({target:t,reason:s instanceof Error?s.message:String(s)})}return}let i=se(o,t,r,s=>{if(!s.revision.exists||!s.text.includes(m))return{kind:"unchanged"};let c=Be(s.text);return c.length===0?{kind:"delete"}:{kind:"write",text:c}});i&&(i.changed?r.removed.push(t):r.unchanged.push(t))}function Dt(e,t){if(Qe(e)==="present"){let r=new RegExp(`${m}[\\s\\S]*?${S}`);return e.replace(r,t)}return e.length>0?`${e.replace(/\n*$/,`
|
|
5
|
-
|
|
6
|
-
`)}${t}
|
|
7
|
-
`:`${t}
|
|
8
|
-
`}function Be(e){Qe(e);let t=new RegExp(`${m}[\\s\\S]*?${S}`),n=e.replace(t,"").replace(/\n{3,}/g,`
|
|
9
|
-
|
|
10
|
-
`).trim();return n.length===0?"":`${n}
|
|
11
|
-
`}function Qe(e){let t=e.split(m).length-1,n=e.split(S).length-1;if(t===0&&n===0)return"absent";if(t===1&&n===1&&e.indexOf(m)<e.indexOf(S))return"present";throw new Error("managed codebaseiq markers are incomplete, duplicated, or out of order")}function se(e,t,n,r){try{return A(e,r,{maxRetries:0})}catch(o){n.skipped.push({target:t,reason:o instanceof Error?o.message:String(o)});return}}function Mt(e,t,n){let r=".git/hooks/pre-commit",o=l(e,r);if(!h(o)){n.unchanged.push(r);return}if(!f(o,"pre-commit hook").includes(Tt)){n.skipped.push({target:r,reason:"pre-commit hook is not managed by codebaseiq"});return}if(t.dryRun){n.removed.push(r);return}se(o,r,n,()=>({kind:"delete"}))?.changed&&n.removed.push(r)}function Nt(e,t,n={}){let r=(n.inspectReadiness??Lt)(e);if(r.state==="not-configured")return;if(r.state==="blocked"){t.skipped.push({target:"architecture Stop hook",reason:r.reason});return}let o=n.commandPrefix??"codebaseiq";for(let i of M){if(O(e,i)){t.skipped.push({target:i,reason:"tracked repository config; the checkout-local hook installer will not modify it"});continue}ce(l(e,i),i,t,s=>$t(s,o))}nt(e,t)}function Xe(e,t,n,r){for(let o of M){let i=l(e,o);if(h(i)){if(O(e,o)){n.skipped.push({target:o,reason:"tracked repository config; the checkout-local hook remover will not modify it"});continue}if(t.dryRun){try{let s=et(i);JSON.stringify(r(s))!==JSON.stringify(s)&&n.removed.push(o)}catch(s){n.skipped.push({target:o,reason:y(s)})}continue}ce(i,o,n,r,!0)}}}function Lt(e){let t=_e(e);if(!t.architecture||t.architecture.boundaries.length===0)return{state:"not-configured"};let n=Ee(e,t),r=De(e,t,n);if(r.state!=="fresh")return{state:"blocked",reason:`the index is ${r.state}; refresh it before installing a persistent architecture grader`};let o;try{o=Me(e);let i=Le(Ne(o));return i.length>0?{state:"blocked",reason:`the current architecture baseline has ${i.length} enforced violation(s); make the declared policy clean before installing the Stop hook`}:{state:"ready"}}catch(i){return{state:"blocked",reason:y(i)}}finally{o?.close()}}function $t(e,t="codebaseiq"){let n=C(e.hooks),r=Array.isArray(n.Stop)?n.Stop:[],o={type:"command",command:`${t} ${ie}`,timeout:120,statusMessage:"Checking architecture boundaries"};return{...e,hooks:{...n,Stop:Ye(r,{hook:o},Ze)}}}function or(e,t){return e===ie&&t.sentinel?.enabled===!0}function jt(e){let t=C(e.hooks),n=Array.isArray(t.Stop)?t.Stop:[],r=Ft(n),o={...t};r.length>0?o.Stop=r:delete o.Stop;let i={...e};return Object.keys(o).length>0?i.hooks=o:delete i.hooks,i}function C(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ft(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!Ze(n)):[]})).filter(t=>t.hooks.length>0)}function ae(e){return typeof e=="object"&&e!==null&&Array.isArray(e.hooks)}function Ye(e,t,n){let r=!1,o=[];for(let i of e){if(!ae(i)||!i.hooks.some(n)){o.push(i);continue}let s=i.hooks.every(n),c=[],a=!1;for(let d of i.hooks)n(d)?r||(c.push(t.hook),r=!0,a=!0):c.push(d);c.length!==0&&o.push(a&&s?Gt({...i,hooks:c},t.matcher):{...i,hooks:c})}return r||o.push({...t.matcher!==void 0?{matcher:t.matcher}:{},hooks:[t.hook]}),o}function Gt(e,t){let{matcher:n,...r}=e;return t===void 0?r:{matcher:t,...r}}function Ze(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&new RegExp(`(?:^|\\s)${ie}$`,"u").test(t)}function ce(e,t,n,r,o=!1){try{A(e,s=>{let c=s.revision.exists?tt(s.text,e):{},a=r(c);return JSON.stringify(a)===JSON.stringify(c)?{kind:"unchanged"}:o&&Object.keys(a).length===0?{kind:"delete"}:{kind:"write",text:`${JSON.stringify(a,null,2)}
|
|
12
|
-
`,mode:384}}).changed?"written"in n?n.written.push(t):n.removed.push(t):o||n.unchanged.push(t)}catch(i){n.skipped.push({target:t,reason:y(i)})}}function et(e){return tt(f(e,"agent hook settings"),e)}function tt(e,t){let n=JSON.parse(e);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Cannot update ${t}: the hook config is not a JSON object.`);return n}function nt(e,t){let n=B(e,["rev-parse","--git-path","info/exclude"]),r=n?Se(e,n):void 0;if(!r||!h(D(r))){t.skipped.push({target:".git/info/exclude",reason:"Git metadata was not found; local hook files may appear as untracked"});return}let o=Ut(B(e,["rev-parse","--show-prefix"])??"");try{A(r,i=>{let s=new RegExp(`${je}([\\s\\S]*?)${Fe}\\n?`,"gu"),c=[...i.text.matchAll(s)].flatMap(b=>b[1].split(`
|
|
13
|
-
`).filter(wt=>wt!=="")),a=i.text.replace(s,"").replace(/\n*$/u,""),d=[...M,He].map(b=>`/${o}${b}`),p=[je,...new Set([...c,...d]),Fe].join(`
|
|
14
|
-
`),u=`${a}${a?`
|
|
15
|
-
|
|
16
|
-
`:""}${p}
|
|
17
|
-
`;return u===i.text?{kind:"unchanged"}:{kind:"write",text:u,mode:420}})}catch(i){t.skipped.push({target:".git/info/exclude",reason:y(i)})}}function Ut(e){return e.replace(/[\\*?[]/gu,"\\$&")}function y(e){return e instanceof Error?e.message:String(e)}var rt={claude:[{event:"SessionStart",timeout:5},{event:"UserPromptSubmit",timeout:5},{event:"PostToolUse",matcher:"Edit|Write|MultiEdit",timeout:15,async:!0},{event:"Stop",timeout:30},{event:"SessionEnd",timeout:2}],codex:[{event:"SessionStart",timeout:5},{event:"UserPromptSubmit",timeout:5},{event:"PostToolUse",matcher:"apply_patch|Edit|Write",timeout:15},{event:"Stop",timeout:30}]};function N(e){let t=l(e,"bin");return{directory:t,script:l(t,ze),version:l(t,"sentinel-hook.version"),manifest:l(t,"package.json"),cliPath:l(t,Pt)}}function ot(e={}){let t=Bt(e.packageRoot??D(Wt(import.meta.url)));if(!t)return{state:"skipped",reason:"the codebaseiq package root was not found"};let n=l(t.root,qt);if(!h(n))return{state:"skipped",reason:"build the package first (dist/sentinel-hook.js was not found)"};let r=N(e.cacheRoot??g());try{let o=`${JSON.stringify({name:"codebaseiq",version:t.version,private:!0},null,2)}
|
|
18
|
-
`,i=[P(r.script,K(n,it("sentinel hook bundle"))),P(r.version,Buffer.from(`${t.version}
|
|
19
|
-
`)),P(r.manifest,Buffer.from(o)),P(r.cliPath,Buffer.from(`${oe(t.root,Ot)}
|
|
20
|
-
`))];return{state:"installed",script:r.script,version:t.version,changed:i.some(Boolean)}}catch(o){return{state:"skipped",reason:`the hook binary could not be installed: ${y(o)}`}}}function ir(e,t={}){let n=N(t.cacheRoot??g());if(!(re(n.version,"sentinel hook version")===e&&h(n.cliPath)))return ot(t)}function Bt(e){let t=e;for(;;){try{let r=JSON.parse(f(l(t,"package.json"),"package manifest"));if(r.name==="codebaseiq"&&typeof r.version=="string")return{root:t,version:r.version}}catch{}let n=D(t);if(n===t)return;t=n}}function it(e){return{maxBytes:be,inputKind:e}}function P(e,t){try{if(K(e,it("sentinel hook file")).equals(t))return!1}catch{}return We(e,t),!0}function sr(e,t={}){let n=t.hosts??Je,r=t.cacheRoot??g(),o=ot({packageRoot:t.packageRoot,cacheRoot:r}),i={written:[],unchanged:[],skipped:[],binary:o,notices:[]};if(o.state==="skipped")return i.skipped.push({target:"sentinel hook binary",reason:o.reason}),i;for(let c of n){let a=E[c];if(O(e,a)){i.skipped.push({target:a,reason:"tracked repository config; the checkout-local hook installer will not modify it"});continue}let d=[];ce(l(e,a),a,i,p=>{let u=Jt(p,zt(c,o.script,t.nodeExecutable));return d=Vt(p,u),u}),c==="codex"&&d.length>0&&i.written.includes(a)&&i.notices.push(`Codex must re-approve the changed hooks (${d.join(", ")}): open Codex once in this project and approve them. The approval it recorded for the old command no longer applies, and codebaseiq can only see that an approval exists, not that it still matches.`)}if(nt(e,i),n.map(c=>E[c]).some(c=>i.written.includes(c)||i.unchanged.includes(c)))try{on(r,e)}catch(c){i.skipped.push({target:"sentinel project registry",reason:y(c)})}return i}function Vt(e,t){let n=o=>`${o.event}:${o.group}:${o.index}:${JSON.stringify(o.hook)}`,r=new Set(_(t).map(n));return[...new Set(_(e).filter(o=>!r.has(n(o))).map(o=>o.event))]}function Kt(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Xe(e,t,n,at),st(e,t,n),n}function ar(e={}){let t=e.cacheRoot??g(),n={removed:[],unchanged:[],skipped:[]};for(let o of rn(t)){if(!h(o)){e.dryRun||pt(t,o);continue}let i=Kt(o,{dryRun:e.dryRun,cacheRoot:t});n.removed.push(...i.removed.map(s=>l(o,s))),n.skipped.push(...i.skipped.map(s=>({...s,target:l(o,s.target)})))}let r=N(t);if(n.skipped.length>0)return h(r.script)&&n.skipped.push({target:r.script,reason:"kept: hooks that run it could not be removed from every project; run uninstall again once they can"}),n;for(let o of[r.script,r.version,r.manifest,r.cliPath])if(h(o)&&(n.removed.push(o),!e.dryRun))try{Et(o)}catch(i){n.skipped.push({target:o,reason:y(i)})}if(!e.dryRun)try{At(r.directory)}catch{}return n}function st(e,t,n){let r=M;if(!(t.dryRun||n.skipped.some(o=>r.includes(o.target))))try{pt(t.cacheRoot??g(),e)}catch(o){n.skipped.push({target:"sentinel project registry",reason:y(o)})}}function H(e){if(!e||typeof e!="object")return!1;let{command:t,args:n}=e;return Array.isArray(n)&&n.includes(R)?!0:typeof t=="string"&&t.split(/\s+/u).includes(R)}function Jt(e,t){let n={...C(e.hooks)};for(let{event:r,...o}of t){let i=n[r];n[r]=Ye(Array.isArray(i)?i:[],o,H)}return{...e,hooks:n}}function at(e){let t=C(e.hooks),n={},r=!1;for(let[i,s]of Object.entries(t)){if(!Array.isArray(s)){n[i]=s;continue}let c=[];for(let a of s){if(!ae(a)||!a.hooks.some(H)){c.push(a);continue}r=!0;let d=a.hooks.filter(p=>!H(p));d.length>0&&c.push({...a,hooks:d})}(c.length>0||s.length===0)&&(n[i]=c)}if(!r)return e;let o={...e};return Object.keys(n).length>0?o.hooks=n:delete o.hooks,o}function zt(e,t,n=process.execPath){return rt[e].map(r=>({event:r.event,...r.matcher!==void 0?{matcher:r.matcher}:{},hook:e==="claude"?Qt(t,r):Xt(t,r,n)}))}function Qt(e,t){return{type:"command",command:"node",args:[e,"--host","claude",...t.async?["--async"]:[],R],...t.async?{async:!0,asyncRewake:!0}:{},timeout:t.timeout}}function Xt(e,t,n){let r=It(n)&&/^node(?:\.exe)?$/iu.test(Ke(n))?n:"node";return{type:"command",command:`${process.platform==="win32"?"& ":""}${Ve(r)} ${Ve(e)} --host codex ${R}`,timeout:t.timeout}}function Ve(e){if((process.platform==="win32"?/["\r\n%$`]/u:/["\r\n$`]/u).test(e))throw new Error(`${JSON.stringify(e)} cannot be quoted in a Codex hook command`);return`"${e}"`}function _(e){let t=[];for(let[n,r]of Object.entries(C(e.hooks)))Array.isArray(r)&&r.forEach((o,i)=>{ae(o)&&o.hooks.forEach((s,c)=>{H(s)&&t.push({event:n,group:i,index:c,hook:s})})});return t}function ct(e){if(h(e))try{return et(e)}catch{return}}function cr(e,t={}){let n=N(t.cacheRoot??g()),r=re(n.version,"sentinel hook version"),o=re(n.cliPath,"sentinel hook CLI path");return{binary:{script:n.script,present:h(n.script),...r?{version:r}:{},...o?{cliTarget:o}:{}},hosts:Je.map(i=>{let s=E[i],c=ct(l(e,s)),a=c?_(c):[],d=rt[i].map(u=>u.event),p=new Set(a.map(u=>u.event));return{host:i,file:s,events:d.filter(u=>p.has(u)),missing:d.filter(u=>!p.has(u)),scripts:[...new Set(a.flatMap(u=>Yt(u.hook)))]}})}}function re(e,t){try{return f(e,t).trim()||void 0}catch{return}}function Yt(e){return(Array.isArray(e.args)?e.args.filter(n=>typeof n=="string"):[...e.command.matchAll(/"([^"]*)"|(\S+)/gu)].map(n=>n[1]??n[2]??"")).filter(n=>Ke(n)===ze)}function dr(e,t={}){let n=l(e,E.codex),r=ct(n),o=r?_(r):[];if(o.length===0)return;let i=l(t.codexHome??process.env.CODEX_HOME??l(Ct(),".codex"),"config.toml"),s=tn(i),c=[...new Set([n,l(k(e),E.codex)])];return{configPath:i,hooks:o.map(({event:a,group:d,index:p})=>{let u=`:${nn(a)}:${d}:${p}`;return{event:a,key:`${n}${u}`,trusted:c.some(b=>s.has(dt(`${b}${u}`)))}})}}var Zt=/^\s*\[hooks\.state\.(?:'([^']*)'|"((?:[^"\\]|\\.)*)")\]\s*(?:#.*)?$/u,en=/^\s*trusted_hash\s*=\s*"sha256:[0-9a-f]+"/u;function tn(e){let t=new Set,n;try{n=f(e,"Codex config")}catch{return t}let r;for(let o of n.split(/\r?\n/u)){let i=Zt.exec(o);i?r=dt(i[1]??(i[2]??"").replace(/\\(["\\])/gu,"$1")):/^\s*\[/u.test(o)?r=void 0:r!==void 0&&en.test(o)&&t.add(r)}return t}function nn(e){return e.replace(/([a-z])([A-Z])/gu,"$1_$2").toLowerCase()}function dt(e){return process.platform==="win32"?e.replaceAll("/","\\").toLowerCase():e}function lr(e){let t={...Pe.delivery};try{let n=JSON.parse(f(l(e,ne,qe),"sentinel settings")).delivery;for(let r of Oe){let o=n?.[r];(o==="shadow"||o==="live")&&(t[r]=o)}}catch{}return t}function de(e){return l(e,ne,Ht)}function rn(e=g()){try{return lt(f(de(e),"sentinel project registry"))}catch{return[]}}function lt(e){try{let{projects:t}=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function ut(e,t){let n=de(e);Rt(D(n),{recursive:!0}),A(n,r=>{let o=t(r.revision.exists?lt(r.text):[]);return o===void 0?{kind:"unchanged"}:{kind:"write",text:`${JSON.stringify({projects:o},null,2)}
|
|
21
|
-
`,mode:384}})}function on(e,t){let n=k(oe(t));ut(e,r=>r.includes(n)?void 0:[...r,n].sort())}function pt(e,t){if(!h(de(e)))return;let n=k(oe(t));ut(e,r=>r.includes(n)?r.filter(o=>o!==n):void 0)}import{spawn as En}from"child_process";import{existsSync as Cn,rmSync as mt}from"fs";import{dirname as In,resolve as U}from"path";import{fileURLToPath as Wn}from"url";import{createHash as sn,randomUUID as ht}from"crypto";import{existsSync as an,linkSync as cn,readdirSync as dn,rmSync as ln}from"fs";import{basename as un,dirname as pn,join as v}from"path";var $=1,hn=10*6e4,kr=10080*6e4,le="requests",fn="claims",mn="completions",gn="staging";function ft(e,t,n={}){let r=n.now?.()??new Date,o=wn(n.ttlMs),i=Rn(n.idempotencyKey),s=i?`key-${sn("sha256").update(i).digest("hex")}`:`request-${(n.randomId??ht)()}`,c={version:$,requestId:s,...i?{idempotencyKey:i}:{},createdAt:r.toISOString(),deadlineAt:new Date(r.getTime()+o).toISOString(),detail:t.trim().slice(0,2048)||"stale index observed by a command"},a=xn(e,s),d=kn(e,a,c,n.onStage);if(d.published)return{disposition:"accepted",request:c,achievedDurability:d.achievedDurability,directorySync:d.directorySync};let p=ue(a);if(!p)throw new Error(`Watch refresh request identity ${s} exists but is malformed.`);return{disposition:"duplicate",request:p}}function Sr(e){let t=Sn(e),n=new Map,r=bn(v(e,le),ue);for(let a of L(v(e,mn))){let d=vn(a);if(!d){r++;continue}n.set(d.requestId,d)}let o=new Set;for(let a of L(v(e,fn))){let d=yn(a);if(!d){r++;continue}o.add(d.requestId)}let i=t.filter(a=>!n.has(a.requestId)&&!o.has(a.requestId)),s=[...n.values()].filter(a=>a.outcome==="completed").length,c=[...n.values()].filter(a=>a.outcome==="expired").length;return{pending:i.length,claimed:t.filter(a=>!n.has(a.requestId)&&o.has(a.requestId)).length,completed:s,expired:c,invalid:r,...i.length>0?{oldestPendingAt:i.map(a=>a.createdAt).reduce((a,d)=>An(a,d))}:{}}}function ue(e){return pe(e,t=>{let n=t;return n.version===$&&I(n.requestId)&&(n.idempotencyKey===void 0||typeof n.idempotencyKey=="string")&&x(n.createdAt)&&x(n.deadlineAt)&&Date.parse(n.deadlineAt)>=Date.parse(n.createdAt)&&typeof n.detail=="string"&&n.detail.length>0})}function yn(e){return pe(e,t=>{let n=t;return n.version===$&&I(n.requestId)&&I(n.claimId)&&x(n.claimedAt)})}function vn(e){return pe(e,t=>{let n=t;return n.version===$&&I(n.requestId)&&(n.claimId===void 0||I(n.claimId))&&(n.outcome==="completed"||n.outcome==="expired")&&x(n.completedAt)})}function kn(e,t,n,r){let o=v(e,gn),i=pn(t),s=Y(o),c=Y(i),a=v(o,`${un(t)}.${process.pid}.${ht()}.tmp`);try{let d=te(a,n,{spacing:2,trailingNewline:!0});r?.("after-staged");try{cn(a,t)}catch(u){if(u.code==="EEXIST")return{published:!1};throw u}let p=Ae(s,c,d.directorySync,Re(i));return r?.("after-published"),{published:!0,achievedDurability:p==="synced"?"directory-durable":"file-flushed",directorySync:p}}finally{ln(a,{force:!0})}}function Sn(e){let t=[];for(let n of L(v(e,le))){let r=ue(n);r&&t.push(r)}return t}function bn(e,t){return L(e).filter(n=>!t(n)).length}function L(e,t=".json"){return an(e)?dn(e,{withFileTypes:!0}).filter(n=>n.isFile()&&n.name.endsWith(t)).map(n=>v(e,n.name)).sort():[]}function pe(e,t){try{let n=JSON.parse(f(e,"watch refresh request record"));return t(n)?n:null}catch{return null}}function xn(e,t){return v(e,le,`${t}.json`)}function wn(e){if(e===void 0)return hn;if(!Number.isFinite(e)||e<=0)throw new Error("Watch refresh request ttlMs must be positive.");return Math.floor(e)}function Rn(e){let t=e?.trim();return t?t.slice(0,512):void 0}function I(e){return typeof e=="string"&&/^[a-z0-9][a-z0-9-]{0,127}$/i.test(e)}function An(e,t){return Date.parse(t)<Date.parse(e)?t:e}var gt=5e3,Tn=6e3,qn=1e3,fe=10,On=new Set(["capabilities","check-deps","config-validate","doctor","init","install-skills","reindex","setup","setup-agent","status","suppress","uninstall","watch"]);function Lr(e){let t=e.classification;if(t.kind!=="live")return;let{state:n}=t;return n.watcher.state==="idle"&&n.lastError===void 0?n.indexGeneration:void 0}function Pn(e,t=process.env){return t.CODEBASEIQ_SKIP_WATCH_SERVICE!=="1"&&!e.startsWith("__")&&!On.has(e)}function $r(e){let t=e.env??process.env;if(t.CODEBASEIQ_SKIP_WATCH_SERVICE==="1")return{kind:"skipped",reason:"environment"};if(!Pn(e.commandName,t))return{kind:"skipped",reason:"excluded-command"};if(e.config.watch?.enabled!==!0)return{kind:"skipped",reason:"disabled"};try{let n=Hn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:e.cliVersion,gitContext:e.gitContext,runtime:e.runtime});return{kind:n.disposition,state:n.state}}catch(n){return{kind:"failed",message:n instanceof Error?n.message:String(n)}}}function kt(e,t,n){let r=k(U(e));if(n&&k(n.projectRoot)===r)return{projectRoot:r,worktreeKind:"git",worktreeId:n.worktreeId,cliVersion:t};let o=ke(r);if(o.kind==="error")throw new Error(`Could not establish Git worktree identity for ${r}: ${o.message}`);return o.kind==="non-git"?{projectRoot:r,worktreeKind:"non-git",cliVersion:t}:{projectRoot:r,worktreeKind:"git",worktreeId:o.identity.worktreeId,cliVersion:t}}function jr(e){return F(e,kt(e.projectRoot,e.cliVersion,e.gitContext))}function F(e,t){let n=e.runtime??ve,r=w(e.cacheDir),o=T(r.statePath),i=ye(r.lockPath);return{identity:t,classification:_n(o,t,n.now(),n.isProcessAlive),lock:i,lockIsLive:i!==null&&n.isProcessAlive(i.pid),paths:r}}function Hn(e){let t=e.runtime??ve,n=kt(e.projectRoot,e.cliVersion,e.gitContext),r=F(e,n),o=me("ensure",r.classification);if(o.kind==="reuse")return j(r.paths.activityPath,t),{disposition:"reused",state:o.state};if(o.kind==="refuse-replace")throw new Error(`codebaseiq watch service pid ${o.state.pid} is still alive but its heartbeat is old. Refusing automatic replacement because civil-clock age alone cannot authorize a process signal.`);if(o.kind==="replace")ge(o.state,e,t),W(r.paths,o.state.pid,t);else if(o.kind==="start"){if(r.lockIsLive){let c=yt(e,n,t,Math.min(e.startupTimeoutMs??1e3,1e3));if(c)return j(r.paths.activityPath,t),{disposition:"reused",state:c};throw new Error(`codebaseiq watch is already running for ${U(e.projectRoot)} (pid ${r.lock?.pid}; lock: ${r.paths.lockPath}) without compatible daemon state. Stop the foreground watcher before starting the service.`)}r.classification.kind==="stale"&&W(r.paths,r.classification.state.pid,t)}else throw new Error(`Unexpected ensure action: ${o.kind}`);if(r=F(e,n),o=me("ensure",r.classification),o.kind==="reuse")return j(r.paths.activityPath,t),{disposition:"reused",state:o.state};if(o.kind==="refuse-replace")throw new Error(`codebaseiq watch service pid ${o.state.pid} remains alive with an old heartbeat; automatic replacement is not authorized.`);let i=e.serverPath??Wn(new URL("./watch-server.js",import.meta.url));t.spawnServer(i,n.projectRoot,e.cliVersion,e.watchOverrides??{},e.spawnEnv);let s=yt(e,n,t,e.startupTimeoutMs??gt);if(!s)throw new Error(`codebaseiq watch service did not become ready within ${e.startupTimeoutMs??gt}ms.`);return j(r.paths.activityPath,t),{disposition:"started",state:s}}function Fr(e){let t=e.runtime??ve,n=w(e.cacheDir),r=T(n.statePath),o=r?t.isProcessAlive(r.pid)?{kind:"live",state:r}:{kind:"stale",state:r,reason:"dead-process"}:{kind:"stopped"},i=me("stop",o);if(i.kind==="signal-stop")return ge(i.state,e,t),W(n,i.state.pid,t),{disposition:"stopped",pid:i.state.pid};if(i.kind==="clean-stale")return W(n,i.state.pid,t),{disposition:"stopped",pid:i.state.pid};let s=ye(n.lockPath);return i.kind==="already-stopped"&&s&&t.isProcessAlive(s.pid)?(ge(s,e,t),W(n,s.pid,t),{disposition:"stopped",pid:s.pid}):{disposition:"already-stopped"}}function St(e,t=Date.now()){Te(e,{version:1,at:new Date(t).toISOString()})}function Gr(e,t,n=Date.now(),r={}){ft(w(In(e)).refreshRequestsPath,t,{...r,now:()=>new Date(n)}),St(e,n)}function Ur(e,t,n={}){let r=n.pid??process.pid,o=n.isProcessAlive??V,i=()=>{},s=n.readProcessIdentity??z,c=n.now??(()=>new Date),a={...Z,wallNow:()=>c().getTime(),isProcessAlive:o,readProcessIdentity:s},d=Ce(e,{kind:"watch",pid:r,processIdentity:s(r),detail:{projectRoot:U(t)},parseLegacy:G,runtime:a});if(d.kind==="contended"){let p=bt(d.observation);return{acquired:!1,lockPath:e,message:Dn(e,t,p),release:i}}return{acquired:!0,lockPath:e,message:"",release:()=>{d.lock.release()}}}function ye(e){return bt(ee(e,{parseLegacy:G}))}var G=e=>{let t=xt(e);return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function bt(e){if(e.state==="valid"&&e.record?.kind==="watch"){let t=e.record.detail?.projectRoot;return typeof t!="string"?null:{version:1,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},projectRoot:t,startedAt:e.record.startedAt}}return xt(e.parsed)}function xt(e){try{let t=e;if(t.version!==1||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.projectRoot!="string"||!we(t.startedAt))return null;let n=t.processIdentity===void 0?null:xe(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{version:1,pid:t.pid,...n?{processIdentity:n}:{},projectRoot:t.projectRoot,startedAt:t.startedAt}}catch{return null}}function _n(e,t,n,r){if(!e)return{kind:"stopped"};if(e.protocolVersion!==Q)return{kind:"incompatible",state:e,reason:"protocol"};if(e.projectRoot!==t.projectRoot)return{kind:"incompatible",state:e,reason:"project"};let o=t.worktreeKind==="git"?t.worktreeId:void 0;if(e.worktreeId!==o)return{kind:"incompatible",state:e,reason:"worktree"};if(e.cliVersion!==t.cliVersion)return{kind:"incompatible",state:e,reason:"cli-version"};if(!r(e.pid))return{kind:"stale",state:e,reason:"dead-process"};let i=Date.parse(e.heartbeatAt);return n-i>X?{kind:"stale",state:e,reason:"old-heartbeat"}:{kind:"live",state:e}}function me(e,t){switch(e){case"status":return{kind:"report",classification:t};case"ensure":switch(t.kind){case"stopped":return{kind:"start"};case"stale":return t.reason==="old-heartbeat"?{kind:"refuse-replace",state:t.state,reason:"old-heartbeat"}:{kind:"start"};case"live":return{kind:"reuse",state:t.state};case"incompatible":return{kind:"replace",state:t.state};default:return he(t)}case"stop":switch(t.kind){case"stopped":return{kind:"already-stopped"};case"stale":return t.reason==="old-heartbeat"?{kind:"signal-stop",state:t.state}:{kind:"clean-stale",state:t.state};case"live":case"incompatible":return{kind:"signal-stop",state:t.state};default:return he(t)}default:return he(e)}}function yt(e,t,n,r){let o=n.monotonicNow??q,i=o()+r;for(;o()<=i;){let s=F(e,t).classification;if(s.kind==="live")return s.state;n.sleep(fe)}return null}function ge(e,t,n){let{pid:r}=e;if(!n.isProcessAlive(r))return;vt(e,n),n.signalProcess(r);let o=t.stopTimeoutMs??Tn,i=n.monotonicNow??q,s=i()+o;for(;i()<=s;){if(!n.isProcessAlive(r))return;n.sleep(fe)}if(!n.forceSignalProcess)throw new Error(`codebaseiq watch service pid ${r} did not stop within ${o}ms and forced termination is unavailable.`);vt(e,n),n.forceSignalProcess(r);let c=t.forceStopTimeoutMs??qn,a=i()+c;for(;i()<=a;){if(!n.isProcessAlive(r))return;let d=n.readProcessIdentity(r);if(e.processIdentity&&d&&!J(e.processIdentity,d))return;n.sleep(fe)}throw new Error(`codebaseiq watch service pid ${r} remained alive ${c}ms after forced termination.`)}function W(e,t,n){if(mt(e.statePath,{force:!0}),mt(e.activityPath,{force:!0}),ye(e.lockPath)?.pid===t&&!n.isProcessAlive(t)){let o={...Z,wallNow:n.now,isProcessAlive:n.isProcessAlive,readProcessIdentity:n.readProcessIdentity},i=ee(e.lockPath,{parseLegacy:G,runtime:o});Ie(e.lockPath,i,{parseLegacy:G,runtime:o})}}function Dn(e,t,n){return`error: codebaseiq watch is already running for ${U(t)}${n?` (pid ${n.pid}, started ${n.startedAt}; lock: ${e})`:` (lock: ${e})`}. Stop that watcher before starting another.`}function j(e,t){try{(t.recordActivity??St)(e,t.now())}catch(n){let r=Mn(n);if(r!=="EPERM"&&r!=="EACCES"&&r!=="EROFS")throw n}}function Mn(e){return e.code}var ve={now:Date.now,monotonicNow:q,isProcessAlive:V,readProcessIdentity:z,spawnServer(e,t,n,r,o){if(!Cn(e))throw new Error(`Watch service helper was not found at ${e}. Run npm run build first.`);En(process.execPath,[e,t,n,JSON.stringify(r)],{detached:!0,stdio:"ignore",windowsHide:!0,env:{...process.env,...o,CODEBASEIQ_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(e){process.kill(e,"SIGTERM")},forceSignalProcess(e){process.kill(e,"SIGKILL")},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function vt(e,t){if(!e.processIdentity)throw new Error(`Refusing to signal codebaseiq watch pid ${e.pid}: its ownership record has no process identity.`);let n=t.readProcessIdentity(e.pid);if(!n)throw new Error(`Refusing to signal codebaseiq watch pid ${e.pid}: its process identity is unavailable.`);if(!J(e.processIdentity,n))throw new Error(`Refusing to signal codebaseiq watch pid ${e.pid}: its process identity does not match the ownership record.`)}function he(e){throw new Error(`Unhandled watch service value: ${JSON.stringify(e)}`)}export{Nn as a,tr as b,nr as c,rr as d,or as e,nt as f,ir as g,sr as h,Kt as i,ar as j,cr as k,dr as l,lr as m,Sr as n,Lr as o,Pn as p,$r as q,jr as r,Hn as s,Fr as t,Gr as u,Ur as v};
|
|
22
|
-
//# sourceMappingURL=chunk-5IC2WZAL.js.map
|
package/dist/chunk-5T44HG5Y.js
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{B as J,C as En,a as bn,d as Ae,f as In,i as xn,j as te,k as F,l as me,m as T,o as wn,p as C,q as R,r as S,u as it,v as ye,w as he,x as re,y as ne,z as Pn}from"./chunk-DUKHVPU5.js";import{createRequire as ls}from"module";var us=ls(import.meta.url),ot=ps().version;function ps(){for(let e of["../package.json","../../package.json"])try{return us(e)}catch{}return{version:"0.0.0"}}import{createHash as Fn,randomUUID as bs}from"crypto";import{chmodSync as An,existsSync as se,linkSync as Is,lstatSync as ct,readdirSync as zt,realpathSync as _,unlinkSync as xs,writeSync as ws}from"fs";import{homedir as Ps}from"os";import{basename as Es,dirname as dt,isAbsolute as kn,join as L,resolve as lt}from"path";import{closeSync as fs,existsSync as gs,fsyncSync as ms,mkdirSync as ys,openSync as hs}from"fs";import{dirname as Rn}from"path";function ie(e,t,r,n){let i=0;for(;i<t.length;){let o=r.writeFile(e,t,i,t.length-i);if(!Number.isSafeInteger(o)||o<=0||o>t.length-i)throw new Error(`${n} write did not make valid forward progress`);i+=o}}function Se(e,t){if(t!=="win32")return!1;let r=e.code;return r==="EACCES"||r==="EBADF"||r==="EINVAL"||r==="EISDIR"||r==="EPERM"}var oe=Object.freeze({platform:process.platform,pathExists:e=>gs(e),makeDirectory:e=>ys(e,{recursive:!0}),openFile:(e,t,r)=>hs(e,t,r),syncFile:e=>ms(e),closeFile:e=>fs(e)});function A(e,t=oe){let r=[],n=e;for(;!t.pathExists(n);){r.push(n);let o=Rn(n);if(o===n)throw new Error(`Cannot establish a durable directory path without an existing ancestor: ${e}`);n=o}let i="synced";for(let o of r.reverse())t.makeDirectory(o),i=E(i,I(Rn(o),t));return i}function I(e,t=oe){let r;try{r=t.openFile(e,"r")}catch(n){if(Se(n,t.platform))return"unsupported";throw n}try{t.syncFile(r)}catch(n){try{t.closeFile(r)}catch{}if(Se(n,t.platform))return"unsupported";throw n}return t.closeFile(r),"synced"}function E(...e){return e.every(t=>t==="not-requested")?"not-requested":e.includes("unsupported")?"unsupported":"synced"}import{isAbsolute as vn,relative as Ss}from"path";var v=class extends Error{constructor(r,n){super(`refusing unsafe project file path ${JSON.stringify(r)} (${n})`);this.relativePath=r;this.reason=n;this.name="UnsafeProjectPathError"}relativePath;reason;code="CODEBASEIQ_UNSAFE_PROJECT_PATH"};function qt(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function nu(e){return e.replace(/\\/g,"/")}function iu(e,t){return qt(e)===qt(t)}function st(e){let t=e.trim();if(!/^file:/i.test(t))return t;let r;try{r=new URL(t)}catch{return t}if(r.protocol!=="file:")return t;let n;try{n=decodeURIComponent(r.pathname)}catch{return t}for(n=n.replace(/\\/g,"/");n.length>1&&n.endsWith("/");)n=n.slice(0,-1);let i=/^\/([A-Za-z]):(\/|$)/.exec(n);i&&(n=`/${i[1].toUpperCase()}:${n.slice(3)}`);let o=n.split("/").map(s=>encodeURIComponent(s).replace(/%3A/gi,":")).join("/");return`file://${r.host}${o}`}function be(e,t){return st(e)===st(t)}function O(e,t){let r=Ss(e,t);return r===""||!r.startsWith("..")&&!vn(r)}function j(e){if(!e)throw new v(e,"empty-path");if(e.includes("\0"))throw new v(e,"nul-byte");if(vn(e)||/^[A-Za-z]:/.test(e)||e.startsWith("//")||e.startsWith("\\\\"))throw new v(e,"absolute-path");let t=qt(e);if(t.split("/").some(n=>n===".."))throw new v(e,"parent-traversal");if(!t||t===".")throw new v(e,"empty-path");return t}var Mn=1,Ce=".codebaseiq-cache-owner.json",Rs=16*1024,Cn=Object.freeze({...oe,randomToken:()=>bs(),linkFile:(e,t)=>Is(e,t),removeFile:e=>xs(e),writeFile:(e,t,r,n)=>ws(e,t,r,n)});function at(e,t){return Object.assign(new Error(`refusing unsafe project dbPath ${JSON.stringify(e)} (${t}); use a repository-relative directory that remains inside the checkout`),{name:"UnsafeCachePathError",code:"CODEBASEIQ_UNSAFE_CACHE_PATH",configuredPath:e,reason:t})}function N(e,t){return Object.assign(new Error(`refusing unowned cache directory ${JSON.stringify(e)} (${t}); move unrelated data elsewhere or choose a new empty dbPath`),{name:"CacheOwnershipError",code:"CODEBASEIQ_CACHE_OWNERSHIP",cacheDir:e,reason:t})}function vs(e,t){let r=_(e);return ks(r,Wt(r,t))}function Wt(e,t){let r=_(e),n=process.env.CODEBASEIQ_CACHE_DIR;return n?lt(n):t?.dbPath?Fs(r,t.dbPath):pt(r)}function ut(){let e=process.env.XDG_CACHE_HOME;return L(e||L(Ps(),".cache"),"codebaseiq")}function pt(e){let t=lt(e);try{t=_(t)}catch{}let r=Fn("sha256").update(t).digest("hex").slice(0,12);return L(ut(),"projects",r)}function ft(e){if(!/^[a-f0-9]{24}$/.test(e))throw new Error(`invalid repository cache identity: ${e}`);let t=L(ut(),"repositories",e);return On(t),_(t)}function Ht(e){return process.env.CODEBASEIQ_SHARED_CACHE!=="0"&&!process.env.CODEBASEIQ_CACHE_DIR&&!process.env.CODEBASEIQ_INDEX_DB&&!e?.dbPath}function mu(e,t){let r=vs(e,t);return{cacheDir:r,dbPath:L(r,"index.db"),indexPath:L(r,"index.scip"),metaPath:L(r,"meta.json")}}function ks(e,t,r=Cn){return Ds(e,t,r).cacheDir}function Ds(e,t,r=Cn){let n=_(e),i=se(t)?"synced":On(t,r),o=_(t),s=L(o,Ce);if(se(s))return $t(n,o),Ut(s),Me(o),{kind:"existing",cacheDir:o};Dn(o),Ts(o),Dn(o);let c=`${JSON.stringify({schemaVersion:Mn,canonicalProjectRoot:n,canonicalCacheDir:o,creatorVersion:ot},null,2)}
|
|
3
|
-
`;try{let d=Os(s,c,r),l=E(i,d);return{kind:"published",cacheDir:o,achievedDurability:l==="synced"?"directory-durable":"file-flushed",directorySync:l}}catch(d){if(_s(d))return $t(n,o),{kind:"existing",cacheDir:o};throw d}}function $t(e,t){let r=_(e),n=_(t);return Ms(n,r,n)}function yu(e,t){return se(L(t,Ce))?($t(e,t),Ln(t),!0):!1}function Fs(e,t){let r;try{r=j(t)}catch(s){throw s instanceof v?at(t,s.reason):s}let n=lt(e,...r.split("/"));if(n===e||!O(e,n))throw at(t,"outside-project");let i=As(n),o=_(i);if(!O(e,o)&&o!==e)throw at(t,"symlink-escape");return n}function As(e){let t=e;for(;!se(t);){let r=dt(t);if(r===t)throw at(e,"no-existing-ancestor");t=r}return t}function Ms(e,t,r){let n=L(e,Ce);if(!se(n)||ct(n).isSymbolicLink())throw N(e,"missing regular ownership record");let i=ct(n);if(!i.isFile()||i.size>Rs)throw N(e,"invalid ownership record file");let o=S(n,"cache ownership record"),s=Cs(o,e);if(s.canonicalProjectRoot!==t)throw N(e,"ownership record belongs to a different project");if(s.canonicalCacheDir!==r)throw N(e,"ownership record names a different cache directory");return{record:s,ownerSha256:Fn("sha256").update(o).digest("hex"),physicalCacheDir:e}}function Cs(e,t){try{let r=JSON.parse(e);if(r.schemaVersion!==Mn||typeof r.canonicalProjectRoot!="string"||typeof r.canonicalCacheDir!="string"||typeof r.creatorVersion!="string"||!kn(r.canonicalProjectRoot)||!kn(r.canonicalCacheDir))throw new Error("invalid fields");return r}catch(r){throw N(t,`malformed ownership record: ${r instanceof Error?r.message:String(r)}`)}}function Dn(e){let t=zt(e).filter(r=>r!==Ce&&!Ls(r));if(t.length>0)throw N(e,`unrecognized existing entries: ${t.slice(0,3).join(", ")}`)}function Ls(e){return e.startsWith(`${Ce}.tmp-`)||[".codebaseiq-generations","affected-shadow-latest.json","affected-shadow.jsonl","agent-hooks","augment-vue-meta.json","cache-lifecycle.lock","evidence.db","evidence.db-shm","evidence.db-wal","health-report-cache.json","index.db","index.db-shm","index.db-wal","index.lock","index.scip","language-indexes","meta.json","reindex-activity.jsonl","shared-cache.json","typescript-index","typescript-scip-fragments","typescript-scip-overlays","typescript-semantic","watch-activity.json","watch-refresh-requests","watch-state.json","watch.lock"].includes(e)?!0:/^(?:reindex-|rust-|typescript-)/.test(e)}function Ts(e){for(let t of zt(e)){let r=L(e,t);try{let n=ct(r);if(n.isSymbolicLink())throw N(e,`legacy cache entry ${t} is a symlink`);if(n.isDirectory())Me(r);else if(n.isFile())Ut(r);else throw N(e,`legacy cache entry ${t} is not a file or directory`)}catch(n){if(Tn(n))continue;throw n}}Me(e)}function Ln(e,t=!1){try{let r=ct(e);if(r.isSymbolicLink())throw N(e,"managed cache tree contains a symlink");if(r.isFile()){Ut(e);return}if(!r.isDirectory())throw N(e,"managed cache tree contains a special file");Me(e);for(let n of zt(e))Ln(L(e,n),!0)}catch(r){if(t&&Tn(r))return;throw r}}function Tn(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function On(e,t=oe){let r=A(e,t);return Me(e),r}function Os(e,t,r){let n=`${e}.tmp-${process.pid}-${r.randomToken()}`,i,o=!1;try{i=r.openFile(n,"wx",384),o=!0,ie(i,Buffer.from(t),r,"cache ownership record"),r.syncFile(i),r.closeFile(i),i=void 0,r.linkFile(n,e);let s=I(dt(e),r);return r.removeFile(n),o=!1,E(s,I(dt(e),r))}finally{if(i!==void 0)try{r.closeFile(i)}catch{}if(o)try{r.removeFile(n)}catch{}}}function Me(e){process.platform!=="win32"&&An(e,448)}function Ut(e){process.platform!=="win32"&&An(e,384)}function js(e){if(se(e))return _(e);let t=[],r=e;for(;;){let n=dt(r);if(n===r)return e;if(t.unshift(Es(r)),se(n))return L(_(n),...t);r=n}}function Jt(e){return js(lt(e))}function _s(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function Vt(e,t,r=[]){let n=Qt(e);if(qn.has(n)||r.some(o=>gt(n,o))||t.some(o=>$n(n,o)))return"config";if(t.some(Wn)&&/\.d\.(?:ts|mts|cts)$/.test(n.toLowerCase()))return"ambient";let i=zn(n);return t.some(o=>(Hn[o]??[]).includes(i))?"source":"other"}function Bn(e,t,r){let n=Qt(e);if(qn.has(n)||r?.some(o=>gt(n,o))||$n(n,t)||Wn(t)&&/\.d\.(?:ts|mts|cts)$/.test(n.toLowerCase()))return!0;let i=zn(n);return(Hn[t]??[]).includes(i)}function Su(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.version!="number"||!jn(t.languages)||typeof t.pnpmWorkspaces!="boolean"||typeof t.typescriptProjectMode!="string"||!jn(t.typescriptProjects)||t.clojureConfigPath!==void 0&&typeof t.clojureConfigPath!="string"||!Array.isArray(t.files)||!t.files.every(Kt)?null:t}function bu(e,t){let r=new Map((e?.files??[]).map(a=>[a.path,a])),n=new Map(t.files.map(a=>[a.path,a])),i=new Set([...r.keys(),...n.keys()]),o=[];for(let a of[...i].sort()){let c=r.get(a),d=n.get(a),l=Vt(a,t.languages);!c&&d?o.push({kind:"added",path:a,inputKind:l,after:d}):c&&!d?o.push({kind:"deleted",path:a,inputKind:l,before:c}):c&&d&&(c.hash!==d.hash||c.size!==d.size)&&o.push({kind:"modified",path:a,inputKind:l,before:c,after:d})}let s=new Set;return e||s.add("prior-snapshot-unavailable"),e&&e.version!==t.version&&s.add("snapshot-version-changed"),(_n(e?.files??[])||_n(t.files))&&s.add("duplicate-input-path"),[...e?.files??[],...t.files].some(Gs)&&s.add("unreadable-input"),{version:1,changes:o,projectIdentityChanged:e?!Ns(e,t):!0,uncertainty:[...s].sort()}}function jn(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function _n(e){return new Set(e.map(t=>t.path)).size!==e.length}function Kt(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.path=="string"&&typeof t.size=="number"&&Number.isFinite(t.size)&&typeof t.hash=="string"}function Gs(e){return e.hash==="unreadable"||e.size<0}function Ns(e,t){return Gn(e.languages,t.languages)&&e.pnpmWorkspaces===t.pnpmWorkspaces&&e.typescriptProjectMode===t.typescriptProjectMode&&Gn(e.typescriptProjects,t.typescriptProjects)&&e.clojureConfigPath===t.clojureConfigPath}function Gn(e,t){if(e.length!==t.length)return!1;let r=[...e].sort(),n=[...t].sort();return r.every((i,o)=>i===n[o])}var qn=new Set([".codebaseiq.json"]),Bs={typescript:["tsconfig.json"],javascript:["package.json"],java:["pom.xml","build.gradle"],scala:["build.sbt"],kotlin:["build.gradle.kts"],rust:["Cargo.toml"],python:["pyproject.toml","setup.py"],ruby:["Gemfile"],go:["go.mod"],cpp:["CMakeLists.txt","Makefile"],c:["CMakeLists.txt","Makefile"],csharp:["*.csproj","*.sln","*.slnx"],vb:["*.vbproj","*.sln","*.slnx"],dart:["pubspec.yaml"],php:["composer.json"],clojure:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"]},qs={typescript:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","tsconfig.*.json","jsconfig.json","jsconfig.*.json"],javascript:["package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","tsconfig.json","tsconfig.*.json","jsconfig.json","jsconfig.*.json"],java:["build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","gradle.lockfile","gradle-wrapper.properties"],scala:["plugins.sbt","build.properties"],kotlin:["pom.xml","build.gradle","settings.gradle","settings.gradle.kts","gradle.properties","gradle.lockfile","gradle-wrapper.properties"],rust:["Cargo.lock","rust-project.json","rust-toolchain","rust-toolchain.toml"],python:["setup.cfg","requirements*.txt","Pipfile","Pipfile.lock","poetry.lock","uv.lock"],ruby:["Gemfile.lock","gems.locked"],go:["go.sum","go.work","go.work.sum"],cpp:["compile_commands.json"],c:["compile_commands.json"],csharp:["Directory.Build.props","Directory.Build.targets","Directory.Packages.props","packages.lock.json","NuGet.Config","global.json"],vb:["Directory.Build.props","Directory.Build.targets","Directory.Packages.props","packages.lock.json","NuGet.Config","global.json"],dart:["pubspec.lock","analysis_options.yaml"],php:["composer.lock"],clojure:[]},Nn=new Map;function $n(e,t){return Bs[t].some(r=>gt(e,r))||qs[t].some(r=>gt(e,r))}function gt(e,t){let r=Qt(t).replace(/^\.\//,"");if(!r)return!1;let n=e.split("/").at(-1)??e,i=r.includes("/")?e:n;if(!r.includes("*")&&!r.includes("?"))return i===r;let o=Nn.get(r);if(!o){let s=r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]");o=new RegExp(`^${s}$`),Nn.set(r,o)}return o.test(i)}function Qt(e){return e.replaceAll("\\","/").replace(/^\.\//,"")}function zn(e){return e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:""}function Wn(e){return e==="typescript"||e==="javascript"}var Hn={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".mjs",".cjs",".vue"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]};var Yt=2,ae=3;var Xt=new Set(Pn);function mt(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(s){return{kind:"malformed",reason:`invalid JSON: ${Vs(s)}`}}if(!J(t))return{kind:"malformed",reason:"metadata must be a JSON object"};let r=t.version;if(!Number.isInteger(r))return{kind:"malformed",reason:"version must be an integer"};if(r!==Yt&&r!==ae)return{kind:"unsupported",version:r,direction:r<Yt?"older":"future"};let n=zs(t,r);if(n)return{kind:"malformed",reason:n};let i=t,o={metadata:i,capabilities:$s(i)};return r===Yt?{kind:"legacy",...o,metadata:i}:{kind:"supported",...o,metadata:i}}function Ru(e){return e.kind==="legacy"||e.kind==="supported"?e.metadata:null}function Un(e){if(e.kind!=="legacy"&&e.kind!=="supported"||!e.capabilities.stableGenerationIdentity)return null;let t=e.metadata;return JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages,scipCompanion:t.scipCompanion,sqliteLayoutVersion:t.version===ae?t.sqliteLayoutVersion:void 0})}function $s(e){let t=e.fingerprint!==void 0,r=J(e.fingerprint),n=e.indexedLanguages!==void 0,i=e.status==="complete",o=e.version===ae?e:null;return{usableForQuery:n,usableForEvidenceCache:t,publishableGeneration:i&&r&&n,stableGenerationIdentity:i&&t&&typeof e.updatedAt=="string",languageShardReuse:!!o?.languageFingerprints,typescriptProjectShardReuse:!!o?.typescriptProjectShards}}function zs(e,t){if(e.status!=="complete"&&e.status!=="partial")return"status must be complete or partial";if(e.updatedAt!==void 0&&!En(e.updatedAt))return"updatedAt must be a valid timestamp";for(let r of["requestedLanguages","indexedLanguages"])if(e[r]!==void 0&&!Ws(e[r]))return`${r} must contain unique supported languages`;return e.skipped!==void 0&&!Hs(e.skipped)?"skipped must contain supported language/reason pairs":e.scipCompanion!==void 0&&e.scipCompanion!=="current"&&e.scipCompanion!=="deferred"?"scipCompanion must be current or deferred":t===ae&&e.sqliteLayoutVersion!==void 0&&(!Number.isSafeInteger(e.sqliteLayoutVersion)||e.sqliteLayoutVersion<1)?"sqliteLayoutVersion must be a positive safe integer":t===ae&&e.languageFingerprints!==void 0&&!Us(e.languageFingerprints)?"languageFingerprints must map supported languages to fingerprint objects":t===ae&&e.typescriptProjectShards!==void 0&&!Js(e.typescriptProjectShards)?"typescriptProjectShards must map project names to file fingerprints":null}function vu(e){return e.version===ae&&e.sqliteLayoutVersion===2}function Ws(e){return!Array.isArray(e)||!e.every(t=>typeof t=="string"&&Xt.has(t))?!1:new Set(e).size===e.length}function Hs(e){return Array.isArray(e)&&e.every(t=>J(t)&&typeof t.language=="string"&&Xt.has(t.language)&&typeof t.reason=="string")}function Us(e){return J(e)&&Object.entries(e).every(([t,r])=>Xt.has(t)&&J(r))}function Js(e){return J(e)&&Object.values(e).every(t=>J(t)&&Array.isArray(t.files)&&t.files.every(Kt))}function Vs(e){return e instanceof Error?e.message:String(e)}import{randomUUID as ia}from"crypto";import{closeSync as oa,existsSync as sa,fsyncSync as aa,linkSync as ca,mkdirSync as da,openSync as la,renameSync as ua,unlinkSync as pa,writeSync as fa}from"fs";import{dirname as Vn}from"path";var Ks=Object.freeze(["EPERM","EACCES","EBUSY"]),Qs=Object.freeze([10,20,40,80,160,320,640,1e3,1e3,1e3]);function Ys(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}var Zt=Object.freeze({platform:process.platform,sleep:Ys});function Xs(e,t){if(t!=="win32")return!1;let r=e?.code;return typeof r=="string"&&Ks.includes(r)}function k(e,t={}){let r=t.runtime??Zt,n=t.delaysMs??Qs;for(let i of n)try{return e()}catch(o){if(!Xs(o,r.platform))throw o;r.sleep(i)}return e()}import{chmodSync as Zs,constants as ea,copyFileSync as ta}from"fs";import{dirname as ra}from"path";var Jn=Object.freeze({...oe,copyFile:(e,t)=>ta(e,t,ea.COPYFILE_FICLONE),chmodFile:(e,t)=>Zs(e,t)});function Le(e,t,r={}){let n=r.runtime??Jn,i=ra(t),o=A(i,n);if(n.copyFile(e,t),n.platform==="win32")na(t,r.mode,n);else{r.mode!==void 0&&n.chmodFile(t,r.mode);let s=n.openFile(t,"r");try{n.syncFile(s)}finally{n.closeFile(s)}}return E(o,I(i,n))}function na(e,t,r){let n=!1,i;try{i=r.openFile(e,"r+")}catch(o){let s=o.code;if(s!=="EACCES"&&s!=="EPERM")throw o;r.chmodFile(e,384),n=!0,i=r.openFile(e,"r+")}try{r.syncFile(i)}finally{r.closeFile(i)}t!==void 0?r.chmodFile(e,t):n&&r.chmodFile(e,292)}var Kn=Object.freeze({platform:process.platform,randomToken:()=>ia(),pathExists:e=>sa(e),makeDirectory:e=>da(e,{recursive:!0}),openFile:(e,t,r)=>la(e,t,r),writeFile:(e,t,r,n)=>fa(e,t,r,n),syncFile:e=>aa(e),closeFile:e=>oa(e),renameFile:(e,t)=>ua(e,t),linkFile:(e,t)=>ca(e,t),removeFile:e=>pa(e)});function er(e,t,r={}){let n=r.durability??"visibility",i=r.runtime??Kn,o=Vn(e),s=n==="durable"?A(o,i):(i.makeDirectory(o),"not-requested"),a=`${e}.tmp-${i.randomToken()}`,c=typeof t=="string"?Buffer.from(t):t,d,l=!1;try{d=i.openFile(a,"wx",r.mode??384),l=!0,ie(d,c,i,"atomic file"),n==="durable"&&i.syncFile(d),i.closeFile(d),d=void 0,k(()=>i.renameFile(a,e),{runtime:{platform:i.platform,sleep:i.sleep??Zt.sleep}}),l=!1;let u=n==="durable"?E(s,I(o,i)):"not-requested";return Qn(n,u)}finally{if(d!==void 0)try{i.closeFile(d)}catch{}if(l)try{i.removeFile(a)}catch{}}}function tr(e,t,r={}){let n=r.durability??"visibility",i=r.runtime??Kn;if(!i.linkFile)throw new Error("Exclusive atomic file publication requires hard-link support.");let o=Vn(e),s=n==="durable"?A(o,i):(i.makeDirectory(o),"not-requested"),a=`${e}.tmp-${i.randomToken()}`,c=typeof t=="string"?Buffer.from(t):t,d,l=!1;try{d=i.openFile(a,"wx",r.mode??384),l=!0,ie(d,c,i,"exclusive atomic file"),n==="durable"&&i.syncFile(d),i.closeFile(d),d=void 0,i.linkFile(a,e);let u=n==="durable"?I(o,i):"not-requested";i.removeFile(a),l=!1;let p=n==="durable"?E(s,u,I(o,i)):"not-requested";return Qn(n,p)}finally{if(d!==void 0)try{i.closeFile(d)}catch{}if(l)try{i.removeFile(a)}catch{}}}function Qn(e,t){return{requestedDurability:e,achievedDurability:e==="visibility"?"visibility":t==="synced"?"directory-durable":"file-flushed",directorySync:t}}function V(e,t,r={}){er(e,Yn(t,r),{durability:"visibility",runtime:r.runtime})}function B(e,t,r={}){return er(e,Yn(t,r),{durability:"durable",runtime:r.runtime})}function Yn(e,t){let r=JSON.stringify(e,null,t.spacing);return t.trailingNewline?`${r}
|
|
4
|
-
`:r}import Qa from"better-sqlite3";import{mkdtempSync as Xn}from"fs";import{win32 as ga}from"path";var ma=259,ya=8,ha=6,yt="\\\\?\\",rr=`${yt}UNC\\`;function Zn(e,t,r){if(r!=="win32"||e.startsWith(yt))return;let n=ga.resolve(e);if(!(n.length+t<=ma))return n.startsWith("\\\\")?`${rr}${n.slice(2)}`:`${yt}${n}`}function ht(e,t=process.platform){return e===""||e===":memory:"?e:Zn(e,ya,t)??e}function nr(e,t=process.platform){let r=Zn(e,ha,t);if(!r)return Xn(e);let n=Xn(r);return n.startsWith(rr)?`\\\\${n.slice(rr.length)}`:n.slice(yt.length)}var ei=[],ti=[];function Ju(e){e.groups.length>0&&ei.push(e)}function Vu(e){ti.push(e)}function ri(e){let t=[];for(let r of ti)try{r.close(e)}catch(n){t.push(n)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Multiple database-owned resources failed to close.")}function Ku(e,t){let r=new Set(t.groups);for(let n of ei)n.groups.some(i=>r.has(i))&&(t.file!==void 0&&n.clearFile?n.clearFile(e,t.file):n.clearAll(e))}import{createHash as Oa,randomUUID as ja}from"crypto";import{existsSync as de,mkdirSync as _a,readdirSync as Ga,rmSync as pi,statSync as fi}from"fs";import{basename as Na,dirname as Oe,join as M}from"path";import{join as Ma}from"path";function ce(){return performance.now()}function Yu(){return Date.now()}function St(e,t){return e.reason instanceof Error?e.reason:new Error(t)}function ni(e,t){if(e?.aborted)throw St(e,t)}import{randomUUID as Sa}from"crypto";import{closeSync as ba,fsyncSync as Ia,linkSync as xa,mkdirSync as wa,openSync as Pa,statSync as Ea,unlinkSync as Ra,writeSync as va}from"fs";import{dirname as cr}from"path";var or="codebaseiq-process-lock",sr=1,bt=Object.freeze({wallNow:()=>Date.now(),isProcessAlive:te,readProcessIdentity:ne,randomToken:()=>Sa(),makeDirectory:e=>wa(e,{recursive:!0}),openFile:(e,t,r)=>Pa(e,t,r),writeFile:(e,t,r,n)=>va(e,t,r,n),syncFile:e=>Ia(e),closeFile:e=>ba(e),linkFile:(e,t)=>xa(e,t),readFile:e=>S(e,"process lock record"),statFile:e=>{let t=Ea(e);return{dev:t.dev,ino:t.ino,size:t.size,mtimeMs:t.mtimeMs}},removeFile:e=>Ra(e)});function It(e,t){let r=t.runtime??bt;r.makeDirectory(cr(e));let n;for(let i=0;i<2;i+=1)try{return{kind:"acquired",lock:oi(e,t,r),...n?{reclaimed:n}:{}}}catch(o){if(o.code!=="EEXIST")throw o;let s=Ie(e,{parseLegacy:t.parseLegacy,runtime:r});if(i===0&&Da(e,s,{creationGraceMs:t.creationGraceMs,parseLegacy:t.parseLegacy,runtime:r})){n=s;continue}return{kind:"contended",observation:s}}return{kind:"contended",observation:Ie(e,{parseLegacy:t.parseLegacy,runtime:r})}}function Ie(e,t={}){let r=t.runtime??bt,n,i;try{n=r.statFile(e),i=r.readFile(e)}catch(c){return c.code==="ENOENT"?{state:"missing"}:{state:"malformed"}}let o;try{o=JSON.parse(i)}catch{return{state:"malformed",raw:i,identity:n}}let s=ka(o);if(s)return{state:"valid",raw:i,identity:n,record:s,owner:Aa(s),parsed:o};let a=t.parseLegacy?.(o)??null;return a?{state:"legacy",raw:i,identity:n,owner:a,parsed:o}:{state:"malformed",raw:i,identity:n,parsed:o}}function ka(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.protocol!==or||t.version!==sr||typeof t.kind!="string"||t.kind.trim()===""||typeof t.pid!="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.token!="string"||t.token.trim()===""||typeof t.startedAt!="string"||!Number.isFinite(Date.parse(t.startedAt))||t.detail!==void 0&&(typeof t.detail!="object"||t.detail===null||Array.isArray(t.detail)))return null;let r=t.processIdentity===void 0?null:he(t.processIdentity);return t.processIdentity!==void 0&&(!r||r.pid!==t.pid)?null:{protocol:or,version:sr,kind:t.kind,pid:t.pid,token:t.token,...r?{processIdentity:r}:{},startedAt:t.startedAt,...t.detail?{detail:t.detail}:{}}}function Da(e,t,r={}){let n=r.runtime??bt;if(!ar(t,n))return!1;let i=Fa(`${e}.reclaim`,n);if(!i)return!1;try{let o=Ie(e,{parseLegacy:r.parseLegacy,runtime:n});return!si(t,o)||!ar(o,n)?!1:dr(e,n)}finally{i.release()}}function oi(e,t,r){let n=t.pid??process.pid,i=r.randomToken(),o=t.processIdentity===void 0?r.readProcessIdentity(n):t.processIdentity,s={protocol:or,version:sr,kind:t.kind,pid:n,token:i,...o?{processIdentity:o}:{},startedAt:new Date(r.wallNow()).toISOString(),...t.detail?{detail:t.detail}:{}},a=`${e}.${i}.candidate`,c=r.openFile(a,"wx",384),d;try{ie(c,Buffer.from(`${JSON.stringify(s)}
|
|
5
|
-
`),r,"process lock"),r.syncFile(c)}catch(u){d=u}try{r.closeFile(c)}catch(u){d??=u}if(d!==void 0)throw ir(a,r),d;try{r.linkFile(a,e)}catch(u){throw ir(a,r),u}ir(a,r);try{ai(cr(e),r)}catch(u){throw ii(e,s,r),u}let l=!1;return{path:e,record:s,release:()=>l?!1:(l=!0,ii(e,s,r))}}function ii(e,t,r=bt){let n=Ie(e,{runtime:r});return n.state!=="valid"||!n.record||n.record.pid!==t.pid||n.record.token!==t.token||t.processIdentity&&(!n.record.processIdentity||!re(t.processIdentity,n.record.processIdentity))?!1:dr(e,r)}function Fa(e,t){for(let r=0;r<2;r+=1)try{return oi(e,{kind:"reclaim-guard",runtime:t},t)}catch(n){if(n.code!=="EEXIST")return null;let i=Ie(e,{runtime:t});if(r>0||!ar(i,t))return null;let o=Ie(e,{runtime:t});if(!si(i,o)||!dr(e,t))return null}return null}function ar(e,t){if(e.state==="missing")return!1;if(e.owner){if(!t.isProcessAlive(e.owner.pid))return!0;if(!e.owner.processIdentity)return!1;let r=t.readProcessIdentity(e.owner.pid);return r!==null&&!re(e.owner.processIdentity,r)}return!1}function si(e,t){return e.state===t.state&&e.raw===t.raw&&e.identity!==void 0&&t.identity!==void 0&&e.identity.dev===t.identity.dev&&e.identity.ino===t.identity.ino&&e.identity.size===t.identity.size&&e.identity.mtimeMs===t.identity.mtimeMs}function Aa(e){return{pid:e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{}}}function ai(e,t){let r;try{r=t.openFile(e,"r")}catch(n){if(Se(n,process.platform))return;throw n}try{t.syncFile(r)}catch(n){if(!Se(n,process.platform))throw n}finally{t.closeFile(r)}}function dr(e,t){try{return t.removeFile(e),ai(cr(e),t),!0}catch{return!1}}function ir(e,t){try{t.removeFile(e)}catch{}}var Ca=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.pid;return typeof t=="number"&&Number.isSafeInteger(t)&&t>0?{pid:t}:null};function ci(e,t={}){return q(Ma(e,"gc.lock"),t)}function q(e,t={}){let r=t.waitMs??0,n=t.pollMs??10,i=t.now??ce,o=i()+r;do{let s=di(e);if(s)return li(s);let a=o-i();if(a<=0)return null;La(Math.min(n,a))}while(i()<=o);return null}async function pp(e,t={}){let r=t.waitMs??0,n=t.pollMs??10,i=t.now??ce,o=i()+r;do{ni(t.signal,"Lock acquisition was aborted.");let s=di(e);if(s)return li(s);let a=o-i();if(a<=0)return null;await Ta(Math.min(n,a),t.signal)}while(i()<=o);return null}function di(e){let t=It(e,{kind:"generic",parseLegacy:Ca});return t.kind==="acquired"?t.lock:null}function li(e){return{release:()=>{e.release()}}}function La(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}function Ta(e,t){return t?.aborted?Promise.reject(St(t,"Lock acquisition was aborted.")):new Promise((r,n)=>{let i=setTimeout(()=>{t?.removeEventListener("abort",o),r()},e),o=()=>{clearTimeout(i),t?.removeEventListener("abort",o),n(t?St(t,"Lock acquisition was aborted."):new Error("Lock acquisition was aborted."))};t?.addEventListener("abort",o,{once:!0})})}var le=1,fr=1,je=".codebaseiq-generations",xt="manifest.json",gi="readers",Ba="gc.lock",qa=128,Te=new Map,mi={pid:process.pid,now:()=>new Date,randomToken:()=>ja(),isProcessAlive:te,readProcessIdentity:ne,resolveImmutableGeneration:hi};function P(e){return M(Oe(e),je)}function _e(e){return M(P(e),Ba)}function yi(e,t=mi){let r=q(_e(e.dbPath),{waitMs:5e3});if(!r)throw new Error("SQLite generation retention is busy; retry opening the index.");let n;try{let o=$(e.dbPath);if(!o||!Ge(e.dbPath,o.currentGeneration))return{generation:mr(e),release(){}};let s=t.randomToken();if(!/^[A-Za-z0-9._-]+$/.test(s))throw new Error("SQLite generation reader token is unsafe.");let a=M(P(e.dbPath),gi);_a(a,{recursive:!0});let c=M(a,`${t.pid}-${s}.json`),d=t.readProcessIdentity(t.pid);V(c,{version:1,token:s,generationIdentity:o.currentGeneration,pid:t.pid,...d?{processIdentity:d}:{},acquiredAt:t.now().toISOString()},{spacing:2,trailingNewline:!0});let l=!1;n={identity:o.currentGeneration,required:o.artifactSet==="immutable-v1",release(){l||(l=!0,pi(c,{force:!0}))}}}finally{r.release()}let i;try{i=t.resolveImmutableGeneration(e,n.identity)}catch(o){throw n.release(),o}if(i?.source==="immutable"&&i.identity===n.identity)return{generation:i,release:n.release};if(n.release(),n.required)throw new Error(`Published SQLite generation ${n.identity} is missing or invalid.`);return $a(e,n.identity)}function $a(e,t){let r=q(_e(e.dbPath),{waitMs:5e3});if(!r)throw new Error("SQLite generation retention is busy; retry opening the index.");try{let n=$(e.dbPath);if(n?.currentGeneration!==t)throw new Error("SQLite index publication changed while opening a legacy generation.");if(de(M(Oe(e.dbPath),"index.lock")))throw new Error("Legacy SQLite publication is in progress; retry after the reindex lock is released.");return{generation:Si(e,n.currentGeneration),release(){}}}finally{r.release()}}function gr(e,t,r=mi,n={}){let i=M(P(e),gi);if(!de(i))return{protectedGenerations:new Set,activeLeases:0,staleLeasesRemoved:0,malformedLeases:0};let o=new Set,s=0,a=0,c=0;for(let d of Ga(i,{withFileTypes:!0})){if(!d.isFile()||!d.name.endsWith(".json"))continue;let l=M(i,d.name),u;try{u=za(JSON.parse(S(l,"SQLite generation reader lease")))}catch{u=null}if(!u){c+=1;for(let p of t)o.add(p);continue}if(!Wa(u,r)){n.removeStale!==!1&&(pi(l,{force:!0}),a+=1);continue}s+=1,o.add(u.generationIdentity)}return{protectedGenerations:o,activeLeases:s,staleLeasesRemoved:a,malformedLeases:c}}function za(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=t.processIdentity===void 0?null:he(t.processIdentity);return t.version!==1||typeof t.token!="string"||t.token.trim()===""||typeof t.generationIdentity!="string"||!/^[a-f0-9]{64}$/.test(t.generationIdentity)||typeof t.pid!="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.acquiredAt!="string"||!Number.isFinite(Date.parse(t.acquiredAt))||t.processIdentity!==void 0&&(!r||r.pid!==t.pid)?null:{version:1,token:t.token,generationIdentity:t.generationIdentity,pid:t.pid,...r?{processIdentity:r}:{},acquiredAt:t.acquiredAt}}function Wa(e,t){if(!t.isProcessAlive(e.pid))return!1;if(!e.processIdentity)return!0;let r=t.readProcessIdentity(e.pid);return r===null||re(e.processIdentity,r)}function $(e){try{let t=JSON.parse(S(M(P(e),"state.json"),"SQLite generation state"));return Ua(t)?t:null}catch{return null}}function Ge(e,t){return Ne(P(e),t)}function Ne(e,t){try{let r=JSON.parse(S(M(e,t,xt),"SQLite generation manifest"));return Ha(r,t)?r:null}catch{return null}}function mr(e){let t=$(e.dbPath);if(t){let r=hi(e,t.currentGeneration);if(r)return r;if(t.artifactSet==="immutable-v1")throw new Error(`Published SQLite generation ${t.currentGeneration} is missing or invalid.`)}if(de(M(Oe(e.dbPath),"index.lock")))throw new Error("Legacy SQLite publication is in progress; retry after the reindex lock is released.");return Si(e,t?.currentGeneration)}function Ep(e){let t=$(e);if(t)return t.currentGeneration;try{let r=M(Oe(e),"meta.json"),n=de(r)?S(r,"reindex metadata"):void 0;return bi(e,n)}catch{return null}}function K(e){return Un(mt(e))??e}function hi(e,t){try{let r=M(P(e.dbPath),t),n=Ge(e.dbPath,t);if(!n)return null;let i=lr(r,n.database),o=n.index?lr(r,n.index):void 0,s=n.metadata?lr(r,n.metadata):void 0;return!ur(i,n.database)||n.index&&(!o||!ur(o,n.index))||n.metadata&&(!s||!ur(s,n.metadata))?null:{identity:t,databasePath:i,...o?{indexPath:o}:{},...s?{metadataPath:s,metadataRaw:S(s,"reindex metadata")}:{},source:"immutable"}}catch{return null}}function Si(e,t){let r=H(e.dbPath),n=M(Oe(e.dbPath),"meta.json"),i=de(n)?S(n,"reindex metadata"):void 0,o=de(e.indexPath)?e.indexPath:void 0;return{identity:t??bi(e.dbPath,i),databasePath:e.dbPath,...o?{indexPath:o}:{},...i===void 0?{}:{metadataPath:n,metadataRaw:i},source:"legacy",databaseFileIdentity:r}}function bi(e,t){let r=Oa("sha256").update("sqlite-generation-legacy-v1\0");return t!==void 0&&r.update(K(t)),r.update(`\0${H(e)}`),r.digest("hex")}function H(e){let t=fi(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}function lr(e,t){if(Na(t.file)!==t.file||t.file==="."||t.file==="..")throw new Error("SQLite generation manifest contains an unsafe artifact path");return M(e,t.file)}function ur(e,t){if(!de(e))return!1;let r=ui(e);if(!r||r.size!==t.size)return!1;let n=`${e}\0${t.sha256}\0${r.identity}`;if(Te.has(n))return!0;let i=ye(e,{inputKind:"immutable SQLite generation artifact",maxBytes:t.size}),o=ui(e);if(!o||o.identity!==r.identity||i!==t.sha256)return!1;for(Te.set(n,!0);Te.size>qa;){let s=Te.keys().next().value;if(s===void 0)break;Te.delete(s)}return!0}function ui(e){let t=fi(e,{bigint:!0});return t.isFile()?{identity:`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`,size:Number(t.size)}:null}function Ha(e,t){return e.version===fr&&e.identity===t&&pr(e.database)&&(e.index===void 0||pr(e.index))&&(e.metadata===void 0||pr(e.metadata))}function pr(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.file=="string"&&!!t.file&&Number.isSafeInteger(t.size)&&(t.size??-1)>=0&&typeof t.sha256=="string"&&/^[a-f0-9]{64}$/.test(t.sha256)}function Ua(e){return e.version===le&&typeof e.currentGeneration=="string"&&!!e.currentGeneration&&typeof e.publishedAt=="string"&&Number.isFinite(Date.parse(e.publishedAt))&&(e.artifactSet===void 0||e.artifactSet==="immutable-v1")&&Ja(e.stableMirrors)&&Va(e.previousGeneration)&&Ka(e.publication)}function Ja(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.databaseFileIdentity=="string"&&!!t.databaseFileIdentity&&(t.indexFileIdentity===void 0||typeof t.indexFileIdentity=="string"&&!!t.indexFileIdentity)}function Va(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.generationIdentity=="string"&&!!t.generationIdentity&&typeof t.databasePath=="string"&&!!t.databasePath&&(t.metadataPath===void 0||typeof t.metadataPath=="string"&&!!t.metadataPath)}function Ka(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e,r=[t.converterDurationMs,t.affectedDocumentCount,t.changedDocumentCount,t.producerDurationMs,t.materializationDurationMs,t.patchDurationMs].filter(n=>n!==void 0);return(t.mode==="incremental"||t.mode==="full")&&t.validation==="passed"&&t.converterDurationMs!==void 0&&r.every(n=>typeof n=="number"&&Number.isFinite(n)&&n>=0)&&(t.scipCompanion===void 0||t.scipCompanion==="current"||t.scipCompanion==="deferred")&&(t.typescriptOverlayGeneration===void 0||typeof t.typescriptOverlayGeneration=="string"&&!!t.typescriptOverlayGeneration)&&(t.scipCompanion!=="deferred"||!!t.typescriptOverlayGeneration)&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")}var Ya=["busy_timeout = 5000","query_only = ON","temp_store = MEMORY","cache_size = -64000","mmap_size = 268435456"],yr=class{constructor(t,r){this.connection=t;this.releaseGenerationReader=r}connection;releaseGenerationReader;active=!0;initialize(t){try{for(let r of Ya)this.connection.pragma(r);t(this.connection)}catch(r){try{this.close()}catch(n){throw new AggregateError([r,n],"SQLite initialization and rollback both failed.",{cause:n})}throw r}}close(){if(!this.active)return;this.active=!1;let t,r;try{this.connection.close()}catch(n){t=n}try{this.releaseGenerationReader()}catch(n){r=n}if(t!==void 0&&r!==void 0)throw new AggregateError([t,r],"SQLite connection close and generation-reader release both failed.");if(t!==void 0)throw t;if(r!==void 0)throw r}},Xa=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs",".codebaseiq-cache","__pycache__",".venv","venv"],Ii=class{db;config;generation;pathFilter;connection;connectionOwnership;statementCache=new Map;closed=!1;constructor(t,r){this.config=t,this.pathFilter=r??null;let n=rc(t),i=new yr(n.db,n.release);try{i.initialize(tc),this.generation=n.generation,this.connection=n.db,this.connectionOwnership=i,this.db=Za(n.db)}catch(o){try{i.close()}catch(s){throw new AggregateError([o,s],"SQLite construction and rollback both failed.",{cause:s})}throw o}}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
|
|
6
|
-
EXISTS (
|
|
7
|
-
SELECT 1
|
|
8
|
-
FROM defn_enclosing_ranges local_der
|
|
9
|
-
JOIN documents local_d ON local_der.document_id = local_d.id
|
|
10
|
-
WHERE local_der.symbol_id = gs.id
|
|
11
|
-
${this.pathExclusionsFor("local_d").trimStart()}
|
|
12
|
-
)
|
|
13
|
-
OR EXISTS (
|
|
14
|
-
SELECT 1
|
|
15
|
-
FROM mentions local_m
|
|
16
|
-
JOIN chunks local_c ON local_m.chunk_id = local_c.id
|
|
17
|
-
JOIN documents local_d ON local_c.document_id = local_d.id
|
|
18
|
-
WHERE local_m.symbol_id = gs.id
|
|
19
|
-
AND local_m.role = 1
|
|
20
|
-
${this.pathExclusionsFor("local_d").trimStart()}
|
|
21
|
-
)
|
|
22
|
-
)`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(r=>Xa.flatMap(n=>[`AND ${r}.relative_path NOT LIKE '${n}/%'`,`AND ${r}.relative_path NOT LIKE '%/${n}/%'`])).join(`
|
|
23
|
-
`)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...r){return this.statement(t).all(...r)}get(t,...r){return this.statement(t).get(...r)}close(){if(this.closed)return;this.closed=!0,this.statementCache.clear();let t,r;try{ri(this)}catch(n){t=n}try{this.connectionOwnership.close()}catch(n){r=n}if(t!==void 0&&r!==void 0)throw new AggregateError([t,r],"Database-owned resource and SQLite connection cleanup both failed.");if(t!==void 0)throw t;if(r!==void 0)throw r}statement(t){let r=this.statementCache.get(t);return r||(r=this.connection.prepare(t),this.statementCache.set(t,r)),r}};function Za(e){return Object.freeze({prepare(t){let r=e.prepare(t);if(!r.readonly||!r.reader)throw new Error("ScipDatabase.db only permits read-only statements that return rows.");return ec(r)}})}function ec(e){let t={get:(...r)=>e.get(...r),all:(...r)=>e.all(...r),iterate:(...r)=>e.iterate(...r),pluck(r){return r===void 0?e.pluck():e.pluck(r),t},expand(r){return r===void 0?e.expand():e.expand(r),t},raw(r){return r===void 0?e.raw():e.raw(r),t},bind(...r){return e.bind(...r),t},columns:()=>e.columns(),safeIntegers(r){return r===void 0?e.safeIntegers():e.safeIntegers(r),t}};return Object.freeze(t)}function tc(e){if(!e.prepare("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'documents'").get())return;let r=e.prepare("SELECT relative_path FROM documents").iterate();for(let n of r)j(n.relative_path)}function rc(e){for(let t=0;t<4;t+=1){let r=yi(e),n=r.generation,i;try{i=new Qa(ht(n.databasePath),{readonly:!0,fileMustExist:!0})}catch(o){throw r.release(),o}if(n.source==="immutable")return{db:i,generation:n,release:r.release};try{let o=mr(e);if(n.databaseFileIdentity===H(n.databasePath)&&o.source==="legacy"&&o.identity===n.identity&&o.databaseFileIdentity===n.databaseFileIdentity&&o.metadataRaw===n.metadataRaw)return{db:i,generation:n,release:r.release}}catch(o){throw i.close(),r.release(),o}i.close(),r.release()}throw new Error("SQLite index publication changed repeatedly while opening a coherent generation.")}import nc from"ignore";import{existsSync as xi,readdirSync as ic}from"fs";import{dirname as hr,isAbsolute as wi,join as wt,relative as oc,resolve as sc}from"path";function jp(e){let t=nc();return ac(e,t)||t.add(lc),{isIgnored:n=>Sr(t,e,n),filter:n=>n.filter(i=>!Sr(t,e,i))}}function ac(e,t){let r=new Set,n=(s,a)=>{if(!(r.has(s)||!xi(s)))try{let c=R(s,{maxBytes:F,inputKind:"gitignore file"});t.add(a?cc(c,a):c),r.add(s)}catch{}},i=hr(e),o=0;for(;i!==hr(i)&&o<5&&(n(wt(i,".gitignore"),""),!xi(wt(i,".git")));)i=hr(i),o++;return Pi(e,"",t,n),r.size>0}function Pi(e,t,r,n){let i=t?wt(e,t):e;n(wt(i,".gitignore"),t);let o;try{o=ic(i,{withFileTypes:!0})}catch{return}for(let s of o){if(!s.isDirectory()||s.name===".git")continue;let a=t?`${t}/${s.name}`:s.name;Sr(r,e,`${a}/`)||Pi(e,a,r,n)}}function cc(e,t){let r=t.replaceAll("\\","/").replace(/\/+$/,"");return e.split(/\r?\n/).map(n=>dc(n,r)).join(`
|
|
24
|
-
`)}function dc(e,t){let r=e.trimStart();if(!r||r.startsWith("#"))return e;let n=e.slice(0,e.length-r.length),i=r.startsWith("!"),o=i?r.slice(1):r;if(!o||o.startsWith("#"))return e;let s=o.startsWith("/"),a=s?o.slice(1):o,l=(a.endsWith("/")?a.slice(0,-1):a).includes("/")||s?`${t}/${a}`:`${t}/**/${a}`;return`${n}${i?"!":""}${l}`}var lc=`
|
|
25
|
-
# Dependencies
|
|
26
|
-
node_modules/
|
|
27
|
-
vendor/
|
|
28
|
-
.bundle/
|
|
29
|
-
|
|
30
|
-
# Build output
|
|
31
|
-
dist/
|
|
32
|
-
build/
|
|
33
|
-
out/
|
|
34
|
-
target/
|
|
35
|
-
bin/
|
|
36
|
-
obj/
|
|
37
|
-
|
|
38
|
-
# Python
|
|
39
|
-
__pycache__/
|
|
40
|
-
*.pyc
|
|
41
|
-
*.pyo
|
|
42
|
-
.venv/
|
|
43
|
-
venv/
|
|
44
|
-
.env/
|
|
45
|
-
env/
|
|
46
|
-
*.egg-info/
|
|
47
|
-
|
|
48
|
-
# Rust
|
|
49
|
-
target/
|
|
50
|
-
|
|
51
|
-
# Java / Kotlin / Scala
|
|
52
|
-
*.class
|
|
53
|
-
.gradle/
|
|
54
|
-
.mvn/
|
|
55
|
-
|
|
56
|
-
# C# / .NET
|
|
57
|
-
bin/
|
|
58
|
-
obj/
|
|
59
|
-
packages/
|
|
60
|
-
|
|
61
|
-
# Go
|
|
62
|
-
vendor/
|
|
63
|
-
|
|
64
|
-
# Dart
|
|
65
|
-
.dart_tool/
|
|
66
|
-
build/
|
|
67
|
-
|
|
68
|
-
# PHP
|
|
69
|
-
vendor/
|
|
70
|
-
|
|
71
|
-
# IDE / OS
|
|
72
|
-
.idea/
|
|
73
|
-
.vscode/
|
|
74
|
-
*.swp
|
|
75
|
-
*.swo
|
|
76
|
-
.DS_Store
|
|
77
|
-
Thumbs.db
|
|
78
|
-
|
|
79
|
-
# Type definitions (often noise in queries)
|
|
80
|
-
*.d.ts
|
|
81
|
-
`;function Sr(e,t,r){let n=uc(t,r);if(!n)return!1;try{return e.ignores(n)}catch{return!1}}function uc(e,t){if(!t||t===".")return null;if(!wi(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let r=wi(t)?t:sc(e,t),n=oc(e,r).replaceAll("\\","/");return!n||n==="."||n.startsWith("..")?null:n}import{appendFileSync as pc,mkdirSync as fc}from"fs";import{createHash as gc,randomUUID as mc}from"crypto";import{dirname as yc}from"path";import{performance as xe}from"perf_hooks";var ki="CODEBASEIQ_PROFILE",Di="CODEBASEIQ_PROFILE_OUT",Fi="CODEBASEIQ_PROFILE_COMMAND",Ai="CODEBASEIQ_PROFILE_CACHE_STATE",br="CODEBASEIQ_PROFILE_RUN_ID",Ir="CODEBASEIQ_PROFILE_WORKLOAD_IDENTITY",xr="CODEBASEIQ_PROFILE_WORKLOAD_IDENTITY_KIND",Mi=[ki,Di,Fi,Ai,br,Ir,xr],$p=new Set(Mi),Ei=new Set,Ri=new Map,vi=!1;function Be(){let e=process.env[ki];return e==="1"||e==="true"}function hc(){return process.env[Di]}function Ci(){return process.env[Fi]}function Sc(){return process.env[Ai]}function Li(){let e=process.env[br];if(e)return e;if(!Be())return;let t=mc();return process.env[br]=t,t}function Ti(){return process.env[Ir]}function bc(e){let t=Ti();if(t)return t;if(!Be())return;let r=Li();if(!r)return;let n=e.projectFingerprint?"published-project":"run-only",i=Oi(["profile-workload-v1",e.toolVersion,e.command,e.projectFingerprint??r]);return process.env[Ir]=i,process.env[xr]=n,i}function Oi(e){return gc("sha256").update(JSON.stringify(e)).digest("hex").slice(0,24)}function zp(){return Object.fromEntries(Mi.flatMap(e=>{let t=process.env[e];return t===void 0?[]:[[e,t]]}))}function Wp(e,t,r){if(!Be())return t();let n=xe.now();try{let i=t();return Pt({type:"span",name:e,durationMs:Math.round(xe.now()-n),ok:!0,...Et(r)??{}}),i}catch(i){throw Pt({type:"span",name:e,durationMs:Math.round(xe.now()-n),ok:!1,error:i instanceof Error?i.message:String(i),...Et(r)??{}}),i}}async function Hp(e,t,r){if(!Be())return t();let n=xe.now();try{let i=await t();return Pt({type:"span",name:e,durationMs:Math.round(xe.now()-n),ok:!0,...Et(r)??{}}),i}catch(i){throw Pt({type:"span",name:e,durationMs:Math.round(xe.now()-n),ok:!1,error:i instanceof Error?i.message:String(i),...Et(r)??{}}),i}}function Pt(e,t=hc()){let r=Ic(e),n={timestamp:new Date().toISOString(),pid:process.pid,runId:Li(),command:Ci(),cacheState:Sc(),...r,...e},i=`${JSON.stringify(n)}
|
|
82
|
-
`;if(t)try{let o=yc(t);Ei.has(o)||(fc(o,{recursive:!0}),Ei.add(o)),pc(t,i);return}catch(o){vi||(vi=!0,process.stderr.write(`[profile] failed to write ${t}: ${o instanceof Error?o.message:String(o)}
|
|
83
|
-
`));return}Be()&&process.stderr.write(i)}function Ic(e){let t=Ti()??bc({command:Ci()??"unknown",toolVersion:"unknown",projectFingerprint:null});if(!t)return{};let r=process.env[xr],n=typeof e.name=="string"?e.name:void 0;if(!n)return{workloadIdentity:t,workloadIdentityKind:r};let i=n.split(/[.:]/,1)[0]??n,o=`${t}\0${n}`,s=Ri.get(o);return s||(s=Oi(["profile-subsystem-v1",t,n]),Ri.set(o,s)),{workloadIdentity:t,workloadIdentityKind:r,subsystem:i,subsystemWorkIdentity:s}}function Et(e){return typeof e=="function"?e():e}import{createHash as Wo,randomUUID as Sl}from"crypto";import{existsSync as Y,lstatSync as en,mkdirSync as ve,readdirSync as Ho,realpathSync as Uo,renameSync as ge,rmSync as Q,statSync as Gt}from"fs";import{dirname as tn,join as f,resolve as Ze}from"path";import{setTimeout as bl}from"timers/promises";import{pathToFileURL as Bo}from"url";import{deserializeSCIP as Jo}from"@c4312/scip";import Il from"better-sqlite3";import{execFileSync as Qc}from"child_process";import{createHash as Wi}from"crypto";import{closeSync as Yc,fstatSync as Hi,lstatSync as Rr,openSync as Xc,readdirSync as Zc,readFileSync as ed,readlinkSync as td,realpathSync as kt}from"fs";import{isAbsolute as rd,join as vr,relative as nd,resolve as id,sep as od}from"path";import{execFileSync as wr}from"child_process";import{createHash as xc}from"crypto";import{mkdirSync as wc,renameSync as Pc,writeFileSync as Ec}from"fs";import{basename as Rc,dirname as vc,join as kc}from"path";var Dc="git-content-hashes.json",Fc=32*1024*1024,Ac=2e5,Rt=3e4;function Pr(){return{env:bn(),encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:Rt,killSignal:"SIGKILL"}}function ji(e){let t,r;try{t=wr("git",["-C",e,"ls-files","-s","-z","--","."],{...Pr(),timeout:Rt}),r=wr("git",["-C",e,"status","--porcelain=v1","-z","--untracked-files=all","--no-renames","--","."],{...Pr(),timeout:Rt})}catch{return null}let n=new Map,i=[];for(let l of t.split("\0")){if(!l)continue;let u=l.indexOf(" "),p=u>0?l.slice(0,u).split(" "):[];if(p.length!==3)continue;let[m,g,D]=p,x=l.slice(u+1);if(m!=="100644"&&m!=="100755"||D!=="0"){n.delete(x);continue}n.set(x,g),Rc(x)===".gitattributes"&&i.push(`${x}:${g}`)}let o=new Set;for(let l of r.split("\0"))l.length>=4&&l[2]===" "&&o.add(l.slice(3));let s=Mc(e,i),a=kc(Wt(e),Dc),c=Cc(a,s),d=new Map;return{lookup(l){if(o.has(l))return;let u=n.get(l);if(u)return d.get(u)??c.entries[u]},seed(l,u){if(o.has(l))return;let p=n.get(l);!p||c.entries[p]||d.has(p)||d.set(p,u)},persist(){if(d.size===0)return;let l=new Set(n.values()),u={};for(let[p,m]of Object.entries(c.entries))l.has(p)&&(u[p]=m);for(let[p,m]of d)u[p]=m;if(!(Object.keys(u).length>Ac))try{wc(vc(a),{recursive:!0});let p=`${a}.${process.pid}.tmp`;Ec(p,JSON.stringify({version:1,salt:s,entries:u})),Pc(p,a)}catch{}}}}function Mc(e,t){let r="";try{r=wr("git",["-C",e,"config","--get-regexp","^core\\.(autocrlf|eol|safecrlf)$"],{...Pr(),timeout:Rt})}catch{}return xc("sha256").update(JSON.stringify([r.trim(),t.sort()])).digest("hex")}function Cc(e,t){let r={version:1,salt:t,entries:{}};try{let n=R(e,{maxBytes:Fc,inputKind:"git-content-hash-store"}),i=JSON.parse(n);if(i.version!==1||i.salt!==t||!i.entries||typeof i.entries!="object")return r;let o={};for(let[s,a]of Object.entries(i.entries))/^[0-9a-f]{40,64}$/.test(s)&&a&&typeof a.size=="number"&&Number.isInteger(a.size)&&a.size>=0&&typeof a.hash=="string"&&/^[0-9a-f]{64}$/.test(a.hash)&&(o[s]={size:a.size,hash:a.hash});return{version:1,salt:t,entries:o}}catch{return r}}import{AsyncLocalStorage as Lc}from"async_hooks";var Tc=new Lc;function we(e,t){let r=vt(e);if(!r||r.missing.has(t))return;let n=r.files.get(t);if(n)return n;let i=r.readBaseFile?.(t);return i&&r.files.set(t,i),i}function Pe(e,t){let r=vt(e);if(r)return r.missing.has(t)?"missing":r.paths.includes(t)?"present":"missing"}function _i(e,t){return vt(e)?.fingerprints.get(t)}function ue(e){return vt(e)?.paths}function vt(e){let t=Tc.getStore();if(t)return t.projectRoot===xn(e)?t:void 0}import{createRequire as Oc}from"module";import{existsSync as jc,readdirSync as _c,statSync as Gc}from"fs";import y from"path";var Nc=Oc(import.meta.url),Gi=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Bc(e,t=[]){let r=y.resolve(e),n=t.flatMap(c=>$c(r,c));if(n.length>0)return Ni(r,qi(n));let i=qc(r),o=qi(i),s=zc(r,o)?[r,...o]:o,a=s.length>0?s:[r];return Ni(r,a)}function $i(e,t,r=[]){let n;try{n=Nc("ts-morph")}catch{return null}let i=y.resolve(e),o=t==="workspace"?Bc(i,r):["."],s=new Set;for(let a of o){let c=a==="."?i:y.join(i,a),d=y.join(c,"tsconfig.json"),l=Jc(n.ts,i);if(!l.fileExists(d))return null;let u=n.ts.readConfigFile(d,l.readFile);if(u.error)return null;let p=n.ts.parseJsonConfigFileContent(u.config,l,c);if(p.errors.length>0)return null;for(let m of p.fileNames){let g=y.resolve(m);O(i,g)&&s.add(y.relative(i,g).split(y.sep).join("/"))}}return s}function Ni(e,t){return[...new Set(t.map(r=>qe(e,r)))].sort((r,n)=>r.localeCompare(n))}function qc(e){let t=ue(e);if(t)return t.flatMap(i=>{if(i.split("/").some(s=>Gi.has(s)))return[];let o=y.join(e,...i.split("/"));return Bi(e,o)?[y.dirname(o)]:[]});let r=[],n=[e];for(;n.length>0;){let i=n.pop(),o;try{o=_c(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=y.join(i,s.name);if(s.isDirectory()){!Gi.has(s.name)&&!s.name.startsWith(".")&&n.push(a);continue}s.isFile()&&Bi(e,a)&&r.push(y.dirname(a))}}return r}function $c(e,t){let r=t.trim();if(!r)return[];let n=y.resolve(e,r);if(!O(e,n))return[];let i=ue(e);if(i){let o=qe(e,n);if(i.includes(o)&&Er(y.basename(n)))return[y.dirname(n)];let s=o==="."?"":`${o}/`;return i.some(a=>a.startsWith(s))?[n]:[]}try{let o=Gc(n);if(o.isDirectory())return[n];if(o.isFile()&&Er(y.basename(n)))return[y.dirname(n)]}catch{return[]}return[]}function Bi(e,t){if(!Er(y.basename(t)))return!1;let r=zi(e,t);return r?y.basename(t)==="tsconfig.json"||"include"in r||"files"in r||"references"in r:!1}function Er(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function qi(e){let t=[...new Set(e.map(r=>y.resolve(r)))].sort((r,n)=>r.localeCompare(n));return t.length<=1?t:t.filter(r=>!t.some(n=>n!==r&&Kc(r,n)))}function zc(e,t){if(t.length===0||t.some(n=>y.resolve(n)===e))return!1;let r=y.join(e,"tsconfig.json");return Hc(e,r)&&Wc(e,r)}function Wc(e,t){let n=zi(e,t)?.include;return Array.isArray(n)?n.some(i=>typeof i=="string"&&i.trim()!==""&&!i.startsWith("!")&&(i.includes("/")||i.includes("**")||!y.extname(i))):!1}function zi(e,t){try{let r=JSON.parse(Uc(e,t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function Hc(e,t){let r=qe(e,t),n=Pe(e,r);return n?n==="present":jc(t)}function Uc(e,t){let r=qe(e,t);if(ue(e)){let i=we(e,r);if(!i)throw Object.assign(new Error(`Snapshot file ${r} is missing.`),{code:"ENOENT"});return i.content.toString("utf8")}return S(t,"TypeScript project config")}function Jc(e,t){let r=ue(t);if(!r)return e.sys;let n=y.resolve(t),i=new Set(r),o=Vc(n,r),s=e,a=c=>{let d=y.resolve(c);return O(n,d)?qe(n,d):null};return{useCaseSensitiveFileNames:e.sys.useCaseSensitiveFileNames,fileExists(c){let d=a(c);return d===null?e.sys.fileExists(c):i.has(d)},readFile(c){let d=a(c);return d===null?e.sys.readFile(c):we(n,d)?.content.toString("utf8")},readDirectory(c,d,l,u,p){let m=y.resolve(c);return O(n,m)?s.matchFiles(m,d,l,u,e.sys.useCaseSensitiveFileNames,n,p,g=>o.get(y.resolve(g))??{files:[],directories:[]},g=>g):e.sys.readDirectory(c,d,l,u,p)}}}function Vc(e,t){let r=new Map,n=new Map,i=o=>{r.has(o)||r.set(o,new Set),n.has(o)||n.set(o,new Set)};i(e);for(let o of t){let s=o.split("/"),a=e;for(let c=0;c<s.length-1;c+=1){let d=s[c];i(a),n.get(a).add(d),a=y.join(a,d),i(a)}r.get(a).add(s.at(-1))}return new Map([...r].map(([o,s])=>[o,{files:[...s].sort(),directories:[...n.get(o)??[]].sort()}]))}function qe(e,t){let r=y.relative(e,t);return r?r.split(y.sep).join("/"):"."}function Kc(e,t){let r=y.relative(e,t);return!!r&&!r.startsWith("..")&&!y.isAbsolute(r)}var Dt=64*1024*1024,$e=class extends Error{constructor(r,n,i,o){super(`${r} ${JSON.stringify(n)} is ${i} bytes; the safety limit is ${o} bytes`);this.inputKind=r;this.inputPath=n;this.observedBytes=i;this.limitBytes=o;this.name="InputTooLargeError"}inputKind;inputPath;observedBytes;limitBytes;code="CODEBASEIQ_INPUT_TOO_LARGE"};function sd(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,r)=>t.localeCompare(r))}function Ui(e,t,r={}){let n=j(t),i=kt(e),o=id(i,...n.split("/"));if(!O(i,o)||o===i)throw new v(t,"outside-project");let s=kt(o);if(!O(i,s)||s===i)throw new v(t,"outside-project");let a=Rr(s);if(!a.isFile())throw new v(t,"not-a-file");let c={projectRoot:i,relativePath:n,absolutePath:s,size:a.size,mtimeMs:a.mtimeMs,device:a.dev,inode:a.ino},d=r.maxBytes??Dt;if(Ji(d),c.size>d)throw new $e(r.inputKind??"project file",c.relativePath,c.size,d);return c}function ad(e,t,r={}){let n=j(t),i=Pe(e,n);if(i){if(i==="missing")throw Object.assign(new Error(`Snapshot project file ${JSON.stringify(n)} does not exist.`),{code:"ENOENT"});let c=we(e,n);if(!c)throw new v(n,"changed-during-read");let d=r.maxBytes??Dt;if(Ji(d),c.size>d)throw new $e(r.inputKind??"project file",n,c.size,d);return Buffer.from(c.content)}let o=Ui(e,t,r),s=r.maxBytes??Dt,a=Xc(o.absolutePath,"r");try{let c=Hi(a);if(!c.isFile()||c.dev!==o.device||c.ino!==o.inode||c.size!==o.size)throw new v(t,"changed-during-read");if(c.size>s)throw new $e(r.inputKind??"project file",o.relativePath,c.size,s);let d=ed(a),l=Hi(a);if(l.dev!==c.dev||l.ino!==c.ino||l.size!==c.size||d.byteLength!==c.size)throw new v(t,"changed-during-read");return d}finally{Yc(a)}}function wf(e,t,r={}){return ad(e,t,r).toString("utf8")}function kr(e){return typeof e=="object"&&e!==null&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function Pf(e,t){try{return Ui(e,t),!0}catch(r){if(kr(r))return!1;throw r}}function Ji(e){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`maxBytes must be a non-negative safe integer; received ${e}`)}function cd(e){return(ue(e)??fd(e)??gd(e)).filter(t=>t&&!Fr(t)).sort()}function dd(e,t={}){let r=(t.includePaths??[]).map(j),n=[...new Set([...cd(e),...r])].filter(c=>!Fr(c)).filter(c=>!t.language||Bn(c,t.language,t.markerFiles)).filter(c=>!t.includePath||t.includePath(c)).sort(),i=kt(e),o,s=()=>o??=ji(i),a=n.flatMap(c=>{let d=_i(e,c);if(d)return[{path:c,size:d.fingerprintSize??d.size,hash:d.sha256}];let l=Pe(e,c);if(l==="present"){let g=we(e,c);if(g)return[{path:c,size:g.fingerprintSize??g.size,hash:g.sha256}]}let u=l===void 0?s():null,p=u?.lookup(c);if(p)return[{path:c,size:p.size,hash:p.hash}];let m=vr(e,c);try{if(Rr(m).isSymbolicLink()){let ee=kt(m),Bt=nd(i,ee);if(Bt===".."||Bt.startsWith(`..${od}`)||rd(Bt))throw new Error("external symlink");let Sn=td(m);return[{path:c,size:Buffer.byteLength(Sn),hash:Wi("sha256").update("symlink\0").update(Sn).digest("hex")}]}let g=Wi("sha256"),D=it(m,{inputKind:"project fingerprint input",maxBytes:Dt},ee=>g.update(ee)),x=g.digest("hex");return u?.seed(c,{size:D,hash:x}),[{path:c,size:D,hash:x}]}catch(g){return kr(g)?[]:[{path:c,size:-1,hash:"unreadable"}]}});return o?.persist(),a}function Dr(e,t,r){let n=Ft(t,r),i=[...n.typescriptProjects.filter(s=>ud(e,s)),...n.clojureConfigPath?[n.clojureConfigPath]:[]],o=n.languages.includes("typescript")?$i(e,n.typescriptProjectMode,n.typescriptProjects):null;return{...n,files:dd(e,{includePath:s=>{let a=Vt(s,t,i);return a==="other"?!1:a!=="source"||!ld(s)||!o?!0:o.has(s)},includePaths:i})}}function ld(e){return/\.(?:[cm]?[jt]sx?|vue)$/iu.test(e)}function ud(e,t){let r;try{r=j(t)}catch{return!1}let n=Pe(e,r);if(n)return n==="present";try{return Rr(vr(e,r)).isFile()}catch(i){if(kr(i))return!1;throw i}}function Ft(e,t){return{version:3,languages:[...e].sort(),pnpmWorkspaces:t.typescriptProjectMode!=="workspace"&&t.pnpmWorkspaces===!0,typescriptProjectMode:t.typescriptProjectMode??"single",typescriptProjects:sd(t.typescriptProjects),clojureConfigPath:pd(t.clojureConfigPath)}}function pd(e){return e?.trim()||void 0}function fd(e){try{return Qc("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"}).split(`
|
|
84
|
-
`).filter(Boolean)}catch{return null}}function gd(e){let t=[],r=[""];for(;r.length>0;){let n=r.pop(),i=n?vr(e,n):e,o;try{o=Zc(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=n?`${n}/${s.name}`:s.name;if(s.isDirectory()){Fr(a)||r.push(a);continue}t.push(a)}}return t}function Fr(e){let t=e.split("/");return e==="meta.json"||t[0]===".codebaseiq"&&(t[1]==="events"||t[1]==="ledger"||t[1]==="releases"||t[1]==="suppressions")||t.some(r=>md.has(r))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var md=new Set([".git","node_modules",".codebaseiq-cache",".codebaseiq-generations",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);import{execFileSync as yd}from"child_process";import{existsSync as hd,readdirSync as Ki}from"fs";import{extname as Qi,join as Yi}from"path";var Xi=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Sd=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function Ar(e){let t=[],r=bd(e),n=Pd(e);for(let i of Sd){if(Id(e,i.files)){t.push(i.language);continue}if(xd(r,i.globs)){t.push(i.language);continue}Rd(n,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Vi(t,"javascript"),t.includes("cpp")&&!n.has(".c")&&Vi(t,"c"),t}function bd(e){try{return Ki(e)}catch{return[]}}function Id(e,t){return t?.length?t.some(r=>hd(Yi(e,r))):!1}function xd(e,t){return t?.length?e.some(r=>t.some(n=>wd(r,n))):!1}function wd(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[r,n]=t.split("*");return e.startsWith(r??"")&&e.endsWith(n??"")}function Pd(e){let t=Ed(e);if(t)return t;let r=new Set,n=[e];for(;n.length>0;){let i=n.pop();if(!i)continue;let o;try{o=Ki(i,{withFileTypes:!0})}catch{continue}for(let s of o){if(s.name.startsWith(".")&&!s.name.endsWith("proj")&&!s.name.endsWith("sln")&&s.isDirectory())continue;let a=Yi(i,s.name);if(s.isDirectory()){Xi.has(s.name)||n.push(a);continue}let c=Qi(s.name).toLowerCase();c&&r.add(c)}}return r}function Ed(e){try{let t=yd("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"}),r=new Set;for(let n of t.split(`
|
|
85
|
-
`)){if(!n||n.split("/").some(o=>Xi.has(o)))continue;let i=Qi(n).toLowerCase();i&&r.add(i)}return r}catch{return null}}function Rd(e,t){return t?.length?t.some(r=>e.has(r)):!1}function Vi(e,t){let r=e.indexOf(t);r!==-1&&e.splice(r,1)}import{lstatSync as Nd,readdirSync as Bd}from"fs";import{join as qd,relative as $d,resolve as Nr,sep as zd}from"path";import{createHash as vd}from"crypto";import{existsSync as ze,mkdirSync as kd,readdirSync as Zi,renameSync as Dd,rmSync as eo,writeFileSync as Fd}from"fs";import{join as U}from"path";import{create as ro,fromBinary as no,toBinary as Ad}from"@bufbuild/protobuf";import{deserializeSCIP as At,DocumentSchema as Cr,IndexSchema as io,serializeSCIP as oo}from"@c4312/scip";var Mt=1,We="typescript-scip-fragments";function jf(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,r=[];for(let o of e){let s=pe(o.relativePath);if(t.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(t.add(s),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${s}`);let a=no(Cr,o.bytes);if(a.relativePath!==s)throw new Error(`TypeScript fragment path mismatch: expected ${s}, got ${a.relativePath}`);r.push(a)}let n=oo(ro(io,{documents:r,externalSymbols:[]})),i=At(n);if(i.documents.length!==r.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return n}function He(e){let t=U(e,We);return{rootDir:t,blobDir:U(t,"blobs"),generationDir:U(t,"generations")}}function Md(e){let t=At(e.indexBytes);mo(t.metadata,yo(e)),go(t.externalSymbols);let r=new Set,n=[];for(let o of t.documents){let s=pe(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript SCIP document path: ${s}`);r.add(s);let a=Ad(Cr,o),c=e.documentIdentities.get(s)??(e.allowUntrackedDocuments?fe(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:s,contentHash:fe(a)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${s}`);n.push(lo(e.cacheDir,{relativePath:s,bytes:a,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=uo(e,n);return po(e.cacheDir,i),i}function _f(e){let t=He(e.cacheDir);if(!ze(Tr(t,e.generationIdentity)))return Md(e);let r=so({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&r.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let n of r.manifest.documents){let i=e.documentIdentities.get(n.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==n.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${n.relativePath}`)}return r.manifest}function Gf(e){let t=so({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,r=new Map(t.documents.map(o=>[o.relativePath,o])),n=new Set;for(let o of e.fragments){let s=pe(o.relativePath);if(n.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(n.add(s),!r.has(s))throw new Error(`TypeScript fragment replacement has no prior document: ${s}`);let a=e.documentIdentities.get(s);if(!a)throw new Error(`missing TypeScript document identity: ${s}`);o.bytes===null?r.delete(s):r.set(s,lo(e.cacheDir,o,a))}if(n.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=uo(e,[...r.values()]);return po(e.cacheDir,i),i}function so(e){let t=He(e.cacheDir),r=Tr(t,e.generationIdentity),n;try{n=Lr(R(r,{maxBytes:F,inputKind:"TypeScript fragment manifest"}))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(n.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&n.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&n.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of n.documents){let s=U(t.blobDir,`${o.blobHash}.scipdoc`),a=C(s,{maxBytes:me,inputKind:"TypeScript fragment blob"});if(a.byteLength!==o.byteLength||fe(a)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,a)}return{manifest:n,fragments:i}}function ao(e){let t=co(e);return Mr(t.baseIndex,t.completeDocuments,"assembled")}function Nf(e){let t=co(e);return Cd(t.deletedAffectedPaths),{completeIndexBytes:Mr(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:Mr(t.baseIndex,t.affectedDocuments,"affected")}}function co(e){let t=At(e.baseIndexBytes);mo(t.metadata,yo(e)),go(t.externalSymbols);let r=new Map;for(let a of e.fragments){let c=pe(a.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);r.set(c,a)}if(r.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let n=new Set,i=[],o=[],s=[];for(let a of t.documents){let c=pe(a.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);n.add(c);let d=r.get(c);if(!d){i.push(a);continue}if(r.delete(c),d.bytes===null){s.push(c);continue}let l=no(Cr,d.bytes);if(l.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${l.relativePath}`);i.push(l),o.push(l)}if(r.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...r.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:s}}function Mr(e,t,r){let n=oo(ro(io,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=At(n);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${r} TypeScript SCIP index failed structural verification`);return n}function Cd(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Bf(e,t){let r=He(e);if(!ze(r.generationDir))return;let n=new Set(t.map(s=>fo(s))),i=Zi(r.generationDir).filter(s=>s.endsWith(".json")),o=new Set;for(let s of i.filter(a=>n.has(a))){let a=Lr(R(U(r.generationDir,s),{maxBytes:F,inputKind:"TypeScript fragment manifest"}));for(let c of a.documents)o.add(`${c.blobHash}.scipdoc`)}for(let s of i)n.has(s)||eo(U(r.generationDir,s),{force:!0});if(ze(r.blobDir))for(let s of Zi(r.blobDir))o.has(s)||eo(U(r.blobDir,s),{force:!0})}function lo(e,t,r){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let n=pe(t.relativePath),i=Buffer.from(t.bytes),o=fe(i),s=He(e);kd(s.blobDir,{recursive:!0});let a=U(s.blobDir,`${o}.scipdoc`);if(ze(a)){let c=C(a,{maxBytes:me,inputKind:"TypeScript fragment blob"});if(c.byteLength!==i.byteLength||fe(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${n}`)}else{let c=`${a}.${process.pid}.${Date.now()}.tmp`;Fd(c,i),Dd(c,a)}return{relativePath:n,blobHash:o,byteLength:i.byteLength,documentIdentity:r}}function uo(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let r=[...t].sort((n,i)=>n.relativePath.localeCompare(i.relativePath));if(new Set(r.map(n=>n.relativePath)).size!==r.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:Mt,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:r}}function po(e,t){let r=He(e),n=Tr(r,t.generationIdentity);if(ze(n)){let i=Lr(R(n,{maxBytes:F,inputKind:"TypeScript fragment manifest"}));if(to(i)!==to(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}V(n,t,{spacing:2,trailingNewline:!0})}function to(e){return fe(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Lr(e){let t=JSON.parse(e);if(t.version!==Mt||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let r=new Set;for(let n of t.documents){if(!n||typeof n.relativePath!="string"||typeof n.blobHash!="string"||!/^[a-f0-9]{64}$/.test(n.blobHash)||typeof n.byteLength!="number"||!Number.isInteger(n.byteLength)||n.byteLength<0||typeof n.documentIdentity!="string"||!n.documentIdentity)throw new Error("invalid TypeScript fragment record");if(pe(n.relativePath),r.has(n.relativePath))throw new Error("duplicate TypeScript fragment record");r.add(n.relativePath)}return t}function Tr(e,t){return U(e.generationDir,fo(t))}function fo(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${fe(e)}.json`}function go(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function mo(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let r=e,n=r.toolInfo??r.tool_info;if(!n||typeof n!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=n;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function yo(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function pe(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function fe(e){return vd("sha256").update(e).digest("hex")}import{createHash as Ld}from"crypto";import{existsSync as Ue,mkdirSync as Td,readdirSync as Or,renameSync as Od,rmSync as ho,writeFileSync as jd}from"fs";import{join as G}from"path";var Ct=1,Vf=64*1024*1024,Ve="typescript-scip-overlays";function Kf(e){let t=bo(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let r=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),n=new Set;for(let o of e.fragments){let s=Gr(o.relativePath);if(n.has(s))throw new Error(`duplicate TypeScript overlay: ${s}`);n.add(s),r.set(s,_d(e.cacheDir,o))}if(n.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Ct,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...r.values()].sort((o,s)=>o.relativePath.localeCompare(s.relativePath))};return Gd(e.cacheDir,i),i}function Qf(e){let t=bo(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let r=t.overlays.map(n=>{if(n.blobHash===null)return{relativePath:n.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=C(G(Ke(e.cacheDir),"blobs",`${n.blobHash}.scipdoc`),{maxBytes:me,inputKind:"TypeScript overlay blob"});if(i.byteLength!==n.byteLength||Je(i)!==n.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${n.relativePath}`);return{relativePath:n.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return ao({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:r})}function Yf(e,t){let r=Ke(e),n=G(r,"generations");if(!Ue(n))return;let i=new Set(t.map(_r)),o=new Set;for(let a of Or(n).filter(c=>i.has(c))){let c=jr(R(G(n,a),{maxBytes:F,inputKind:"TypeScript overlay manifest"}));for(let d of c.overlays)d.blobHash&&o.add(`${d.blobHash}.scipdoc`)}for(let a of Or(n))i.has(a)||ho(G(n,a),{force:!0});let s=G(r,"blobs");if(Ue(s))for(let a of Or(s))o.has(a)||ho(G(s,a),{force:!0})}function bo(e,t){let r=G(Ke(e),"generations",_r(t));if(!Ue(r))return null;let n=jr(R(r,{maxBytes:F,inputKind:"TypeScript overlay manifest"}));if(n.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return n}function _d(e,t){let r=Gr(t.relativePath);if(t.bytes===null)return{relativePath:r,blobHash:null,byteLength:0};let n=Buffer.from(t.bytes),i=Je(n),o=G(Ke(e),"blobs");Td(o,{recursive:!0});let s=G(o,`${i}.scipdoc`);if(Ue(s)){let a=C(s,{maxBytes:me,inputKind:"TypeScript overlay blob"});if(a.byteLength!==n.byteLength||Je(a)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${r}`)}else{let a=`${s}.${process.pid}.${Date.now()}.tmp`;jd(a,n),Od(a,s)}return{relativePath:r,blobHash:i,byteLength:n.byteLength}}function Gd(e,t){let r=G(Ke(e),"generations",_r(t.generationIdentity));if(Ue(r)){let n=jr(R(r,{maxBytes:F,inputKind:"TypeScript overlay manifest"}));if(So(n)!==So(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}V(r,t,{spacing:2,trailingNewline:!0})}function jr(e){let t=JSON.parse(e);if(t.version!==Ct||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let r=new Set;for(let n of t.overlays){if(!n||typeof n.relativePath!="string"||n.blobHash!==null&&(typeof n.blobHash!="string"||!/^[a-f0-9]{64}$/.test(n.blobHash))||!Number.isInteger(n.byteLength)||n.byteLength<0||n.blobHash===null&&n.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(Gr(n.relativePath),r.has(n.relativePath))throw new Error("duplicate TypeScript overlay record");r.add(n.relativePath)}return t}function Ke(e){return G(e,Ve)}function _r(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${Je(e)}.json`}function So(e){return Je(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Gr(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function Je(e){return Ld("sha256").update(e).digest("hex")}var Qe=1,Br="language-indexes",Io=["index.db","index.scip","meta.json"],xo=[Br,We,Ve];function Lt(e){let t=[];for(let r of Io)Wd(e,r),t.push(r);for(let r of xo)wo(e,r,t);return{version:Qe,files:t.sort()}}function Tt(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(n=>!n||n==="."||n===".."))throw new Error(`invalid index artifact path: ${e}`);let r=t[0];if(!Io.includes(e)&&!xo.includes(r))throw new Error(`index artifact path is not shareable: ${e}`);return e}function z(e,t){let r=Tt(t),n=Nr(e),i=Nr(n,...r.split("/"));if(i!==n&&!i.startsWith(`${n}${zd}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function wo(e,t,r){let n=qd(e,t),i;try{i=Bd(n,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let s=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${s}`);o.isDirectory()?wo(e,s,r):o.isFile()&&r.push(Tt(s))}}function Wd(e,t){let r=z(e,t),n;try{n=Nd(r)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!n.isFile()||n.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if($d(Nr(e),r).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{writeFileSync as qr}from"fs";import{create as Ee}from"@bufbuild/protobuf";import{deserializeSCIP as $r,serializeSCIP as zr,DocumentSchema as Vd,IndexSchema as Ro,MetadataSchema as vo,SymbolInformationSchema as Kd}from"@c4312/scip";import{create as Po}from"@bufbuild/protobuf";import{DocumentSchema as Hd,IndexSchema as Ud,SymbolRole as Jd}from"@c4312/scip";function Eo(e){let t=new Set,r=new Map;for(let s of e.documents){r.set(s,j(s.relativePath));for(let a of s.symbols)a.symbol&&t.add(a.symbol)}for(let s of e.externalSymbols)s.symbol&&t.add(s.symbol);let n=0,i=0,o=[];for(let s of e.documents){let a=r.get(s),c=s.occurrences.filter(d=>(d.symbolRoles&Jd.Definition)===0||t.has(d.symbol)?!0:(n+=1,!1));if(a===s.relativePath&&c.length===s.occurrences.length){o.push(s);continue}i+=1,o.push(Po(Hd,{language:s.language,relativePath:a,occurrences:c,symbols:s.symbols,text:s.text,positionEncoding:s.positionEncoding}))}return{index:i===0?e:Po(Ud,{metadata:e.metadata,documents:o,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:i}}function ko(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Yd(e),r=Xd(e.flatMap(i=>i.documents??[])),n=Fo(e.flatMap(i=>i.externalSymbols??[]));return Ee(Ro,{metadata:t,documents:r,externalSymbols:n})}function gg(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let r=e.map(i=>$r(C(i,{inputKind:"SCIP merge input",maxBytes:T}))),n=ko(r);return qr(t,Buffer.from(zr(n))),{documentCount:n.documents.length,externalSymbolCount:n.externalSymbols.length,inputCount:e.length}}function mg(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let r=e.map(i=>$r(C(i,{inputKind:"SCIP merge input",maxBytes:T}))),n=Eo(ko(r));return qr(t,Buffer.from(zr(n.index))),{documentCount:n.index.documents.length,externalSymbolCount:n.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Qd(e,t,r){let n=e.metadata;if(!n)throw new Error("Cannot rebase a SCIP index without metadata");if(!be(n.projectRoot,t))throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${n.projectRoot}`);return Ee(Ro,{metadata:Ee(vo,{...n,projectRoot:r}),documents:e.documents,externalSymbols:e.externalSymbols})}function Do(e,t,r){let n=$r(C(e,{inputKind:"SCIP normalization input",maxBytes:T})),i=Qd(n,t,r);qr(e,Buffer.from(zr(i)))}function Yd(e){let t=e[0]?.metadata;if(!t)return;let r=t.projectRoot;for(let i of e.slice(1)){let o=i.metadata?.projectRoot;if(r&&o&&!be(o,r))throw new Error(`Cannot merge SCIP indexes with different project roots: ${r} vs ${o}`)}let n=r&&st(r);return n===r?t:Ee(vo,{...t,projectRoot:n})}function Xd(e){let t=new Map;for(let r of e){let n=t.get(r.relativePath);if(!n){t.set(r.relativePath,r);continue}t.set(r.relativePath,Ee(Vd,{language:n.language||r.language,relativePath:n.relativePath||r.relativePath,occurrences:Zd([...n.occurrences,...r.occurrences]),symbols:Fo([...n.symbols,...r.symbols]),text:tl(n.text,r.text),positionEncoding:n.positionEncoding||r.positionEncoding}))}return[...t.values()]}function Zd(e){let t=new Set,r=[];for(let n of e){let i=JSON.stringify(n);t.has(i)||(t.add(i),r.push(n))}return r}function Fo(e){let t=new Map;for(let r of e){let n=t.get(r.symbol);if(!n){t.set(r.symbol,r);continue}t.set(r.symbol,Ee(Kd,{symbol:n.symbol,documentation:rl([...n.documentation,...r.documentation]),relationships:el([...n.relationships,...r.relationships]),kind:n.kind||r.kind,displayName:n.displayName||r.displayName,enclosingSymbol:n.enclosingSymbol||r.enclosingSymbol,signatureDocumentation:n.signatureDocumentation??r.signatureDocumentation}))}return[...t.values()]}function el(e){let t=new Set,r=[];for(let n of e){let i=[n.symbol,n.isReference?"1":"0",n.isImplementation?"1":"0",n.isTypeDefinition?"1":"0",n.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),r.push(n))}return r}function tl(e,t){return e?t?e.length>=t.length?e:t:e:t}function rl(e){return[...new Set(e)]}import{createHash as Kr}from"crypto";import{closeSync as nl,existsSync as b,mkdirSync as il,openSync as ol,readSync as sl,readdirSync as Qr,renameSync as Jr,rmSync as Ye,statSync as Re}from"fs";import{basename as Lo,dirname as W,join as h,relative as Ao}from"path";var Vr=Object.freeze({maxGenerations:2,maxLogicalBytes:2*1024*1024*1024});function To(e){let t=P(e.outputDb),r=ul(e);e.onStage?.("after-recovery-retained");let n=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=Zr({generationRoot:t,databasePath:e.tempOutputDb,indexPath:b(n)?n:void 0,metadataPath:b(e.tempMetaPath)?e.tempMetaPath:void 0}),o=(e.now??(()=>new Date))().toISOString(),s={version:le,currentGeneration:i.identity,artifactSet:"immutable-v1",...r?{previousGeneration:r}:{},...e.publication?{publication:e.publication}:{},publishedAt:o},a=B(h(t,"state.json"),s,{spacing:2,trailingNewline:!0});e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||Ur(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Ur(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Ur(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let c=i.identity,d={...s,stableMirrors:Xr(e.outputDb,e.outputScip)};B(h(t,"state.json"),d,{spacing:2,trailingNewline:!0});let l=Oo(e.outputDb,{now:e.now}),u=E(i.directorySync,a.directorySync);return{currentGeneration:c,...r?{previousGeneration:r}:{},retention:l,achievedDurability:u==="synced"?"directory-durable":"file-flushed",directorySync:u}}function al(e,t,r,n=()=>new Date){if(!b(e))return null;let i=$(e),o=h(P(e),"state.json");if(i?.artifactSet==="immutable-v1"&&Ge(e,i.currentGeneration))return i;let s=P(e),a=!i&&b(o)?fl(r,e,t):void 0;if(a&&!Ne(s,a))return null;let c=Zr({generationRoot:s,databasePath:e,indexPath:b(t)?t:void 0,metadataPath:b(r)?r:void 0,forcedIdentity:i?.currentGeneration??a}),d={version:le,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:Xr(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??n().toISOString()};return B(h(s,"state.json"),d,{spacing:2,trailingNewline:!0}),d}function Dg(e,t,r=()=>new Date){if(!b(e)||!b(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let n=$(e),i=P(e),o=Zr({generationRoot:i,databasePath:e,indexPath:b(h(W(e),"index.scip"))?h(W(e),"index.scip"):void 0,metadataPath:t}),s=n&&n.currentGeneration!==o.identity?Go(e,n.currentGeneration):void 0,a={version:le,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:Xr(e,h(W(e),"index.scip")),...s?{previousGeneration:s}:{},...n?.publication?{publication:n.publication}:{},publishedAt:r().toISOString()};return B(h(P(e),"state.json"),a,{spacing:2,trailingNewline:!0}),Oo(e,{now:r}),a}function Oo(e,t={}){let r=cl(t.limits),i=(t.now??(()=>new Date))().toISOString(),o=q(_e(e),{waitMs:0});if(!o)return{state:"deferred",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:r,at:i,reason:"another process owns local generation retention"};try{let s=$(e),a=jo(e),c=gr(e,a.map(x=>x.identity),{isProcessAlive:t.isProcessAlive??te,readProcessIdentity:t.readProcessIdentity??ne}),d=new Set(c.protectedGenerations);s?.currentGeneration&&d.add(s.currentGeneration),s?.previousGeneration?.generationIdentity&&d.add(s.previousGeneration.generationIdentity);let l=a.length,u=a.reduce((x,ee)=>x+ee.logicalBytes,0),p=0,m=0;for(let x of a){if(l<=r.maxGenerations&&u<=r.maxLogicalBytes)break;d.has(x.identity)||(t.onBeforeRemove?.(x.identity),Ye(x.path,{recursive:!0,force:!0}),l-=1,u-=x.logicalBytes,p+=1,m+=x.logicalBytes)}let g=l>r.maxGenerations||u>r.maxLogicalBytes,D={state:g?"protected":p>0?"collected":"within-bounds",generationCount:l,logicalBytes:u,protectedGenerations:d.size,activeReaderLeases:c.activeLeases,staleReaderLeasesRemoved:c.staleLeasesRemoved,malformedReaderLeases:c.malformedLeases,removedGenerations:p,removedLogicalBytes:m,limits:r,at:i,...g?{reason:c.malformedLeases>0?"malformed reader ownership evidence fails closed":"retention bounds cannot be met without deleting a protected generation"}:{}};return Mo(e,D),D}catch(s){let a={state:"error",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:r,at:i,reason:s instanceof Error?s.message:String(s)};try{Mo(e,a)}catch{}return a}finally{o.release()}}function Fg(e){let t=P(e);if(!b(t))return{state:"absent",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,malformedReaderLeases:0,limits:{...Vr},reason:"local immutable generation store does not exist"};let r=dl(e),n=r?.limits??{...Vr},i=q(_e(e),{waitMs:0});if(!i)return{state:"deferred",generationCount:r?.generationCount??0,logicalBytes:r?.logicalBytes??0,protectedGenerations:r?.protectedGenerations??0,activeReaderLeases:r?.activeReaderLeases??0,malformedReaderLeases:r?.malformedReaderLeases??0,limits:n,...r?{lastCollection:r}:{},reason:"another process owns local generation retention"};try{let o=jo(e),s=$(e),a=gr(e,o.map(d=>d.identity),{isProcessAlive:te,readProcessIdentity:ne},{removeStale:!1}),c=new Set(a.protectedGenerations);return s?.currentGeneration&&c.add(s.currentGeneration),s?.previousGeneration?.generationIdentity&&c.add(s.previousGeneration.generationIdentity),{state:"managed",generationCount:o.length,logicalBytes:o.reduce((d,l)=>d+l.logicalBytes,0),...o[0]?{oldestGenerationAt:new Date(o[0].modifiedAtMs).toISOString()}:{},protectedGenerations:c.size,activeReaderLeases:a.activeLeases,malformedReaderLeases:a.malformedLeases,limits:n,...r?{lastCollection:r}:{},...a.malformedLeases>0?{reason:"malformed reader ownership evidence prevents unsafe collection"}:{}}}catch(o){return{state:"error",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,malformedReaderLeases:0,limits:n,...r?{lastCollection:r}:{},reason:o instanceof Error?o.message:String(o)}}finally{i.release()}}function cl(e={}){let t={...Vr,...e};if(!Number.isSafeInteger(t.maxGenerations)||t.maxGenerations<2)throw new Error("Local SQLite generation retention must keep at least current and previous generations.");if(!Number.isSafeInteger(t.maxLogicalBytes)||t.maxLogicalBytes<=0)throw new Error("Local SQLite generation byte retention must be a positive safe integer.");return t}function jo(e){let t=P(e);return b(t)?Qr(t,{withFileTypes:!0}).filter(r=>r.isDirectory()&&/^[a-f0-9]{64}$/.test(r.name)).map(r=>{let n=h(t,r.name),i=Ne(t,r.name),o=i?i.database.size+(i.index?.size??0)+(i.metadata?.size??0):_o(n);return{identity:r.name,path:n,logicalBytes:o,modifiedAtMs:Re(n).mtimeMs}}).sort((r,n)=>r.modifiedAtMs-n.modifiedAtMs||r.identity.localeCompare(n.identity)):[]}function _o(e){let t=0;for(let r of Qr(e,{withFileTypes:!0})){let n=h(e,r.name);r.isDirectory()?t+=_o(n):r.isFile()&&(t+=Re(n).size)}return t}function Mo(e,t){V(h(P(e),"gc.json"),t,{spacing:2,trailingNewline:!0})}function dl(e){try{let t=JSON.parse(S(h(P(e),"gc.json"),"local SQLite generation GC status"));return!t||t.state!=="within-bounds"&&t.state!=="collected"&&t.state!=="protected"&&t.state!=="deferred"&&t.state!=="error"||!Number.isSafeInteger(t.generationCount)||t.generationCount<0||!Number.isFinite(t.logicalBytes)||t.logicalBytes<0||!Number.isFinite(Date.parse(t.at))?void 0:t}catch{return}}function Yr(e,t=h(W(e),"meta.json")){let r=h(P(e),"state.json");if(!b(r))return{state:"legacy",statePath:r};let n=$(e);if(!n)return{state:"invalid",statePath:r,reason:"generation state is malformed"};try{let i=Ge(e,n.currentGeneration),o=i!==null,s=i?ll(e,t,i,n):!1,a=n.previousGeneration?b(h(W(e),n.previousGeneration.databasePath)):!0;return!s||!o||!a?{state:"drifted",statePath:r,currentMatches:s,recoveryExists:a,generation:n,reason:o?s?"retained recovery database is missing":"stable database or metadata no longer matches the published generation":"published immutable generation is missing"}:{state:"current",statePath:r,currentMatches:s,recoveryExists:a,generation:n}}catch(i){return{state:"drifted",statePath:r,currentMatches:!1,recoveryExists:!1,generation:n,reason:i instanceof Error?i.message:String(i)}}}function ll(e,t,r,n){if(n.stableMirrors&&(n.stableMirrors.databaseFileIdentity!==H(e)||n.stableMirrors.indexFileIdentity!==void 0&&n.stableMirrors.indexFileIdentity!==H(h(W(e),"index.scip")))||!Co(e,r.database))return!1;let i=h(W(e),"index.scip");if(r.index&&!Co(i,r.index))return!1;if(!r.metadata)return!b(t);if(!b(t))return!1;let o=h(P(e),r.identity,r.metadata.file);return b(o)&&K(S(t,"reindex metadata"))===K(S(o,"immutable reindex metadata"))}function Co(e,t){return b(e)&&Re(e).isFile()&&Re(e).size===t.size}function ul(e){let t=al(e.outputDb,e.outputScip,e.metaPath);return t?Go(e.outputDb,t.currentGeneration):void 0}function Xr(e,t){return{databaseFileIdentity:H(e),...b(t)?{indexFileIdentity:H(t)}:{}}}function Go(e,t){let r=h(P(e),t),n=h(r,Lo(e)),i=h(r,"meta.json");return{generationIdentity:t,databasePath:Ao(W(e),n),...b(i)?{metadataPath:Ao(W(e),i)}:{}}}function pl(e){if(b(e)){for(let t of Qr(e,{withFileTypes:!0}))if(t.isDirectory()&&t.name.endsWith(".tmp"))try{Ye(h(e,t.name),{recursive:!0,force:!0})}catch{}}}function fl(e,t,r=h(W(t),"index.scip")){let n=Kr("sha256").update("sqlite-generation-artifacts-v1\0");return n.update(Ot(t)),b(r)&&n.update(`\0${Ot(r)}`),b(e)&&n.update(`\0${K(S(e,"reindex metadata"))}`),n.digest("hex")}function Zr(e){let t=Wr(e.databasePath),r=e.indexPath?Wr(e.indexPath):void 0,n=e.metadataPath?Wr(e.metadataPath):void 0,i=e.forcedIdentity??gl(t,r,e.metadataPath),o=h(e.generationRoot,i),s=h(o,xt);if(b(s)){let d=Ne(e.generationRoot,i);if(d&&No(o,d.database,t)&&yl(o,d.index,r)&&hl(o,d.metadata,e.metadataPath))return{identity:i,directorySync:I(e.generationRoot)};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}let a=[A(e.generationRoot)];pl(e.generationRoot);let c=`${o}.${process.pid}.${Date.now()}.tmp`;Ye(c,{recursive:!0,force:!0}),il(c,{recursive:!0});try{a.push(Hr(e.databasePath,h(c,t.file))),r&&e.indexPath&&a.push(Hr(e.indexPath,h(c,r.file))),n&&e.metadataPath&&a.push(Hr(e.metadataPath,h(c,n.file)));let d=B(h(c,xt),{version:fr,identity:i,database:t,...r?{index:r}:{},...n?{metadata:n}:{}},{spacing:2,trailingNewline:!0});d.directorySync!=="not-requested"&&a.push(d.directorySync),a.push(I(c)),k(()=>Jr(c,o)),a.push(I(e.generationRoot))}finally{try{Ye(c,{recursive:!0,force:!0})}catch{}}return{identity:i,directorySync:E(...a)}}function gl(e,t,r){let n=Kr("sha256").update("sqlite-generation-artifacts-v1\0");return n.update(e.sha256),t&&n.update(`\0${t.sha256}`),r&&n.update(`\0${K(S(r,"reindex metadata"))}`),n.digest("hex")}function Wr(e){return{file:Lo(e),size:Re(e).size,sha256:Ot(e)}}function Ot(e){let t=Kr("sha256"),r=ol(e,"r"),n=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=ml(r,n);if(i===0)break;t.update(n.subarray(0,i))}}finally{nl(r)}return t.digest("hex")}function ml(e,t){let r=0;for(;r<t.length;){let n=sl(e,t,r,t.length-r,null);if(r+=n,n===0)break}return r}function Hr(e,t){return Le(e,t,{mode:292})}function No(e,t,r){let n=h(e,t.file);return t.file===r.file&&t.size===r.size&&t.sha256===r.sha256&&b(n)&&Re(n).size===t.size&&Ot(n)===t.sha256}function yl(e,t,r){return!t||!r?t===r:No(e,t,r)}function hl(e,t,r){if(!t||!r)return t===void 0&&r===void 0;let n=h(e,t.file);return b(n)&&K(S(n,"stored reindex metadata"))===K(S(r,"candidate reindex metadata"))}function Ur(e,t){k(()=>Ye(`${t}.tmp-replace`,{force:!0})),k(()=>Jr(e,`${t}.tmp-replace`)),k(()=>Jr(`${t}.tmp-replace`,t))}var sn=1,qo="CODEBASEIQ_SHARED_CACHE",xl=2,jt=JSON.stringify({cliVersion:ot,artifactCatalogVersion:Qe,postIndexAugmentationSchemaVersion:xl,sqliteGenerationStoreVersion:le,typescriptFragmentStoreVersion:Mt,typescriptOverlayStoreVersion:Ct}),an="manifest.json",wl="shared-cache.json",cn=[Br,We,Ve];function rn(e,t){if(!e.clean||!e.treeOid)return;let r=Zo(JSON.stringify({version:sn,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:jt}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:jt,generationId:r,repositoryCacheDir:ft(e.repositoryId)}}function Vo(e,t,r){if(process.env[qo]==="0")return`${qo}=0`;if(!Ht(r))return"explicit cache or database override";if(Jt(tn(t))!==Jt(pt(e))||t!==f(tn(t),"index.db"))return"index database is outside the managed worktree cache"}function im(e,t,r){if(!Ht(t))return;let n=r??Ae(e);return n?f(ft(n.repositoryId),"evidence.db"):void 0}function X(e,t=!0){let r=un(e),n;try{n=Qo(R(f(r,an),{inputKind:"shared-generation manifest",maxBytes:F}))}catch{return null}if(n.generationId!==e.generationId||n.repositoryId!==e.repositoryId||n.treeOid!==e.treeOid||n.producerIdentity!==e.producerIdentity||JSON.stringify(n.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return n;try{for(let i of n.artifacts){let o=z(r,i.path),s=Gt(o);if(!s.isFile()||s.size!==i.size||ye(o,{inputKind:"shared-generation artifact",maxBytes:T})!==i.sha256)return null}}catch{return null}return n}function om(e,t,r){if(!e.treeOid)return null;let n=Ft(t,r),i=f(ut(),"repositories",e.repositoryId),o;try{let c=en(i);if(!c.isDirectory()||c.isSymbolicLink())return null;o=Uo(i)}catch{return null}let s=f(o,"generations"),a=[];try{for(let c of Ho(s)){if(!/^[a-f0-9]{64}$/.test(c))continue;let d=f(s,c),l;try{l=en(d)}catch{continue}if(!(!l.isDirectory()||l.isSymbolicLink()))try{let u=Qo(R(f(d,an),{inputKind:"shared-generation baseline manifest",maxBytes:F}));u.generationId===c&&u.repositoryId===e.repositoryId&&u.treeOid===e.treeOid&&u.producerIdentity===jt&&vl(u.fingerprint,n)&&a.push(u)}catch{continue}}}catch{return null}a.sort((c,d)=>Date.parse(d.createdAt)-Date.parse(c.createdAt)||c.generationId.localeCompare(d.generationId));for(let c of a){let d={repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:c.fingerprint,producerIdentity:c.producerIdentity,generationId:c.generationId,repositoryCacheDir:o},l=X(d);if(l)return{snapshot:d,manifest:l}}return null}function Ko(e){let t=q(f(e.snapshot.repositoryCacheDir,"locks",`${e.snapshot.generationId}.publish.lock`));if(!t)throw new Error(`shared generation publication is already in progress for ${e.snapshot.generationId}`);try{return Pl(e)}finally{t.release()}}function Pl(e){let t=X(e.snapshot);if(t)return $o(e.snapshot,t);if(!et(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let r=zo(e.sourceCacheDir);if(!r)throw new Error("source index artifacts are incomplete");let n=Lt(e.sourceCacheDir),i=f(e.snapshot.repositoryCacheDir,"generations"),o=[A(i)],s=nr(f(i,`.tmp-${process.pid}-`));try{let a=[];for(let g of n.files){let D=z(e.sourceCacheDir,g),x=z(s,g);o.push(tt(D,x,292)),e.onPublicationStage?.("after-artifact-flushed",g);let ee=Gt(x).size;a.push({path:g,size:ee,sha256:ye(x,{inputKind:"staged shared-generation artifact",maxBytes:T})})}let c=Jo(C(f(s,"index.scip"),{inputKind:"staged shared SCIP index",maxBytes:T})).metadata?.projectRoot;if(!c)throw new Error("shared SCIP generation has no project root metadata");let d=fn(e.sourceProjectRoot);if(!be(c,d))throw new Error("shared SCIP generation root does not match its source worktree");if(zo(e.sourceCacheDir)!==r||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let l={version:sn,artifactCatalogVersion:Qe,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:c,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:a.sort((g,D)=>g.path.localeCompare(D.path))},u=B(f(s,an),l,{spacing:2,trailingNewline:!0});u.directorySync!=="not-requested"&&o.push(u.directorySync),e.onPublicationStage?.("after-manifest-flushed"),o.push(I(s)),e.onPublicationStage?.("after-staging-directory-synced");let p=un(e.snapshot);try{if(Y(p)&&!X(e.snapshot)){let g=`${p}.corrupt-${process.pid}-${Date.now()}`;k(()=>ge(p,g)),Q(g,{recursive:!0,force:!0})}k(()=>ge(s,p))}catch(g){let D=X(e.snapshot);if(D)return $o(e.snapshot,D);throw g}e.onPublicationStage?.("after-generation-renamed"),o.push(I(i)),e.onPublicationStage?.("after-generations-directory-synced");let m=E(...o);return{kind:"published",manifest:l,achievedDurability:m==="synced"?"directory-durable":"file-flushed",directorySync:m}}finally{Q(s,{recursive:!0,force:!0})}}function $o(e,t){let r=I(f(e.repositoryCacheDir,"generations"));return{kind:"existing",manifest:t,achievedDurability:r==="synced"?"directory-durable":"file-flushed",directorySync:r}}function nn(e){let t=un(e.snapshot);ve(e.targetCacheDir,{recursive:!0});let r=q(f(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!r)throw new Error("timed out waiting for another cache hydration");let n,i,o=!1;try{n=nr(f(e.targetCacheDir,".shared-hydrate-")),Al(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let d=z(t,c.path),l=z(n,c.path);if(tt(d,l),Gt(l).size!==c.size||ye(l,{inputKind:"hydrated shared-generation artifact",maxBytes:T})!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let s=fn(e.targetProjectRoot);if(s!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&Do(z(n,c.path),e.manifest.scipProjectRoot,s);if(!et(n,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=kl(e.targetCacheDir,n),o=!0,Dl(n,e.targetCacheDir,i),To({tempOutputScip:f(n,"index.scip"),tempOutputDb:f(n,"index.db"),tempMetaPath:f(n,"meta.json"),outputScip:f(e.targetCacheDir,"index.scip"),outputDb:f(e.targetCacheDir,"index.db"),metaPath:f(e.targetCacheDir,"meta.json"),now:e.now});let a=Yr(f(e.targetCacheDir,"index.db"),f(e.targetCacheDir,"meta.json"));if(a.state==="invalid"||a.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${a.reason}`);e.persistLease!==!1&&on(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(s){throw o&&i&&Fl(e.targetCacheDir,i),s}finally{n&&Q(n,{recursive:!0,force:!0}),r.release()}}function sm(e,t,r,n){let i=Vo(e,r.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=n??Ae(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return _t(o,r.cacheDir,"missed",void 0,"worktree has uncommitted changes"),{kind:"missed",reason:"worktree has uncommitted changes"};let s=t.languages??Ar(e),a=Dr(e,s,Yo(t)),c=rn(o,a);if(!c)return{kind:"missed",reason:"clean committed snapshot is unavailable"};let d=X(c);if(d)return nn({snapshot:c,manifest:d,targetCacheDir:r.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId};let l=El(c,e);return l?(d=l.manifest,nn({snapshot:c,manifest:d,targetCacheDir:r.cacheDir,targetProjectRoot:e,action:"peer-imported"}),{kind:"peer-imported",generationId:c.generationId,sourceProjectRoot:l.sourceProjectRoot}):(_t(o,r.cacheDir,"missed",void 0,"no exact shared or peer generation exists"),{kind:"missed",reason:"no exact shared or peer generation exists"})}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}function am(e,t,r,n){let i=Vo(e,r.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=n??Ae(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return _t(o,r.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let s=t.languages??Ar(e),a=Dr(e,s,Yo(t)),c=rn(o,a);if(!c)return _t(o,r.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let d=X(c);if(d)return et(r.cacheDir,e,a)?(on(c,r.cacheDir,"local-fresh"),{kind:"local-fresh"}):(nn({snapshot:c,manifest:d,targetCacheDir:r.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId});let l=ln(r.cacheDir);return!l||JSON.stringify(l.fingerprint)!==JSON.stringify(a)||JSON.stringify([...l.indexedLanguages??[]].sort())!==JSON.stringify([...s].sort())?{kind:"missed",reason:"local metadata does not match the clean worktree snapshot"}:et(r.cacheDir,e,a)?(Ko({snapshot:c,sourceCacheDir:r.cacheDir,sourceProjectRoot:e,sourceStillValid:()=>{let u=Ae(e);return(u?rn(u,a):void 0)?.generationId===c.generationId}}),on(c,r.cacheDir,"built"),{kind:"built",generationId:c.generationId}):{kind:"missed",reason:"local index artifacts are incomplete or incompatible"}}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}async function cm(e,t={}){let r=t.timeoutMs??3e4,n=t.pollMs??100,i=t.now??ce,o=i()+r,s=f(e.repositoryCacheDir,"locks"),a=f(s,`${e.generationId}.lock`),c=d=>{if(!d||typeof d!="object"||Array.isArray(d))return null;let l=d.pid;return typeof l=="number"&&Number.isSafeInteger(l)&&l>0?{pid:l}:null};for(;i()<=o;){if(X(e))return{kind:"generation-ready"};let d=It(a,{kind:"shared-generation-build",detail:{generationId:e.generationId},parseLegacy:c});if(d.kind==="acquired")return{kind:"owner",release:()=>d.lock.release()};let l=o-i();if(l<=0)break;await bl(Math.min(n,l))}return X(e)?{kind:"generation-ready"}:{kind:"timeout"}}function on(e,t,r,n=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:r,lastSeenAt:(n??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:dn(i)};return pn(e.repositoryCacheDir,o,!0),o}function dm(e,t,r=void 0){let n={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,lastAction:"overlay",lastReason:`private cache forked from shared baseline ${e.generationId}`,lastSeenAt:(r??(()=>new Date))().toISOString()},i={...n,ownershipChecksum:dn(n)};return pn(e.repositoryCacheDir,i,!0),i}function _t(e,t,r,n=void 0,i=void 0){let o={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,lastAction:r,...i?{lastReason:i}:{},lastSeenAt:(n??(()=>new Date))().toISOString()},s={...o,ownershipChecksum:dn(o)};return pn(ft(e.repositoryId),s,!1),s}function dn(e){return Zo(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:Ze(e.projectRoot),localCacheDir:Ze(e.localCacheDir)}))}function Qo(e){let t=JSON.parse(e);if(t.version!==sn||t.artifactCatalogVersion!==Qe||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==jt||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let r=new Set;for(let n of t.artifacts){if(!n||typeof n.path!="string"||typeof n.size!="number"||n.size<0||typeof n.sha256!="string"||!/^[a-f0-9]{64}$/.test(n.sha256))throw new Error("invalid shared generation artifact");if(Tt(n.path),r.has(n.path))throw new Error(`duplicate shared generation artifact: ${n.path}`);r.add(n.path)}for(let n of["index.db","index.scip","meta.json"])if(!r.has(n))throw new Error(`shared generation is missing ${n}`);return t}function tt(e,t,r=384){return Le(e,t,{mode:r})}function El(e,t){for(let r of In(t)){if(Ze(r.path)===Ze(t))continue;let n=pt(r.path),i=ln(n);if(!(!i||JSON.stringify(i.fingerprint)!==JSON.stringify(e.fingerprint)||JSON.stringify([...i.indexedLanguages??[]].sort())!==JSON.stringify([...e.fingerprint.languages].sort()))&&et(n,r.path,e.fingerprint))try{return{manifest:Ko({snapshot:e,sourceCacheDir:n,sourceProjectRoot:r.path}).manifest,sourceProjectRoot:r.path}}catch{continue}}return null}function Rl(e,t,r){ve(e,{recursive:!0}),B(f(e,wl),{version:1,repositoryId:t,worktreeId:r},{spacing:2,trailingNewline:!0})}function zo(e){try{let t=Lt(e),r=Wo("sha256");for(let n of t.files){let i=z(e,n),o=Gt(i).size;r.update(n).update("\0").update(String(o)).update("\0"),it(i,{inputKind:"source-generation artifact",maxBytes:T},s=>r.update(s)),r.update("\0")}return r.digest("hex")}catch{return null}}function ln(e){try{let t=mt(R(f(e,"meta.json"),{inputKind:"reindex metadata",maxBytes:F}));return(t.kind==="legacy"||t.kind==="supported")&&t.capabilities.publishableGeneration?t.metadata:void 0}catch{return}}function Yo(e){return{pnpmWorkspaces:e.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.indexer?.typescript?.projectMode,typescriptProjects:e.indexer?.typescript?.projects,clojureConfigPath:e.indexer?.clojure?.configPath}}function vl(e,t){let r=Ft(e.languages,e);return JSON.stringify(r)===JSON.stringify(t)}function un(e){return f(e.repositoryCacheDir,"generations",e.generationId)}function pn(e,t,r){let n=ci(e,{waitMs:5e3});if(!n)throw new Error("repository cache cleanup is busy");try{if(r){let o=t.activeGenerationId??t.baseGenerationId;if(!o||!Y(f(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=f(e,"worktrees");ve(i,{recursive:!0}),B(f(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),Rl(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{n.release()}}function kl(e,t){let r=f(t,".rollback"),n=new Map,i=new Map;ve(r,{recursive:!0});for(let a of["index.scip","index.db","meta.json"]){let c=f(e,a),d=Y(c);n.set(a,d),d&&tt(c,f(r,"stable",a))}for(let a of cn){let c=f(e,a),d=Y(c);if(d){let l=en(c);if(!l.isDirectory()||l.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${a}`)}i.set(a,d)}let o=f(e,je),s=Y(o);return s&&Xo(o,f(r,"sqlite-generations")),{root:r,stableFiles:n,managedDirectories:i,generationStoreExisted:s}}function Dl(e,t,r){for(let n of cn){let i=f(t,n);if(r.managedDirectories.get(n)){let s=f(r.root,"managed",n);ve(tn(s),{recursive:!0}),k(()=>ge(i,s))}let o=f(e,n);Y(o)&&k(()=>ge(o,i))}}function Fl(e,t){for(let i of cn){let o=f(e,i),s=f(t.root,"managed",i);t.managedDirectories.get(i)?Y(s)&&(Q(o,{recursive:!0,force:!0}),k(()=>ge(s,o))):Q(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let s=f(e,i);if(!o){Q(s,{force:!0});continue}let a=`${s}.shared-restore-${Sl()}`;tt(f(t.root,"stable",i),a),k(()=>Q(s,{force:!0})),k(()=>ge(a,s))}let r=f(e,je);Q(r,{recursive:!0,force:!0});let n=f(t.root,"sqlite-generations");t.generationStoreExisted&&Y(n)&&k(()=>ge(n,r))}function Xo(e,t){ve(t,{recursive:!0});for(let r of Ho(e,{withFileTypes:!0})){let n=f(e,r.name),i=f(t,r.name);if(r.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${n}`);r.isDirectory()?Xo(n,i):r.isFile()&&tt(n,i)}}function Al(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function et(e,t,r,n=!0,i=!0){try{let o=ln(e);if(!o||JSON.stringify(o.fingerprint)!==JSON.stringify(r)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...r.languages].sort()))return Xe("source validation rejected metadata"),!1;let s=Lt(e),a=Yr(f(e,"index.db"),f(e,"meta.json"));if(n?a.state!=="current":a.state==="invalid"||a.state==="drifted")return Xe(`source validation rejected SQLite generation state ${a.state}`),!1;let c=new Il(ht(f(e,"index.db")),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let d=fn(t),u=(i?s.files.filter(p=>p.endsWith(".scip")):["index.scip"]).every(p=>{let m=Jo(C(z(e,p),{inputKind:"shared SCIP validation artifact",maxBytes:T})).metadata?.projectRoot,g=m!==void 0&&be(m,d);return g||Xe(`source validation rejected SCIP root for ${p}: ${String(m)}`),g});return u||Xe("source validation rejected SCIP project roots"),u}catch(o){return Xe(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function Xe(e){process.env.CODEBASEIQ_DEBUG&&console.error(`shared-cache: ${e}`)}function fn(e){try{return Bo(Uo(e)).href}catch{return Bo(Ze(e)).href}}function Zo(e){return Wo("sha256").update(e).digest("hex")}function um(e){return typeof e=="object"&&e!==null}function pm(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null}import{createHash as Ml,randomUUID as is}from"crypto";import{existsSync as Fe,lstatSync as nt,readdirSync as De,renameSync as os,rmSync as Z}from"fs";import{basename as gn,dirname as Cl,join as w}from"path";function Nt(e){return Array.isArray(e)?`[${e.map(Nt).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Nt(r)}`).join(",")}}`:JSON.stringify(e)}var Ll=1,Tl=Object.freeze({maxItems:1024,maxBytes:512*1024*1024,maxItemBytes:64*1024*1024,maxBatch:16,claimLeaseMs:5*6e4,responseRetentionMs:10*6e4,deadLetterRetentionMs:1440*6e4,temporaryRetentionMs:6e4,cleanupBatch:64}),ke=class extends Error{constructor(r,n,i,o){let s=r==="item-too-large"?`request is ${o} bytes; per-item limit is ${i.maxItemBytes}`:r==="item-capacity"?`mailbox has ${n.totalItems} retained items; limit is ${i.maxItems}`:r==="byte-capacity"?`mailbox retains ${n.totalBytes} bytes and the request adds ${o}; limit is ${i.maxBytes}`:"another writer held the admission coordinator through the bounded wait";super(`Mailbox backpressure: ${s}. Retry after the service drains or expires retained work.`);this.code=r;this.status=n;this.limits=i;this.attemptedBytes=o;this.name="MailboxBackpressureError"}code;status;limits;attemptedBytes},Ol=".owner.json",jl={isProcessAlive:()=>!0,readProcessIdentity:()=>null};function Pm(e){return{rootDir:e,pendingDir:w(e,"pending"),inflightDir:w(e,"inflight"),responseDir:w(e,"responses"),deadLetterDir:w(e,"dead-letter"),legacyRequestDir:w(e,"requests")}}function _l(e={}){let t={...Tl,...e};for(let[r,n]of Object.entries(t))if(!Number.isFinite(n)||n<=0||!Number.isInteger(n))throw new Error(`Mailbox limit ${r} must be a positive integer.`);return t}function ss(e){let t=[e.pendingDir,e.inflightDir,e.responseDir,e.deadLetterDir,e.legacyRequestDir].map(r=>A(r));return E(...t)}function Em(e,t){return Ml("sha256").update(Nt({namespace:e,payload:t})).digest("hex")}function Gl(e){if(!/^[a-f0-9]{64}$/.test(e))throw new Error("Mailbox operation keys must be lowercase SHA-256 identities.");return`op-${e}`}function Rm(e,t,r={}){let n=_l(r.limits),i=r.nowMs??Date.now(),o=ss(e);return Ul(t),Bl(e,n,r.admissionLockTimeoutMs??2e3,r.monotonicNow??ce,()=>{Nl(e,i,n);let s=w(e.pendingDir,`${t.id}.json`),a=w(e.responseDir,`${t.id}.json`),c=es(e,t.id);if(c){let p=ts(c,t.operationKey,t.id);return{disposition:"duplicate",requestId:t.id,responsePath:a,authoritativeDeadlineAtMs:p.deadlineAtMs??t.deadlineAtMs}}let d=`${JSON.stringify(t)}
|
|
86
|
-
`,l=Buffer.byteLength(d),u=as(e);if(l>n.maxItemBytes)throw new ke("item-too-large",u,n,l);if(u.totalItems+1>n.maxItems)throw new ke("item-capacity",u,n,l);if(u.totalBytes+l>n.maxBytes)throw new ke("byte-capacity",u,n,l);r.onBeforePublish?.();try{let p=tr(s,d,{durability:"durable"}),m=E(o,p.directorySync);return{disposition:"accepted",requestId:t.id,responsePath:a,authoritativeDeadlineAtMs:t.deadlineAtMs,achievedDurability:m==="synced"?"directory-durable":"file-flushed",directorySync:m}}catch(p){if(p.code!=="EEXIST")throw p;let m=es(e,t.id);if(!m)throw p;let g=ts(m,t.operationKey,t.id);return{disposition:"duplicate",requestId:t.id,responsePath:a,authoritativeDeadlineAtMs:g.deadlineAtMs??t.deadlineAtMs}}})}function Nl(e,t,r,n=jl){let i={reclaimed:0,completedClaimsRemoved:0,responsesRemoved:0,deadLettersRemoved:0,temporaryFilesRemoved:0},o=r.cleanupBatch;for(let s of yn(e.inflightDir)){if(o<=0)break;let a=w(e.responseDir,`${s.requestId}.json`);if(Fe(a)){Z(s.path,{force:!0}),i.completedClaimsRemoved++,o--;continue}if(s.claimExpiresAtMs>t||Wl(e,s.ownerId,n)!=="dead")continue;let c=w(e.pendingDir,s.originalFile);try{os(s.path,c),i.reclaimed++}catch(d){if(d.code!=="EEXIST")throw d;Z(s.path,{force:!0})}I(Cl(s.path)),I(e.pendingDir),o--}o=rs(e.responseDir,o,(s,a)=>a+r.responseRetentionMs,t,()=>{i.responsesRemoved++}),o=rs(e.deadLetterDir,o,(s,a)=>a+r.deadLetterRetentionMs,t,()=>{i.deadLettersRemoved++});for(let s of[e.pendingDir,e.inflightDir,e.responseDir,e.deadLetterDir,e.legacyRequestDir]){if(o<=0)break;for(let a of cs(s)){if(o<=0)break;gn(a).includes(".tmp-")&&(nt(a).mtimeMs+r.temporaryRetentionMs>t||(Z(a,{force:!0}),i.temporaryFilesRemoved++,o--))}}return Jl(e.inflightDir),i}function as(e){ss(e);let t=[...rt(e.pendingDir).map(c=>({path:c,pending:!0})),...rt(e.legacyRequestDir).map(c=>({path:c,pending:!0}))],r=yn(e.inflightDir).map(c=>({path:c.path,pending:!1})),n=rt(e.responseDir).map(c=>({path:c,pending:!1})),i=rt(e.deadLetterDir).map(c=>({path:c,pending:!1})),o=[...t,...r,...n,...i],s=0,a;for(let c of t){let d=hn(c.path);if(!d){s++;continue}let l=d.enqueuedAtMs??nt(c.path).mtimeMs;a=a===void 0?l:Math.min(a,l)}return{pending:t.length,inflight:r.length,responses:n.length,deadLetters:i.length,invalid:s,totalItems:o.length,totalBytes:o.reduce((c,d)=>c+Vl(d.path),0),...a===void 0?{}:{oldestPendingAt:new Date(a).toISOString()}}}function Bl(e,t,r,n,i){let o=w(e.rootDir,".admission.lock"),s=`${process.pid}-${is()}`,a=n()+Math.max(0,r);for(;!ql(e.rootDir,o,s);){if($l(o),n()>=a)throw new ke("admission-busy",as(e),t,0);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,5)}try{return i()}finally{try{mn(o).ownerToken===s&&(Z(o,{recursive:!0,force:!0}),I(e.rootDir))}catch{}}}function ql(e,t,r){let n=`${JSON.stringify({ownerToken:r,pid:process.pid,acquiredAtMs:Date.now()})}
|
|
87
|
-
`;try{return tr(t,n,{durability:"durable"}),!0}catch(i){if(i.code==="EEXIST")return!1;try{mn(t).ownerToken===r&&(Z(t,{force:!0}),I(e))}catch{}throw i}}function $l(e){let t=null;try{let n=mn(e);typeof n.ownerToken=="string"&&Number.isSafeInteger(n.pid)&&Number(n.pid)>0&&(t=Number(n.pid))}catch{}if(t===null||zl(t))return;let r=`${e}.stale-${is()}`;try{os(e,r)}catch(n){let i=n.code;if(i==="ENOENT"||i==="EEXIST")return;throw n}Z(r,{recursive:!0,force:!0})}function mn(e){try{return JSON.parse(S(e,"mailbox lock record"))}catch(t){if(t.code!=="EISDIR"&&!(t instanceof wn&&t.reason==="not-regular"))throw t;return JSON.parse(S(w(e,"owner.json"),"mailbox lock owner record"))}}function zl(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="EPERM"||r!=="ESRCH"}}function Wl(e,t,r){let n=Hl(w(e.inflightDir,ds(t),Ol));if(!n)return"unknown";if(!r.isProcessAlive(n.pid))return"dead";if(!n.processIdentity)return"live";let i=r.readProcessIdentity(n.pid);return i?re(n.processIdentity,i)?"live":"dead":"unknown"}function Hl(e){try{let t=JSON.parse(S(e,"mailbox owner record"));if(t.version!==1||typeof t.ownerId!="string"||!t.ownerId||typeof t.pid!="number"||!Number.isSafeInteger(t.pid)||t.pid<=0)return null;let r=t.processIdentity===void 0?null:he(t.processIdentity);return t.processIdentity!==void 0&&(!r||r.pid!==t.pid)?null:{version:1,ownerId:t.ownerId,pid:t.pid,...r?{processIdentity:r}:{}}}catch{return null}}function es(e,t){for(let r of[w(e.pendingDir,`${t}.json`),w(e.legacyRequestDir,`${t}.json`),w(e.responseDir,`${t}.json`)])if(Fe(r))return r;for(let r of yn(e.inflightDir))if(r.requestId===t)return r.path;return null}function ts(e,t,r){let n=hn(e);if(!n||n.operationKey!==t)throw new Error(`Mailbox operation ${r} conflicts with an existing retained record.`);return n}function Ul(e){if(e.mailboxVersion!==Ll||e.id!==Gl(e.operationKey)||!e.clientId.trim()||!Number.isFinite(e.enqueuedAtMs)||!Number.isFinite(e.deadlineAtMs)||e.deadlineAtMs<e.enqueuedAtMs)throw new Error("Mailbox request has an invalid lifecycle identity.")}function yn(e){if(!Fe(e))return[];let t=[];for(let r of De(e,{withFileTypes:!0})){if(!r.isDirectory())continue;let n=ns(r.name);if(n===null)continue;let i=w(e,r.name);for(let o of De(i,{withFileTypes:!0})){if(!o.isFile()||!o.name.endsWith(".claim"))continue;let s=/^(.*)\.(\d+)\.claim$/.exec(o.name);if(!s)continue;let a=ns(s[1]),c=Number(s[2]);if(a===null||gn(a)!==a||!a.endsWith(".json")||!Number.isSafeInteger(c))continue;let d=w(i,o.name),l=hn(d)??{id:gn(a,".json")},u=nt(d);t.push({requestId:l.id,ownerId:n,path:d,originalFile:a,claimedAtMs:u.mtimeMs,claimExpiresAtMs:c,byteLength:u.size,...l.operationKey?{operationKey:l.operationKey}:{},...l.clientId?{clientId:l.clientId}:{},...l.enqueuedAtMs===void 0?{}:{enqueuedAtMs:l.enqueuedAtMs},...l.deadlineAtMs===void 0?{}:{deadlineAtMs:l.deadlineAtMs},legacy:l.operationKey===void 0})}}return t.sort((r,n)=>r.claimedAtMs-n.claimedAtMs||r.path.localeCompare(n.path))}function hn(e){try{let t=JSON.parse(S(e,"mailbox record"));return typeof t.id!="string"||!t.id?null:{id:t.id,...typeof t.operationKey=="string"?{operationKey:t.operationKey}:{},...typeof t.clientId=="string"?{clientId:t.clientId}:{},...typeof t.enqueuedAtMs=="number"?{enqueuedAtMs:t.enqueuedAtMs}:{},...typeof t.deadlineAtMs=="number"?{deadlineAtMs:t.deadlineAtMs}:{}}}catch{return null}}function rs(e,t,r,n,i){for(let o of rt(e)){if(t<=0)break;let s=nt(o);r(o,s.mtimeMs)>n||(Z(o,{force:!0}),i(),t--)}return t}function rt(e){return Fe(e)?De(e,{withFileTypes:!0}).filter(t=>t.isFile()).map(t=>w(e,t.name)).sort():[]}function cs(e){if(!Fe(e))return[];let t=[];for(let r of De(e,{withFileTypes:!0})){let n=w(e,r.name);r.isFile()?t.push(n):r.isDirectory()&&t.push(...cs(n))}return t.sort()}function Jl(e){if(Fe(e))for(let t of De(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let r=w(e,t.name);De(r).some(n=>n.endsWith(".claim"))||Z(r,{recursive:!0,force:!0})}}function Vl(e){try{return nt(e).size}catch{return 0}}function ds(e){return Buffer.from(e,"utf8").toString("base64url")}function ns(e){try{let t=Buffer.from(e,"base64url").toString("utf8");return ds(t)===e?t:null}catch{return null}}export{ie as a,Se as b,A as c,I as d,E as e,v as f,qt as g,nu as h,iu as i,O as j,j as k,ot as l,Ce as m,Wt as n,ut as o,pt as p,Ht as q,mu as r,yu as s,Jt as t,ht as u,nr as v,Ju as w,Vu as x,Ku as y,Vt as z,Su as A,bu as B,Bs as C,ae as D,mt as E,Ru as F,Un as G,$s as H,vu as I,ce as J,Yu as K,St as L,ni as M,bt as N,It as O,Ie as P,Da as Q,ci as R,q as S,pp as T,k as U,er as V,tr as W,V as X,B as Y,Ep as Z,Ii as _,jp as $,Be as aa,Ci as ba,Li as ca,Ti as da,bc as ea,Oi as fa,zp as ga,Wp as ha,Hp as ia,Pt as ja,Bc as ka,$e as la,sd as ma,Ui as na,ad as oa,wf as pa,kr as qa,Pf as ra,cd as sa,dd as ta,Dr as ua,Ar as va,To as wa,al as xa,Dg as ya,Fg as za,Yr as Aa,um as Ba,pm as Ca,Nt as Da,Ll as Ea,Pm as Fa,Em as Ga,Gl as Ha,Rm as Ia,jf as Ja,_f as Ka,Gf as La,Nf as Ma,Bf as Na,Vf as Oa,Kf as Pa,Qf as Qa,Yf as Ra,Eo as Sa,gg as Ta,mg as Ua,rn as Va,Vo as Wa,im as Xa,X as Ya,om as Za,Ko as _a,nn as $a,sm as ab,am as bb,cm as cb,on as db,dm as eb,dn as fb};
|
|
88
|
-
//# sourceMappingURL=chunk-5T44HG5Y.js.map
|